Merge from Chromium at DEPS revision r210036

This commit was generated by merge_to_master.py.

Change-Id: Ib2112ed87a48d7a6d9c0563ba71850716d1475ef
diff --git a/Source/core/Init.cpp b/Source/core/Init.cpp
index 3b6fd1d..6f1ff40 100644
--- a/Source/core/Init.cpp
+++ b/Source/core/Init.cpp
@@ -39,7 +39,8 @@
 #include "XMLNSNames.h"
 #include "XMLNames.h"
 #include "core/css/MediaFeatureNames.h"
-#include "core/dom/Node.h"
+#include "core/platform/EventTracer.h"
+#include "core/platform/Partitions.h"
 #include "wtf/text/StringStatics.h"
 
 namespace WebCore {
@@ -62,12 +63,15 @@
     MediaFeatureNames::init();
     WTF::StringStatics::init();
     QualifiedName::init();
-    Node::init();
+#if ENABLE(PARTITION_ALLOC)
+    Partitions::init();
+#endif
+    EventTracer::initialize();
 }
 
 void shutdown()
 {
-    Node::shutdown();
+    Partitions::shutdown();
 }
 
 } // namespace WebCore
diff --git a/Source/core/OWNERS b/Source/core/OWNERS
index aa6bdd7..b98c2fb 100644
--- a/Source/core/OWNERS
+++ b/Source/core/OWNERS
@@ -3,6 +3,7 @@
 alexis.menard@intel.com
 apavlov@chromium.org
 arv@chromium.org
+ch.dumez@sisa.samsung.com
 crogers@google.com
 darin@chromium.org
 dglazkov@chromium.org
diff --git a/Source/core/Resources/pagepopups/calendarPicker.css b/Source/core/Resources/pagepopups/calendarPicker.css
index 9255f95..bab88b5 100644
--- a/Source/core/Resources/pagepopups/calendarPicker.css
+++ b/Source/core/Resources/pagepopups/calendarPicker.css
@@ -121,6 +121,9 @@
 .week-day-label {
     text-align: center;
     display: inline-block;
+    line-height: 23px;
+    padding-top: 1px;
+    box-sizing: padding-box;
 }
 
 .week-number-label {
@@ -132,7 +135,6 @@
     background-color: #f5f5f5;
     border-bottom: 1px solid #bfbfbf;
     height: 24px;
-    line-height: 24px;
 }
 
 .calendar-picker {
diff --git a/Source/core/Resources/pagepopups/calendarPicker.js b/Source/core/Resources/pagepopups/calendarPicker.js
index d59102b..5111f3d 100644
--- a/Source/core/Resources/pagepopups/calendarPicker.js
+++ b/Source/core/Resources/pagepopups/calendarPicker.js
@@ -3011,7 +3011,7 @@
     this.element.classList.add(DayCell.ClassNameDayCell);
     this.element.style.width = DayCell.Width + "px";
     this.element.style.height = DayCell.Height + "px";
-    this.element.style.lineHeight = (DayCell.Height - DayCell.BorderWidth * 2) + "px";
+    this.element.style.lineHeight = (DayCell.Height - DayCell.PaddingSize * 2) + "px";
     /**
      * @type {?Day}
      */
@@ -3022,7 +3022,7 @@
 
 DayCell.Width = 34;
 DayCell.Height = hasInaccuratePointingDevice() ? 34 : 20;
-DayCell.BorderWidth = 1;
+DayCell.PaddingSize = 1;
 DayCell.ClassNameDayCell = "day-cell";
 DayCell.ClassNameHighlighted = "highlighted";
 DayCell.ClassNameDisabled = "disabled";
@@ -3107,8 +3107,9 @@
 function WeekNumberCell() {
     ListCell.call(this);
     this.element.classList.add(WeekNumberCell.ClassNameWeekNumberCell);
-    this.element.style.width = (WeekNumberCell.Width - WeekNumberCell.RightBorderWidth) + "px";
+    this.element.style.width = (WeekNumberCell.Width - WeekNumberCell.SeparatorWidth) + "px";
     this.element.style.height = WeekNumberCell.Height + "px";
+    this.element.style.lineHeight = (WeekNumberCell.Height - WeekNumberCell.PaddingSize * 2) + "px";
     /**
      * @type {?Week}
      */
@@ -3119,7 +3120,8 @@
 
 WeekNumberCell.Width = 48;
 WeekNumberCell.Height = DayCell.Height;
-WeekNumberCell.RightBorderWidth = 1;
+WeekNumberCell.SeparatorWidth = 1;
+WeekNumberCell.PaddingSize = 1;
 WeekNumberCell.ClassNameWeekNumberCell = "week-number-cell";
 WeekNumberCell.ClassNameHighlighted = "highlighted";
 WeekNumberCell.ClassNameDisabled = "disabled";
diff --git a/Source/core/accessibility/AXObjectCache.cpp b/Source/core/accessibility/AXObjectCache.cpp
index c2d3c26..17fb379 100644
--- a/Source/core/accessibility/AXObjectCache.cpp
+++ b/Source/core/accessibility/AXObjectCache.cpp
@@ -550,6 +550,19 @@
     m_idsInUse.remove(objID);
 }
 
+void AXObjectCache::selectionChanged(Node* node)
+{
+    // Find the nearest ancestor that already has an accessibility object, since we
+    // might be in the middle of a layout.
+    while (node) {
+        if (AccessibilityObject* obj = get(node)) {
+            obj->selectionChanged();
+            return;
+        }
+        node = node->parentNode();
+    }
+}
+
 void AXObjectCache::textChanged(Node* node)
 {
     textChanged(getOrCreate(node));
diff --git a/Source/core/accessibility/AXObjectCache.h b/Source/core/accessibility/AXObjectCache.h
index 20ac1c5..5078992 100644
--- a/Source/core/accessibility/AXObjectCache.h
+++ b/Source/core/accessibility/AXObjectCache.h
@@ -26,13 +26,12 @@
 #ifndef AXObjectCache_h
 #define AXObjectCache_h
 
-#include <limits.h>
 #include "core/accessibility/AccessibilityObject.h"
 #include "core/platform/Timer.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/RefPtr.h>
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/HashSet.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
@@ -110,6 +109,7 @@
     void checkedStateChanged(Node*);
     void selectedChildrenChanged(Node*);
     void selectedChildrenChanged(RenderObject*);
+    void selectionChanged(Node*);
     // Called by a node when text or a text equivalent (e.g. alt) attribute is changed.
     void textChanged(Node*);
     void textChanged(RenderObject*);
diff --git a/Source/core/accessibility/AccessibilityListBoxOption.cpp b/Source/core/accessibility/AccessibilityListBoxOption.cpp
index 4956237..6a413c2 100644
--- a/Source/core/accessibility/AccessibilityListBoxOption.cpp
+++ b/Source/core/accessibility/AccessibilityListBoxOption.cpp
@@ -80,7 +80,7 @@
     if (!m_optionElement->hasTagName(optionTag))
         return false;
     
-    return static_cast<HTMLOptionElement*>(m_optionElement)->selected();
+    return toHTMLOptionElement(m_optionElement)->selected();
 }
 
 bool AccessibilityListBoxOption::isSelectedOptionActive() const
@@ -153,7 +153,7 @@
         return ariaLabel;
     
     if (m_optionElement->hasTagName(optionTag))
-        return static_cast<HTMLOptionElement*>(m_optionElement)->text();
+        return toHTMLOptionElement(m_optionElement)->text();
     
     if (m_optionElement->hasTagName(optgroupTag))
         return static_cast<HTMLOptGroupElement*>(m_optionElement)->groupLabelText();
@@ -199,7 +199,7 @@
         return 0;
     
     if (m_optionElement->hasTagName(optionTag))
-        return static_cast<HTMLOptionElement*>(m_optionElement)->ownerSelectElement();
+        return toHTMLOptionElement(m_optionElement)->ownerSelectElement();
     
     if (m_optionElement->hasTagName(optgroupTag))
         return static_cast<HTMLOptGroupElement*>(m_optionElement)->ownerSelectElement();
diff --git a/Source/core/accessibility/AccessibilityMenuListOption.cpp b/Source/core/accessibility/AccessibilityMenuListOption.cpp
index 1b1573d..14821b3 100644
--- a/Source/core/accessibility/AccessibilityMenuListOption.cpp
+++ b/Source/core/accessibility/AccessibilityMenuListOption.cpp
@@ -51,7 +51,7 @@
 {
     // isDisabledFormControl() returns true if the parent <select> element is disabled,
     // which we don't want.
-    return !static_cast<HTMLOptionElement*>(m_element.get())->ownElementDisabled();
+    return !toHTMLOptionElement(m_element.get())->ownElementDisabled();
 }
 
 bool AccessibilityMenuListOption::isVisible() const
@@ -72,7 +72,7 @@
 
 bool AccessibilityMenuListOption::isSelected() const
 {
-    return static_cast<HTMLOptionElement*>(m_element.get())->selected();
+    return toHTMLOptionElement(m_element.get())->selected();
 }
 
 void AccessibilityMenuListOption::setSelected(bool b)
@@ -80,7 +80,7 @@
     if (!canSetSelectedAttribute())
         return;
 
-    static_cast<HTMLOptionElement*>(m_element.get())->setSelected(b);
+    toHTMLOptionElement(m_element.get())->setSelected(b);
 }
 
 bool AccessibilityMenuListOption::canSetSelectedAttribute() const
@@ -106,7 +106,7 @@
 
 String AccessibilityMenuListOption::stringValue() const
 {
-    return static_cast<HTMLOptionElement*>(m_element.get())->text();
+    return toHTMLOptionElement(m_element.get())->text();
 }
 
 } // namespace WebCore
diff --git a/Source/core/accessibility/AccessibilityNodeObject.cpp b/Source/core/accessibility/AccessibilityNodeObject.cpp
index cf524cf..1cc5f00 100644
--- a/Source/core/accessibility/AccessibilityNodeObject.cpp
+++ b/Source/core/accessibility/AccessibilityNodeObject.cpp
@@ -33,15 +33,12 @@
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/Text.h"
 #include "core/dom/UserGestureIndicator.h"
-#include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLFrameElementBase.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLLabelElement.h"
 #include "core/html/HTMLSelectElement.h"
 #include "core/html/HTMLTextAreaElement.h"
-#include <wtf/StdLibExtras.h>
-#include <wtf/text/StringBuilder.h>
-#include <wtf/unicode/CharacterNames.h>
+#include "wtf/text/StringBuilder.h"
 
 using namespace std;
 
@@ -595,6 +592,20 @@
     return false;
 }
 
+bool AccessibilityNodeObject::isNonNativeTextControl() const
+{
+    if (isNativeTextControl())
+        return false;
+
+    if (hasContentEditableAttributeSet())
+        return true;
+
+    if (isARIATextControl())
+        return true;
+
+    return false;
+}
+
 bool AccessibilityNodeObject::isPasswordField() const
 {
     Node* node = this->node();
@@ -686,7 +697,7 @@
         return true;
 
     if (node->hasTagName(textareaTag))
-        return static_cast<HTMLTextAreaElement*>(node)->isReadOnly();
+        return toHTMLFormControlElement(node)->isReadOnly();
 
     if (node->hasTagName(inputTag)) {
         HTMLInputElement* input = toHTMLInputElement(node);
@@ -704,7 +715,7 @@
 
     Node* n = this->node();
     if (n && (n->isElementNode() && toElement(n)->isFormControlElement()))
-        return static_cast<HTMLFormControlElement*>(n)->isRequired();
+        return toHTMLFormControlElement(n)->isRequired();
 
     return false;
 }
@@ -819,12 +830,8 @@
     if (!node)
         return String();
 
-    if (isNativeTextControl()) {
-        if (node->hasTagName(textareaTag))
-            return static_cast<HTMLTextAreaElement*>(node)->value();
-        if (node->hasTagName(inputTag))
-            return toHTMLInputElement(node)->value();
-    }
+    if (isNativeTextControl() && (node->hasTagName(textareaTag) || node->hasTagName(inputTag)))
+        return toHTMLTextFormControlElement(node)->value();
 
     if (!node->isElementNode())
         return String();
@@ -1414,12 +1421,44 @@
         if (parent->supportsARIALiveRegion())
             axObjectCache()->postNotification(parent, parent->document(), AXObjectCache::AXLiveRegionChanged, true);
 
-        // If this element is an ARIA text control, notify the AT of changes.
-        if (parent->isARIATextControl() && !parent->isNativeTextControl() && !parent->node()->rendererIsEditable())
+        // If this element is an ARIA text box or content editable, post a "value changed" notification on it
+        // so that it behaves just like a native input element or textarea.
+        if (isNonNativeTextControl())
             axObjectCache()->postNotification(parent, parent->document(), AXObjectCache::AXValueChanged, true);
     }
 }
 
+void AccessibilityNodeObject::selectionChanged()
+{
+    // When the selection changes, post the notification on the first ancestor that's an
+    // ARIA text box, or that's marked as contentEditable, otherwise post the notification
+    // on the web area.
+    if (isNonNativeTextControl() || isWebArea())
+        axObjectCache()->postNotification(this, document(), AXObjectCache::AXSelectedTextChanged, true);
+    else
+        AccessibilityObject::selectionChanged(); // Calls selectionChanged on parent.
+}
+
+void AccessibilityNodeObject::textChanged()
+{
+    // If this element supports ARIA live regions, or is part of a region with an ARIA editable role,
+    // then notify the AT of changes.
+    AXObjectCache* cache = axObjectCache();
+    for (Node* parentNode = node(); parentNode; parentNode = parentNode->parentNode()) {
+        AccessibilityObject* parent = cache->get(parentNode);
+        if (!parent)
+            continue;
+
+        if (parent->supportsARIALiveRegion())
+            cache->postNotification(parentNode, AXObjectCache::AXLiveRegionChanged, true);
+
+        // If this element is an ARIA text box or content editable, post a "value changed" notification on it
+        // so that it behaves just like a native input element or textarea.
+        if (parent->isNonNativeTextControl())
+            cache->postNotification(parentNode, AXObjectCache::AXValueChanged, true);
+    }
+}
+
 void AccessibilityNodeObject::updateAccessibilityRole()
 {
     bool ignoredStatus = accessibilityIsIgnored();
@@ -1456,10 +1495,10 @@
     Node* owner = document->ownerElement();
     if (owner) {
         if (owner->hasTagName(frameTag) || owner->hasTagName(iframeTag)) {
-            const AtomicString& title = static_cast<HTMLFrameElementBase*>(owner)->getAttribute(titleAttr);
+            const AtomicString& title = toElement(owner)->getAttribute(titleAttr);
             if (!title.isEmpty())
                 return title;
-            return static_cast<HTMLFrameElementBase*>(owner)->getNameAttribute();
+            return toElement(owner)->getNameAttribute();
         }
         if (owner->isHTMLElement())
             return toHTMLElement(owner)->getNameAttribute();
diff --git a/Source/core/accessibility/AccessibilityNodeObject.h b/Source/core/accessibility/AccessibilityNodeObject.h
index 6dd849a..df735b1 100644
--- a/Source/core/accessibility/AccessibilityNodeObject.h
+++ b/Source/core/accessibility/AccessibilityNodeObject.h
@@ -118,6 +118,7 @@
     virtual bool isMultiSelectable() const OVERRIDE;
     bool isNativeImage() const;
     virtual bool isNativeTextControl() const OVERRIDE;
+    virtual bool isNonNativeTextControl() const OVERRIDE;
     virtual bool isPasswordField() const OVERRIDE;
     virtual bool isProgressIndicator() const OVERRIDE;
     virtual bool isSlider() const OVERRIDE;
@@ -189,6 +190,8 @@
 
     // Notifications that this object may have changed.
     virtual void childrenChanged() OVERRIDE;
+    virtual void selectionChanged() OVERRIDE;
+    virtual void textChanged() OVERRIDE;
     virtual void updateAccessibilityRole() OVERRIDE;
 
 private:
diff --git a/Source/core/accessibility/AccessibilityObject.cpp b/Source/core/accessibility/AccessibilityObject.cpp
index 57e5440..4ca0313 100644
--- a/Source/core/accessibility/AccessibilityObject.cpp
+++ b/Source/core/accessibility/AccessibilityObject.cpp
@@ -30,24 +30,16 @@
 #include "core/accessibility/AccessibilityObject.h"
 
 #include "core/accessibility/AXObjectCache.h"
-#include "core/accessibility/AccessibilityTable.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/UserGestureIndicator.h"
-#include "core/editing/Editor.h"
-#include "core/editing/FrameSelection.h"
-#include "core/editing/RenderedPosition.h"
-#include "core/editing/TextCheckingHelper.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
 #include "core/platform/LocalizedStrings.h"
-#include "core/platform/text/TextCheckerClient.h"
 #include "core/rendering/RenderListItem.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
-#include <wtf/StdLibExtras.h>
-#include <wtf/text/StringBuilder.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/unicode/CharacterNames.h>
+#include "wtf/StdLibExtras.h"
+#include "wtf/text/WTFString.h"
 
 using namespace std;
 
@@ -816,6 +808,12 @@
     }
 }
 
+void AccessibilityObject::selectionChanged()
+{
+    if (AccessibilityObject* parent = parentObjectIfExists())
+        parent->selectionChanged();
+}
+
 static VisiblePosition startOfStyleRange(const VisiblePosition& visiblePos)
 {
     RenderObject* renderer = visiblePos.deepEquivalent().deprecatedNode()->renderer();
diff --git a/Source/core/accessibility/AccessibilityObject.h b/Source/core/accessibility/AccessibilityObject.h
index 73c8f38..83287ca 100644
--- a/Source/core/accessibility/AccessibilityObject.h
+++ b/Source/core/accessibility/AccessibilityObject.h
@@ -32,12 +32,11 @@
 
 #include "core/editing/TextIterator.h"
 #include "core/editing/VisiblePosition.h"
-#include "core/editing/VisibleSelection.h"
 #include "core/platform/graphics/FloatQuad.h"
 #include "core/platform/graphics/LayoutRect.h"
-#include <wtf/Forward.h>
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -319,7 +318,8 @@
     bool isMenuRelated() const;
     virtual bool isMockObject() const { return false; }
     virtual bool isNativeSpinButton() const { return false; }
-    virtual bool isNativeTextControl() const { return false; }
+    virtual bool isNativeTextControl() const { return false; } // input or textarea
+    virtual bool isNonNativeTextControl() const { return false; } // contenteditable or role=textbox
     virtual bool isPasswordField() const { return false; }
     virtual bool isProgressIndicator() const { return false; }
     bool isRadioButton() const { return roleValue() == RadioButtonRole; }
@@ -515,6 +515,7 @@
     virtual void handleActiveDescendantChanged() { }
     virtual void handleAriaExpandedChanged() { }
     void notifyIfIgnoredValueChanged();
+    virtual void selectionChanged();
     virtual void textChanged() { }
     virtual void updateAccessibilityRole() { }
 
diff --git a/Source/core/accessibility/AccessibilityRenderObject.cpp b/Source/core/accessibility/AccessibilityRenderObject.cpp
index 91d22f9..cdb352c 100644
--- a/Source/core/accessibility/AccessibilityRenderObject.cpp
+++ b/Source/core/accessibility/AccessibilityRenderObject.cpp
@@ -39,7 +39,6 @@
 #include "core/editing/RenderedPosition.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
-#include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLLabelElement.h"
 #include "core/html/HTMLOptionElement.h"
@@ -63,10 +62,7 @@
 #include "core/svg/SVGDocument.h"
 #include "core/svg/SVGSVGElement.h"
 #include "core/svg/graphics/SVGImage.h"
-#include "core/svg/graphics/SVGImageChromeClient.h"
-#include <wtf/StdLibExtras.h>
-#include <wtf/text/StringBuilder.h>
-#include <wtf/unicode/CharacterNames.h>
+#include "wtf/StdLibExtras.h"
 
 using namespace std;
 
@@ -1405,7 +1401,7 @@
         return accessibilityImageMapHitTest(static_cast<HTMLAreaElement*>(node), point);
 
     if (node->hasTagName(optionTag))
-        node = static_cast<HTMLOptionElement*>(node)->ownerSelectElement();
+        node = toHTMLOptionElement(node)->ownerSelectElement();
 
     RenderObject* obj = node->renderer();
     if (!obj)
@@ -1859,24 +1855,6 @@
         axObjectCache()->postNotification(this, document(), isExpanded() ? AXObjectCache::AXRowExpanded : AXObjectCache::AXRowCollapsed, true);
 }
 
-void AccessibilityRenderObject::textChanged()
-{
-    // If this element supports ARIA live regions, or is part of a region with an ARIA editable role,
-    // then notify the AT of changes.
-    AXObjectCache* cache = axObjectCache();
-    for (RenderObject* renderParent = m_renderer; renderParent; renderParent = renderParent->parent()) {
-        AccessibilityObject* parent = cache->get(renderParent);
-        if (!parent)
-            continue;
-
-        if (parent->supportsARIALiveRegion())
-            cache->postNotification(renderParent, AXObjectCache::AXLiveRegionChanged, true);
-
-        if (parent->isARIATextControl() && !parent->isNativeTextControl() && !parent->node()->rendererIsEditable())
-            cache->postNotification(renderParent, AXObjectCache::AXValueChanged, true);
-    }
-}
-
 //
 // Text metrics. Most of these should be deprecated, needs major cleanup.
 //
diff --git a/Source/core/accessibility/AccessibilityRenderObject.h b/Source/core/accessibility/AccessibilityRenderObject.h
index 949b992..9200b53 100644
--- a/Source/core/accessibility/AccessibilityRenderObject.h
+++ b/Source/core/accessibility/AccessibilityRenderObject.h
@@ -198,7 +198,6 @@
     // Notifications that this object may have changed.
     virtual void handleActiveDescendantChanged() OVERRIDE;
     virtual void handleAriaExpandedChanged() OVERRIDE;
-    virtual void textChanged() OVERRIDE;
 
     // Text metrics. Most of these should be deprecated, needs major cleanup.
     virtual int index(const VisiblePosition&) const OVERRIDE;
diff --git a/Source/core/accessibility/AccessibilityTableColumn.h b/Source/core/accessibility/AccessibilityTableColumn.h
index fb0f073..09de7ec 100644
--- a/Source/core/accessibility/AccessibilityTableColumn.h
+++ b/Source/core/accessibility/AccessibilityTableColumn.h
@@ -31,7 +31,6 @@
 
 #include "core/accessibility/AccessibilityMockObject.h"
 #include "core/accessibility/AccessibilityTable.h"
-#include "core/platform/graphics/IntRect.h"
 
 namespace WebCore {
 
diff --git a/Source/core/accessibility/AccessibilityTableHeaderContainer.h b/Source/core/accessibility/AccessibilityTableHeaderContainer.h
index e198b6e..2fe679a 100644
--- a/Source/core/accessibility/AccessibilityTableHeaderContainer.h
+++ b/Source/core/accessibility/AccessibilityTableHeaderContainer.h
@@ -31,7 +31,6 @@
 
 #include "core/accessibility/AccessibilityMockObject.h"
 #include "core/accessibility/AccessibilityTable.h"
-#include "core/platform/graphics/IntRect.h"
 
 namespace WebCore {
 
diff --git a/Source/core/core.gyp b/Source/core/core.gyp
index 5978bc4..d30200a 100644
--- a/Source/core/core.gyp
+++ b/Source/core/core.gyp
@@ -212,6 +212,7 @@
       'hard_dependency': 1,
       'dependencies': [
         'webcore_prerequisites',
+        '../bindings/derived_sources.gyp:bindings_derived_sources',
         'core_derived_sources.gyp:make_derived_sources',
         'inspector_overlay_page',
         'inspector_protocol_sources',
@@ -276,8 +277,6 @@
         '<(SHARED_INTERMEDIATE_DIR)/webkit/EventInterfaces.h',
         '<(SHARED_INTERMEDIATE_DIR)/webkit/EventTargetHeaders.h',
         '<(SHARED_INTERMEDIATE_DIR)/webkit/EventTargetInterfaces.h',
-        '<(SHARED_INTERMEDIATE_DIR)/webkit/DOMException.cpp',
-        '<(SHARED_INTERMEDIATE_DIR)/webkit/DOMException.h',
         '<(SHARED_INTERMEDIATE_DIR)/webkit/PickerCommon.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/webkit/UserAgentStyleSheetsData.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/webkit/V8HTMLElementWrapperFactory.cpp',
@@ -285,7 +284,6 @@
         '<(SHARED_INTERMEDIATE_DIR)/webkit/XMLNSNames.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/webkit/XMLNames.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/webkit/SVGNames.cpp',
-        '<(SHARED_INTERMEDIATE_DIR)/webkit/MathMLElementFactory.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/webkit/MathMLNames.cpp',
         '<(SHARED_INTERMEDIATE_DIR)/webkit/FontFamilyNames.cpp',
 
@@ -355,8 +353,8 @@
         'inspector_overlay_page',
         'inspector_protocol_sources',
         'inspector_instrumentation_sources',
-        'core_derived_sources.gyp:make_derived_sources',
         '../bindings/derived_sources.gyp:bindings_derived_sources',
+        'core_derived_sources.gyp:make_derived_sources',
         '../wtf/wtf.gyp:wtf',
         '../config.gyp:config',
         '../weborigin/weborigin.gyp:weborigin',
@@ -630,11 +628,6 @@
         ['exclude', 'platform/graphics/cpu/arm/filters/.*NEON\\.(cpp|h)'],
       ],
       'conditions': [
-        ['component=="shared_library"', {
-            'defines': [
-                'WEBKIT_DLL',
-            ],
-        }],
         ['use_default_render_theme==1', {
           'sources/': [
             ['exclude', 'platform/chromium/PlatformThemeChromiumWin.h'],
@@ -781,7 +774,7 @@
             ['exclude', 'platform/graphics/FontPlatformData\\.cpp$'],
           ],
         }],
-        ['OS != "linux" and OS != "mac" and (OS != "win" or (OS == "win" and "ENABLE_GDI_FONTS_ON_WINDOWS=1"))', {
+        ['OS != "linux" and OS != "mac" and (OS != "win" or (OS == "win" and "ENABLE_GDI_FONTS_ON_WINDOWS=1" in feature_defines))', {
           'sources/': [
             ['exclude', 'VDMX[^/]+\\.(cpp|h)$'],
           ],
@@ -794,10 +787,7 @@
             ['include', '/SkiaFontWin\\.cpp$'],
             ['include', '/TransparencyWin\\.cpp$'],
 
-            # The Chromium Win currently uses GlyphPageTreeNodeChromiumWin.cpp from
-            # platform/graphics/chromium, included by regex above, instead.
             ['exclude', 'platform/graphics/skia/FontCacheSkia\\.cpp$'],
-            ['exclude', 'platform/graphics/skia/GlyphPageTreeNodeSkia\\.cpp$'],
 
             # SystemInfo.cpp is useful and we don't want to copy it.
             ['include', 'platform/win/SystemInfo\\.cpp$'],
@@ -811,11 +801,14 @@
             ['"ENABLE_GDI_FONTS_ON_WINDOWS=1" in feature_defines', {
               'sources/': [
                 ['exclude', 'platform/graphics/skia/SimpleFontDataSkia\\.cpp$'],
+                ['exclude', 'platform/graphics/skia/GlyphPageTreeNodeSkia\\.cpp$'],
               ],
             },{ # ENABLE_GDI_FONTS_ON_WINDOWS!=1
               'sources/': [
                 ['exclude', 'platform/graphics/chromium/SimpleFontDataChromiumWin\\.cpp$'],
                 ['include', 'platform/graphics/skia/SimpleFontDataSkia\\.cpp$'],
+                ['include', 'platform/graphics/skia/GlyphPageTreeNodeSkia\\.cpp$'],
+                ['exclude', 'platform/graphics/chromium/GlyphPageTreeNodeChromiumWin\\.cpp$'],
               ],
             }],
           ],
diff --git a/Source/core/core.gypi b/Source/core/core.gypi
index e50eeac..f05128a 100644
--- a/Source/core/core.gypi
+++ b/Source/core/core.gypi
@@ -44,6 +44,7 @@
             'dom/BeforeLoadEvent.idl',
             'dom/CDATASection.idl',
             'dom/CharacterData.idl',
+            'dom/ChildNode.idl',
             'dom/ClientRect.idl',
             'dom/ClientRectList.idl',
             'dom/Clipboard.idl',
@@ -89,6 +90,8 @@
             'dom/PopStateEvent.idl',
             'dom/ProcessingInstruction.idl',
             'dom/ProgressEvent.idl',
+            'dom/Promise.idl',
+            'dom/PromiseResolver.idl',
             'dom/Range.idl',
             'dom/RequestAnimationFrameCallback.idl',
             'dom/ResourceProgressEvent.idl',
@@ -110,10 +113,10 @@
             'fileapi/Blob.idl',
             'fileapi/File.idl',
             'fileapi/FileError.idl',
-            'fileapi/FileException.idl',
             'fileapi/FileList.idl',
             'fileapi/FileReader.idl',
             'fileapi/FileReaderSync.idl',
+            'fileapi/Stream.idl',
             'html/DOMSettableTokenList.idl',
             'html/DOMTokenList.idl',
             'html/FormData.idl',
@@ -291,6 +294,7 @@
             'page/WebKitPoint.idl',
             'page/Window.idl',
             'page/WindowPagePopup.idl',
+            'page/WindowTimers.idl',
             'page/WorkerNavigator.idl',
             'plugins/MimeType.idl',
             'plugins/MimeTypeArray.idl',
@@ -299,11 +303,11 @@
             'storage/Storage.idl',
             'storage/StorageEvent.idl',
             'workers/AbstractWorker.idl',
-            'workers/DedicatedWorkerContext.idl',
+            'workers/DedicatedWorkerGlobalScope.idl',
             'workers/SharedWorker.idl',
-            'workers/SharedWorkerContext.idl',
+            'workers/SharedWorkerGlobalScope.idl',
             'workers/Worker.idl',
-            'workers/WorkerContext.idl',
+            'workers/WorkerGlobalScope.idl',
             'workers/WorkerLocation.idl',
             'xml/DOMParser.idl',
             'xml/XMLHttpRequest.idl',
@@ -311,7 +315,6 @@
             'xml/XMLHttpRequestUpload.idl',
             'xml/XMLSerializer.idl',
             'xml/XPathEvaluator.idl',
-            'xml/XPathException.idl',
             'xml/XPathExpression.idl',
             'xml/XPathNSResolver.idl',
             'xml/XPathResult.idl',
@@ -352,7 +355,7 @@
             'svg/SVGElementInstance.idl',
             'svg/SVGElementInstanceList.idl',
             'svg/SVGEllipseElement.idl',
-            'svg/SVGException.idl',
+            'svg/SVGExternalResourcesRequired.idl',
             'svg/SVGFEBlendElement.idl',
             'svg/SVGFEColorMatrixElement.idl',
             'svg/SVGFEComponentTransferElement.idl',
@@ -379,6 +382,8 @@
             'svg/SVGFETileElement.idl',
             'svg/SVGFETurbulenceElement.idl',
             'svg/SVGFilterElement.idl',
+            'svg/SVGFilterPrimitiveStandardAttributes.idl',
+            'svg/SVGFitToViewBox.idl',
             'svg/SVGFontElement.idl',
             'svg/SVGFontFaceElement.idl',
             'svg/SVGFontFaceFormatElement.idl',
@@ -390,6 +395,7 @@
             'svg/SVGGlyphElement.idl',
             'svg/SVGGlyphRefElement.idl',
             'svg/SVGGradientElement.idl',
+            'svg/SVGGraphicsElement.idl',
             'svg/SVGHKernElement.idl',
             'svg/SVGImageElement.idl',
             'svg/SVGLength.idl',
@@ -448,6 +454,7 @@
             'svg/SVGSymbolElement.idl',
             'svg/SVGTRefElement.idl',
             'svg/SVGTSpanElement.idl',
+            'svg/SVGTests.idl',
             'svg/SVGTextContentElement.idl',
             'svg/SVGTextElement.idl',
             'svg/SVGTextPathElement.idl',
@@ -455,6 +462,7 @@
             'svg/SVGTitleElement.idl',
             'svg/SVGTransform.idl',
             'svg/SVGTransformList.idl',
+            'svg/SVGURIReference.idl',
             'svg/SVGUnitTypes.idl',
             'svg/SVGUseElement.idl',
             'svg/SVGViewElement.idl',
@@ -624,7 +632,6 @@
             'css/CSSShaderValue.cpp',
             'css/CSSShaderValue.h',
             'css/CSSStyleDeclaration.h',
-            'css/CSSStyleDeclaration.cpp',
             'css/CSSStyleRule.cpp',
             'css/CSSStyleRule.h',
             'css/CSSStyleSheet.cpp',
@@ -728,6 +735,8 @@
             'css/StyleSheetContents.h',
             'css/StyleSheetList.cpp',
             'css/StyleSheetList.h',
+            'css/resolver/ElementStyleResources.cpp',
+            'css/resolver/ElementStyleResources.h',
             'css/resolver/FilterOperationResolver.cpp',
             'css/resolver/FilterOperationResolver.h',
             'css/resolver/ScopedStyleResolver.cpp',
@@ -737,6 +746,8 @@
             'css/resolver/StyleResolver.h',
             'css/resolver/StyleResolverState.cpp',
             'css/resolver/StyleResolverState.h',
+            'css/resolver/StyleResourceLoader.cpp',
+            'css/resolver/StyleResourceLoader.h',
             'css/resolver/TransformBuilder.cpp',
             'css/resolver/TransformBuilder.h',
             'css/resolver/ViewportStyleResolver.cpp',
@@ -830,20 +841,20 @@
             'editing/WrapContentsInDummySpanCommand.cpp',
             'editing/WrapContentsInDummySpanCommand.h',
             'editing/chromium/EditorChromium.cpp',
-            'editing/chromium/FrameSelectionChromium.cpp',
             'editing/htmlediting.cpp',
             'editing/markup.cpp',
             'fileapi/Blob.cpp',
             'fileapi/Blob.h',
             'fileapi/BlobBuilder.cpp',
             'fileapi/BlobBuilder.h',
+            'fileapi/BlobRegistry.cpp',
+            'fileapi/BlobRegistry.h',
             'fileapi/BlobURL.cpp',
             'fileapi/BlobURL.h',
             'fileapi/File.cpp',
             'fileapi/File.h',
+            'fileapi/FileError.cpp',
             'fileapi/FileError.h',
-            'fileapi/FileException.cpp',
-            'fileapi/FileException.h',
             'fileapi/FileList.cpp',
             'fileapi/FileList.h',
             'fileapi/FileReader.cpp',
@@ -853,8 +864,8 @@
             'fileapi/FileReaderLoaderClient.h',
             'fileapi/FileReaderSync.cpp',
             'fileapi/FileReaderSync.h',
-            'fileapi/ThreadableBlobRegistry.cpp',
-            'fileapi/ThreadableBlobRegistry.h',
+            'fileapi/Stream.cpp',
+            'fileapi/Stream.h',
             'history/BackForwardClient.h',
             'history/BackForwardController.cpp',
             'history/HistoryItem.cpp',
@@ -983,13 +994,13 @@
             'inspector/InspectorStyleTextEditor.h',
             'inspector/InspectorTimelineAgent.cpp',
             'inspector/InspectorTimelineAgent.h',
-            'inspector/InspectorValues.cpp',
-            'inspector/InspectorWorkerResource.h',
             'inspector/InspectorWorkerAgent.cpp',
             'inspector/InspectorWorkerAgent.h',
             'inspector/InstrumentingAgents.h',
             'inspector/JavaScriptCallFrame.cpp',
             'inspector/JavaScriptCallFrame.h',
+            'inspector/JSONParser.cpp',
+            'inspector/JSONParser.h',
             'inspector/MemoryInstrumentationImpl.cpp',
             'inspector/MemoryInstrumentationImpl.h',
             'inspector/NetworkResourcesData.cpp',
@@ -1051,6 +1062,9 @@
             'loader/MixedContentChecker.cpp',
             'loader/MixedContentChecker.h',
             'loader/NavigationAction.cpp',
+            'loader/NavigationAction.h',
+            'loader/NavigationPolicy.cpp',
+            'loader/NavigationPolicy.h',
             'loader/NavigationScheduler.cpp',
             'loader/PingLoader.cpp',
             'loader/PingLoader.h',
@@ -1062,13 +1076,14 @@
             'loader/ResourceLoadNotifier.cpp',
             'loader/ResourceLoader.cpp',
             'loader/ResourceLoaderOptions.h',
-            'loader/ResourceLoaderTypes.h',
             'loader/SinkDocument.cpp',
             'loader/SinkDocument.h',
             'loader/SubframeLoader.cpp',
             'loader/SubstituteData.cpp',
             'loader/SubstituteData.h',
             'loader/TextResourceDecoder.cpp',
+            'loader/TextResourceDecoderBuilder.cpp',
+            'loader/TextResourceDecoderBuilder.h',
             'loader/TextTrackLoader.cpp',
             'loader/TextTrackLoader.h',
             'loader/ThreadableLoader.cpp',
@@ -1150,7 +1165,6 @@
             'page/FrameDestructionObserver.h',
             'page/FrameTree.cpp',
             'page/FrameView.cpp',
-            'page/GroupSettings.cpp',
             'page/History.cpp',
             'page/History.h',
             'page/LayoutMilestones.h',
@@ -1260,24 +1274,11 @@
             'rendering/AutoTableLayout.h',
             'rendering/BidiRun.cpp',
             'rendering/BidiRun.h',
+            'rendering/CompositingReasons.h',
             'rendering/CounterNode.cpp',
             'rendering/CounterNode.h',
             'rendering/EllipsisBox.cpp',
             'rendering/EllipsisBox.h',
-            'rendering/exclusions/ExclusionInterval.cpp',
-            'rendering/exclusions/ExclusionInterval.h',
-            'rendering/exclusions/ExclusionPolygon.cpp',
-            'rendering/exclusions/ExclusionPolygon.h',
-            'rendering/exclusions/ExclusionRectangle.cpp',
-            'rendering/exclusions/ExclusionRectangle.h',
-            'rendering/exclusions/ExclusionShape.cpp',
-            'rendering/exclusions/ExclusionShape.h',
-            'rendering/exclusions/ExclusionShapeInfo.cpp',
-            'rendering/exclusions/ExclusionShapeInfo.h',
-            'rendering/exclusions/ExclusionShapeInsideInfo.cpp',
-            'rendering/exclusions/ExclusionShapeInsideInfo.h',
-            'rendering/exclusions/ExclusionShapeOutsideInfo.cpp',
-            'rendering/exclusions/ExclusionShapeOutsideInfo.h',
             'rendering/FilterEffectRenderer.cpp',
             'rendering/FilterEffectRenderer.h',
             'rendering/FixedTableLayout.cpp',
@@ -1298,6 +1299,8 @@
             'rendering/ImageQualityController.h',
             'rendering/ImageQualityController.cpp',
             'rendering/LayoutState.cpp',
+            'rendering/OrderIterator.cpp',
+            'rendering/OrderIterator.h',
             'rendering/LayoutRepainter.cpp',
             'rendering/PointerEventsHitRules.cpp',
             'rendering/PointerEventsHitRules.h',
@@ -1474,10 +1477,25 @@
             'rendering/VerticalPositionCache.h',
             'rendering/break_lines.cpp',
             'rendering/break_lines.h',
+            'rendering/shapes/PolygonShape.cpp',
+            'rendering/shapes/PolygonShape.h',
+            'rendering/shapes/RectangleShape.cpp',
+            'rendering/shapes/RectangleShape.h',
+            'rendering/shapes/Shape.cpp',
+            'rendering/shapes/Shape.h',
+            'rendering/shapes/ShapeInfo.cpp',
+            'rendering/shapes/ShapeInfo.h',
+            'rendering/shapes/ShapeInsideInfo.cpp',
+            'rendering/shapes/ShapeInsideInfo.h',
+            'rendering/shapes/ShapeInterval.cpp',
+            'rendering/shapes/ShapeInterval.h',
+            'rendering/shapes/ShapeOutsideInfo.cpp',
+            'rendering/shapes/ShapeOutsideInfo.h',
             'rendering/style/BasicShapes.cpp',
             'rendering/style/ContentData.cpp',
             'rendering/style/CounterDirectives.cpp',
             'rendering/style/FillLayer.cpp',
+            'rendering/style/GridCoordinate.h',
             'rendering/style/KeyframeList.cpp',
             'rendering/style/KeyframeList.h',
             'rendering/style/NinePieceImage.cpp',
@@ -1563,25 +1581,25 @@
             'storage/StorageNamespace.h',
             'workers/AbstractWorker.cpp',
             'workers/AbstractWorker.h',
-            'workers/DedicatedWorkerContext.cpp',
-            'workers/DedicatedWorkerContext.h',
+            'workers/DedicatedWorkerGlobalScope.cpp',
+            'workers/DedicatedWorkerGlobalScope.h',
             'workers/DedicatedWorkerThread.cpp',
             'workers/DedicatedWorkerThread.h',
             'workers/SharedWorker.cpp',
             'workers/SharedWorker.h',
-            'workers/SharedWorkerContext.cpp',
-            'workers/SharedWorkerContext.h',
+            'workers/SharedWorkerGlobalScope.cpp',
+            'workers/SharedWorkerGlobalScope.h',
             'workers/SharedWorkerRepository.h',
             'workers/SharedWorkerThread.cpp',
             'workers/SharedWorkerThread.h',
             'workers/Worker.cpp',
             'workers/Worker.h',
-            'workers/WorkerContext.cpp',
-            'workers/WorkerContext.h',
-            'workers/WorkerContextProxy.h',
-            'workers/WorkerContextProxy.cpp',
+            'workers/WorkerGlobalScopeProxy.h',
+            'workers/WorkerGlobalScopeProxy.cpp',
             'workers/WorkerEventQueue.cpp',
             'workers/WorkerEventQueue.h',
+            'workers/WorkerGlobalScope.cpp',
+            'workers/WorkerGlobalScope.h',
             'workers/WorkerLoaderProxy.h',
             'workers/WorkerLocation.cpp',
             'workers/WorkerLocation.h',
@@ -1600,6 +1618,7 @@
             'xml/parser/XMLDocumentParser.h',
             'xml/parser/XMLDocumentParserScope.cpp',
             'xml/parser/XMLDocumentParserScope.h',
+            'xml/parser/XMLParserInput.h',
             'xml/DOMParser.cpp',
             'xml/DOMParser.h',
             'xml/NativeXPathNSResolver.cpp',
@@ -1619,8 +1638,6 @@
             'xml/XMLTreeViewer.h',
             'xml/XPathEvaluator.cpp',
             'xml/XPathEvaluator.h',
-            'xml/XPathException.cpp',
-            'xml/XPathException.h',
             'xml/XPathExpression.cpp',
             'xml/XPathExpression.h',
             'xml/XPathExpressionNode.cpp',
@@ -1694,22 +1711,28 @@
             'dom/ContainerNode.cpp',
             'dom/ContainerNodeAlgorithms.h',
             'dom/ContainerNodeAlgorithms.cpp',
-            'dom/ContextDestructionObserver.cpp',
+            'dom/ContextLifecycleObserver.h',
+            'dom/ContextLifecycleObserver.cpp',
             'dom/ContextFeatures.cpp',
             'dom/ContextFeatures.h',
+            'dom/ContextLifecycleNotifier.cpp',
+            'dom/ContextLifecycleNotifier.h',
             'dom/CrossThreadTask.h',
             'dom/CustomElementDefinition.cpp',
             'dom/CustomElementDefinition.h',
+            'dom/CustomElementCallback.h',
+            'dom/CustomElementCallbackDispatcher.cpp',
+            'dom/CustomElementCallbackDispatcher.h',
             'dom/CustomElementRegistry.cpp',
             'dom/CustomElementRegistry.h',
             'dom/CustomElementUpgradeCandidateMap.cpp',
             'dom/CustomElementUpgradeCandidateMap.h',
             'dom/CustomEvent.cpp',
             'dom/CustomEvent.h',
-            'dom/DOMCoreException.cpp',
-            'dom/DOMCoreException.h',
             'dom/DOMError.cpp',
             'dom/DOMError.h',
+            'dom/DOMException.cpp',
+            'dom/DOMException.h',
             'dom/DOMImplementation.cpp',
             'dom/DOMNamedFlowCollection.cpp',
             'dom/DOMNamedFlowCollection.h',
@@ -1739,6 +1762,8 @@
             'dom/DocumentLifecycleObserver.h',
             'dom/DocumentMarkerController.cpp',
             'dom/DocumentMarker.cpp',
+            'dom/DocumentOrderedList.cpp',
+            'dom/DocumentOrderedList.h',
             'dom/DocumentOrderedMap.cpp',
             'dom/DocumentParser.cpp',
             'dom/DocumentSharedObjectPool.cpp',
@@ -1766,8 +1791,6 @@
             'dom/EventQueue.h',
             'dom/EventSender.h',
             'dom/EventTarget.cpp',
-            'dom/ExceptionBase.cpp',
-            'dom/ExceptionBase.h',
             'dom/ExceptionCodePlaceholder.cpp',
             'dom/FocusEvent.cpp',
             'dom/FocusEvent.h',
@@ -1794,6 +1817,8 @@
             'dom/MessageEvent.h',
             'dom/MessagePort.cpp',
             'dom/MessagePortChannel.cpp',
+            'dom/Microtask.cpp',
+            'dom/Microtask.h',
             'dom/MouseEvent.cpp',
             'dom/MouseRelatedEvent.cpp',
             'dom/MutationCallback.h',
@@ -1850,11 +1875,12 @@
             'dom/ProcessingInstruction.h',
             'dom/ProgressEvent.cpp',
             'dom/ProgressEvent.h',
+            'dom/Promise.h',
+            'dom/PromiseResolver.h',
             'dom/PseudoElement.cpp',
             'dom/QualifiedName.cpp',
             'dom/Range.cpp',
             'dom/RawDataDocumentParser.h',
-            'dom/RegisteredEventListener.cpp',
             'dom/RequestAnimationFrameCallback.h',
             'dom/ResourceProgressEvent.cpp',
             'dom/ResourceProgressEvent.h',
@@ -1881,7 +1907,6 @@
             'dom/StringCallback.h',
             'dom/StyleElement.cpp',
             'dom/StyleElement.h',
-            'dom/StyledElement.cpp',
             'dom/TagNodeList.cpp',
             'dom/TagNodeList.h',
             'dom/Text.cpp',
@@ -2475,6 +2500,8 @@
             'platform/FileMetadata.h',
             'platform/FloatConversion.h',
             'platform/HashTools.h',
+            'platform/JSONValues.cpp',
+            'platform/JSONValues.h',
             'platform/KillRing.h',
             'platform/KillRingNone.cpp',
             'platform/Language.cpp',
@@ -2487,6 +2514,8 @@
             'platform/MIMETypeFromURL.cpp',
             'platform/MIMETypeFromURL.h',
             'platform/NotImplemented.cpp',
+            'platform/Partitions.cpp',
+            'platform/Partitions.h',
             'platform/Pasteboard.h',
             'platform/PlatformEvent.cpp',
             'platform/PlatformEvent.h',
@@ -2635,8 +2664,6 @@
             'platform/chromium/ClipboardUtilitiesChromium.cpp',
             'platform/chromium/ClipboardUtilitiesChromium.h',
             'platform/chromium/DragDataRef.h',
-            'platform/chromium/DragImageChromiumSkia.cpp',
-            'platform/chromium/DragImageRef.h',
             'platform/chromium/FileSystemChromium.cpp',
             'platform/chromium/FileSystemChromiumLinux.cpp',
             'platform/chromium/FileSystemChromiumMac.mm',
@@ -2729,7 +2756,6 @@
             'platform/graphics/Latin1TextIterator.h',
             'platform/graphics/MediaPlayer.cpp',
             'platform/graphics/MediaPlayer.h',
-            'platform/graphics/NativeImagePtr.h' ,
             'platform/graphics/Path.cpp',
             'platform/graphics/PathTraversalState.cpp',
             'platform/graphics/PathTraversalState.h',
@@ -2779,7 +2805,6 @@
             'platform/graphics/chromium/GlyphPageTreeNodeChromiumWin.cpp',
             'platform/graphics/chromium/IconChromium.cpp',
             'platform/graphics/chromium/IconChromiumAndroid.cpp',
-            'platform/graphics/chromium/ImageBufferDataSkia.h',
             'platform/graphics/chromium/ImageChromium.cpp',
             'platform/graphics/chromium/ImageDecodingStore.cpp',
             'platform/graphics/chromium/ImageDecodingStore.h',
@@ -2934,8 +2959,8 @@
             'platform/graphics/skia/FontCacheSkia.cpp',
             'platform/graphics/skia/FontCustomPlatformData.cpp',
             'platform/graphics/skia/FontCustomPlatformData.h',
+            'platform/graphics/skia/FontPlatformDataSkia.cpp',
             'platform/graphics/skia/GlyphPageTreeNodeSkia.cpp',
-            'platform/graphics/skia/ImageBufferSkia.cpp',
             'platform/graphics/skia/ImageSkia.cpp',
             'platform/graphics/skia/MemoryInstrumentationSkia.cpp',
             'platform/graphics/skia/MemoryInstrumentationSkia.h',
@@ -2970,6 +2995,7 @@
             'platform/graphics/transforms/TranslateTransformOperation.h',
             'platform/image-decoders/ImageDecoder.cpp',
             'platform/image-decoders/ImageDecoder.h',
+            'platform/image-decoders/ImageFrame.cpp',
             'platform/image-decoders/bmp/BMPImageDecoder.cpp',
             'platform/image-decoders/bmp/BMPImageDecoder.h',
             'platform/image-decoders/bmp/BMPImageReader.cpp',
@@ -2984,7 +3010,6 @@
             'platform/image-decoders/jpeg/JPEGImageDecoder.h',
             'platform/image-decoders/png/PNGImageDecoder.cpp',
             'platform/image-decoders/png/PNGImageDecoder.h',
-            'platform/image-decoders/skia/ImageDecoderSkia.cpp',
             'platform/image-decoders/webp/WEBPImageDecoder.cpp',
             'platform/image-decoders/webp/WEBPImageDecoder.h',
             'platform/image-encoders/skia/JPEGImageEncoder.cpp',
@@ -3030,6 +3055,9 @@
             'platform/mediastream/RTCSessionDescriptionRequest.h',
             'platform/mediastream/RTCStatsRequest.h',
             'platform/mediastream/RTCVoidRequest.h',
+            'platform/midi/MIDIAccessor.h',
+            'platform/midi/MIDIAccessor.cpp',
+            'platform/midi/MIDIAccessorClient.h',
             'platform/mock/DeviceMotionClientMock.cpp',
             'platform/mock/DeviceOrientationClientMock.cpp',
             'platform/mock/GeolocationClientMock.cpp',
@@ -3039,10 +3067,6 @@
             'platform/mock/ScrollbarThemeMock.h',
             'platform/network/BlobData.cpp',
             'platform/network/BlobData.h',
-            'platform/network/BlobRegistry.h',
-            'platform/network/BlobRegistry.cpp',
-            'platform/network/BlobRegistryProxy.cpp',
-            'platform/network/BlobRegistryProxy.h',
             'platform/network/DNS.cpp',
             'platform/network/DNS.h',
             'platform/network/FormData.cpp',
@@ -3250,7 +3274,6 @@
             'rendering/svg/SVGTextRunRenderingContext.h',
             'svg/ColorDistance.cpp',
             'svg/ColorDistance.h',
-            'svg/ElementTimeControl.h',
             'svg/GradientAttributes.h',
             'svg/LinearGradientAttributes.h',
             'svg/PatternAttributes.h',
@@ -3316,8 +3339,6 @@
             'svg/SVGElementRareData.h',
             'svg/SVGEllipseElement.cpp',
             'svg/SVGEllipseElement.h',
-            'svg/SVGException.cpp',
-            'svg/SVGException.h',
             'svg/SVGExternalResourcesRequired.cpp',
             'svg/SVGExternalResourcesRequired.h',
             'svg/SVGFEBlendElement.cpp',
@@ -3403,6 +3424,8 @@
             'svg/SVGGlyphMap.h',
             'svg/SVGGradientElement.cpp',
             'svg/SVGGradientElement.h',
+            'svg/SVGGraphicsElement.cpp',
+            'svg/SVGGraphicsElement.h',
             'svg/SVGHKernElement.cpp',
             'svg/SVGHKernElement.h',
             'svg/SVGImageElement.cpp',
@@ -3506,10 +3529,6 @@
             'svg/SVGStyleElement.h',
             'svg/SVGStyledElement.cpp',
             'svg/SVGStyledElement.h',
-            'svg/SVGStyledLocatableElement.cpp',
-            'svg/SVGStyledLocatableElement.h',
-            'svg/SVGStyledTransformableElement.cpp',
-            'svg/SVGStyledTransformableElement.h',
             'svg/SVGSwitchElement.cpp',
             'svg/SVGSwitchElement.h',
             'svg/SVGSymbolElement.cpp',
@@ -3601,6 +3620,7 @@
             'platform/chromium/support/WebActiveGestureAnimation.cpp',
             'platform/chromium/support/WebActiveGestureAnimation.h',
             'platform/chromium/support/WebAudioBus.cpp',
+            'platform/chromium/support/WebCryptoAlgorithm.cpp',
             'platform/chromium/support/WebCursorInfo.cpp',
             'platform/chromium/support/WebData.cpp',
             'platform/chromium/support/WebDeviceMotionData.cpp',
@@ -3610,7 +3630,6 @@
             'platform/chromium/support/WebMediaConstraints.cpp',
             'platform/chromium/support/WebMediaStream.cpp',
             'platform/chromium/support/WebMediaStreamSource.cpp',
-            'platform/chromium/support/WebMediaStreamSourcesRequest.cpp',
             'platform/chromium/support/WebMediaStreamTrack.cpp',
             'platform/chromium/support/WebPrerender.cpp',
             'platform/chromium/support/WebPrerenderingSupport.cpp',
@@ -3664,6 +3683,7 @@
             'platform/graphics/chromium/test/MockImageDecoder.h',
             'platform/image-decoders/ImageDecoderTest.cpp',
             'platform/image-decoders/gif/GIFImageDecoderTest.cpp',
+            'platform/image-decoders/webp/WEBPImageDecoderTest.cpp',
             'platform/text/DateTimeFormatTest.cpp',
             'tests/HeapGraphSerializerTest.cpp',
             'tests/LayoutUnit.cpp',
diff --git a/Source/core/core_derived_sources.gyp b/Source/core/core_derived_sources.gyp
index a947a25..8265a95 100644
--- a/Source/core/core_derived_sources.gyp
+++ b/Source/core/core_derived_sources.gyp
@@ -351,7 +351,8 @@
           'inputs': [
             '<@(scripts_for_in_files)',
             'scripts/make_event_factory.py',
-            'dom/EventNames.in',
+            '<(SHARED_INTERMEDIATE_DIR)/EventNames.in',
+            'dom/EventAliases.in',
           ],
           'outputs': [
             '<(SHARED_INTERMEDIATE_DIR)/webkit/Event.cpp',
@@ -361,7 +362,8 @@
           'action': [
             'python',
             'scripts/make_event_factory.py',
-            'dom/EventNames.in',
+            '<(SHARED_INTERMEDIATE_DIR)/EventNames.in',
+            'dom/EventAliases.in',
             '--output_dir',
             '<(SHARED_INTERMEDIATE_DIR)/webkit/',
           ],
@@ -386,27 +388,6 @@
           ],
         },
         {
-          'action_name': 'ExceptionCodeDescription',
-          'inputs': [
-            '<@(scripts_for_in_files)',
-            'scripts/make_dom_exceptions.py',
-            'dom/DOMExceptions.in',
-          ],
-          'outputs': [
-            '<(SHARED_INTERMEDIATE_DIR)/webkit/DOMException.cpp',
-            '<(SHARED_INTERMEDIATE_DIR)/webkit/DOMException.h',
-            '<(SHARED_INTERMEDIATE_DIR)/webkit/DOMExceptionHeaders.h',
-            '<(SHARED_INTERMEDIATE_DIR)/webkit/DOMExceptionInterfaces.h',
-          ],
-          'action': [
-            'python',
-            'scripts/make_dom_exceptions.py',
-            'dom/DOMExceptions.in',
-            '--output_dir',
-            '<(SHARED_INTERMEDIATE_DIR)/webkit/',
-          ],
-        },
-        {
           'action_name': 'MathMLNames',
           'inputs': [
             'scripts/Hasher.pm',
@@ -418,8 +399,6 @@
           'outputs': [
             '<(SHARED_INTERMEDIATE_DIR)/webkit/MathMLNames.cpp',
             '<(SHARED_INTERMEDIATE_DIR)/webkit/MathMLNames.h',
-            '<(SHARED_INTERMEDIATE_DIR)/webkit/MathMLElementFactory.cpp',
-            '<(SHARED_INTERMEDIATE_DIR)/webkit/MathMLElementFactory.h',
           ],
           'action': [
             'python',
@@ -428,7 +407,6 @@
             '--',
             '<@(_inputs)',
             '--',
-            '--factory',
             '--extraDefines', '<(feature_defines)'
           ],
           'msvs_cygwin_shell': 1,
diff --git a/Source/core/css/CSSAspectRatioValue.cpp b/Source/core/css/CSSAspectRatioValue.cpp
index 2f6c463..bced41f 100644
--- a/Source/core/css/CSSAspectRatioValue.cpp
+++ b/Source/core/css/CSSAspectRatioValue.cpp
@@ -30,7 +30,6 @@
 #include "core/css/CSSAspectRatioValue.h"
 
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSAspectRatioValue.h b/Source/core/css/CSSAspectRatioValue.h
index 4d640ca..a9c5cc2 100644
--- a/Source/core/css/CSSAspectRatioValue.h
+++ b/Source/core/css/CSSAspectRatioValue.h
@@ -29,7 +29,6 @@
 #ifndef CSSAspectRatioValue_h
 #define CSSAspectRatioValue_h
 
-#include "core/css/CSSPrimitiveValue.h"
 #include "core/css/CSSValue.h"
 
 namespace WebCore {
diff --git a/Source/core/css/CSSBorderImage.h b/Source/core/css/CSSBorderImage.h
index f6c2f37..bdf13fe 100644
--- a/Source/core/css/CSSBorderImage.h
+++ b/Source/core/css/CSSBorderImage.h
@@ -22,8 +22,7 @@
 
 #include "core/css/CSSBorderImageSliceValue.h"
 #include "core/css/CSSValueList.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSComputedStyleDeclaration.cpp b/Source/core/css/CSSComputedStyleDeclaration.cpp
index 64defa5..a5fb17f 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.cpp
+++ b/Source/core/css/CSSComputedStyleDeclaration.cpp
@@ -63,9 +63,9 @@
 #include "core/rendering/style/ContentData.h"
 #include "core/rendering/style/CounterContent.h"
 #include "core/rendering/style/CursorList.h"
-#include "core/rendering/style/ExclusionShapeValue.h"
 #include "core/rendering/style/RenderStyle.h"
-#include <wtf/text/StringBuilder.h>
+#include "core/rendering/style/ShapeValue.h"
+#include "wtf/text/StringBuilder.h"
 
 #include "core/platform/graphics/filters/custom/CustomFilterArrayParameter.h"
 #include "core/platform/graphics/filters/custom/CustomFilterNumberParameter.h"
@@ -244,27 +244,27 @@
     CSSPropertyWebkitColumnSpan,
     CSSPropertyWebkitColumnWidth,
     CSSPropertyWebkitFilter,
-    CSSPropertyWebkitAlignContent,
-    CSSPropertyWebkitAlignItems,
-    CSSPropertyWebkitAlignSelf,
-    CSSPropertyWebkitFlexBasis,
-    CSSPropertyWebkitFlexGrow,
-    CSSPropertyWebkitFlexShrink,
-    CSSPropertyWebkitFlexDirection,
-    CSSPropertyWebkitFlexWrap,
-    CSSPropertyWebkitJustifyContent,
+    CSSPropertyAlignContent,
+    CSSPropertyAlignItems,
+    CSSPropertyAlignSelf,
+    CSSPropertyFlexBasis,
+    CSSPropertyFlexGrow,
+    CSSPropertyFlexShrink,
+    CSSPropertyFlexDirection,
+    CSSPropertyFlexWrap,
+    CSSPropertyJustifyContent,
     CSSPropertyWebkitFontKerning,
     CSSPropertyWebkitFontSmoothing,
     CSSPropertyWebkitFontVariantLigatures,
     CSSPropertyGridAutoColumns,
     CSSPropertyGridAutoFlow,
     CSSPropertyGridAutoRows,
-    CSSPropertyGridColumns,
-    CSSPropertyGridRows,
-    CSSPropertyGridStart,
-    CSSPropertyGridEnd,
-    CSSPropertyGridBefore,
-    CSSPropertyGridAfter,
+    CSSPropertyGridColumnEnd,
+    CSSPropertyGridColumnStart,
+    CSSPropertyGridDefinitionColumns,
+    CSSPropertyGridDefinitionRows,
+    CSSPropertyGridRowEnd,
+    CSSPropertyGridRowStart,
     CSSPropertyWebkitHighlight,
     CSSPropertyWebkitHyphenateCharacter,
     CSSPropertyWebkitHyphenateLimitAfter,
@@ -297,7 +297,7 @@
     CSSPropertyWebkitMaskPosition,
     CSSPropertyWebkitMaskRepeat,
     CSSPropertyWebkitMaskSize,
-    CSSPropertyWebkitOrder,
+    CSSPropertyOrder,
     CSSPropertyWebkitPerspective,
     CSSPropertyWebkitPerspectiveOrigin,
     CSSPropertyWebkitPrintColorAdjust,
@@ -634,7 +634,8 @@
             toRenderBox(renderer)->containingBlockLogicalWidthForContent() :
             toRenderBox(renderer)->containingBlockLogicalHeightForContent(ExcludeMarginBorderPadding);
         return zoomAdjustedPixelValue(valueForLength(l, containingBlockSize, 0), style);
-    } if (l.isViewportPercentage())
+    }
+    if (l.isViewportPercentage())
         return zoomAdjustedPixelValue(valueForLength(l, 0, renderView), style);
     if (l.isAuto()) {
         // FIXME: It's not enough to simply return "auto" values for one offset if the other side is defined.
@@ -1316,7 +1317,7 @@
 
     if (!list->length())
         return cssValuePool().createIdentifierValue(CSSValueNone);
-    return list;
+    return list.release();
 }
 
 static PassRefPtr<CSSValue> renderTextDecorationStyleFlagsToCSSValue(TextDecorationStyle textDecorationStyle)
@@ -1484,22 +1485,17 @@
     return cssValuePool().createIdentifierValue(CSSValueNormal);
 }
 
-static bool isLayoutDependentProperty(CSSPropertyID propertyID)
+static bool isLayoutDependent(CSSPropertyID propertyID, PassRefPtr<RenderStyle> style, RenderObject* renderer)
 {
+    // Some properties only depend on layout in certain conditions which
+    // are specified in the main switch statement below. So we can avoid
+    // forcing layout in those conditions. The conditions in this switch
+    // statement must remain in sync with the conditions in the main switch.
+    // FIXME: Some of these cases could be narrowed down or optimized better.
     switch (propertyID) {
     case CSSPropertyBottom:
     case CSSPropertyHeight:
     case CSSPropertyLeft:
-    case CSSPropertyMargin:
-    case CSSPropertyMarginBottom:
-    case CSSPropertyMarginLeft:
-    case CSSPropertyMarginRight:
-    case CSSPropertyMarginTop:
-    case CSSPropertyPadding:
-    case CSSPropertyPaddingBottom:
-    case CSSPropertyPaddingLeft:
-    case CSSPropertyPaddingRight:
-    case CSSPropertyPaddingTop:
     case CSSPropertyRight:
     case CSSPropertyTop:
     case CSSPropertyWebkitPerspectiveOrigin:
@@ -1508,11 +1504,47 @@
     case CSSPropertyWidth:
     case CSSPropertyWebkitFilter:
         return true;
+    case CSSPropertyMargin:
+        return renderer && renderer->isBox() && (!style || !style->marginBottom().isFixed() || !style->marginTop().isFixed() || !style->marginLeft().isFixed() || !style->marginRight().isFixed());
+    case CSSPropertyMarginLeft:
+        return renderer && renderer->isBox() && (!style || !style->marginLeft().isFixed());
+    case CSSPropertyMarginRight:
+        return renderer && renderer->isBox() && (!style || !style->marginRight().isFixed());
+    case CSSPropertyMarginTop:
+        return renderer && renderer->isBox() && (!style || !style->marginTop().isFixed());
+    case CSSPropertyMarginBottom:
+        return renderer && renderer->isBox() && (!style || !style->marginBottom().isFixed());
+    case CSSPropertyPadding:
+        return renderer && renderer->isBox() && (!style || !style->paddingBottom().isFixed() || !style->paddingTop().isFixed() || !style->paddingLeft().isFixed() || !style->paddingRight().isFixed());
+    case CSSPropertyPaddingBottom:
+        return renderer && renderer->isBox() && (!style || !style->paddingBottom().isFixed());
+    case CSSPropertyPaddingLeft:
+        return renderer && renderer->isBox() && (!style || !style->paddingLeft().isFixed());
+    case CSSPropertyPaddingRight:
+        return renderer && renderer->isBox() && (!style || !style->paddingRight().isFixed());
+    case CSSPropertyPaddingTop:
+        return renderer && renderer->isBox() && (!style || !style->paddingTop().isFixed());
     default:
         return false;
     }
 }
 
+PassRefPtr<RenderStyle> CSSComputedStyleDeclaration::computeRenderStyle(CSSPropertyID propertyID) const
+{
+    Node* styledNode = this->styledNode();
+    ASSERT(styledNode);
+    RenderObject* renderer = styledNode->renderer();
+    if (renderer && renderer->isComposited() && AnimationController::supportsAcceleratedAnimationOfProperty(propertyID)) {
+        AnimationUpdateBlock animationUpdateBlock(renderer->animation());
+        if (m_pseudoElementSpecifier && !styledNode->isPseudoElement()) {
+            // FIXME: This cached pseudo style will only exist if the animation has been run at least once.
+            return renderer->animation()->getAnimatedStyleForRenderer(renderer)->getCachedPseudoStyle(m_pseudoElementSpecifier);
+        }
+        return renderer->animation()->getAnimatedStyleForRenderer(renderer);
+    }
+    return styledNode->computedStyle(styledNode->isPseudoElement() ? NOPSEUDO : m_pseudoElementSpecifier);
+}
+
 Node* CSSComputedStyleDeclaration::styledNode() const
 {
     if (!m_node)
@@ -1529,42 +1561,35 @@
     Node* styledNode = this->styledNode();
     if (!styledNode)
         return 0;
+    RenderObject* renderer = styledNode->renderer();
+    RefPtr<RenderStyle> style;
 
     if (updateLayout) {
         Document* document = styledNode->document();
-        // FIXME: Some of these cases could be narrowed down or optimized better.
-        bool forceFullLayout = isLayoutDependentProperty(propertyID)
-            || styledNode->isInShadowTree()
-            || (document->styleResolverIfExists() && document->styleResolverIfExists()->hasViewportDependentMediaQueries() && document->ownerElement())
-            || document->seamlessParentIFrame();
 
-        if (forceFullLayout)
-            document->updateLayoutIgnorePendingStylesheets();
-        else {
-            bool needsStyleRecalc = document->hasPendingForcedStyleRecalc();
-            for (Node* n = styledNode; n && !needsStyleRecalc; n = n->parentNode())
-                needsStyleRecalc = n->needsStyleRecalc();
-            if (needsStyleRecalc)
-                document->updateStyleIfNeeded();
-        }
+        document->updateStyleForNodeIfNeeded(styledNode);
 
         // The style recalc could have caused the styled node to be discarded or replaced
         // if it was a PseudoElement so we need to update it.
         styledNode = this->styledNode();
-    }
+        renderer = styledNode->renderer();
 
-    RenderObject* renderer = styledNode->renderer();
+        style = computeRenderStyle(propertyID);
 
-    RefPtr<RenderStyle> style;
-    if (renderer && renderer->isComposited() && AnimationController::supportsAcceleratedAnimationOfProperty(propertyID)) {
-        AnimationUpdateBlock animationUpdateBlock(renderer->animation());
-        style = renderer->animation()->getAnimatedStyleForRenderer(renderer);
-        if (m_pseudoElementSpecifier && !styledNode->isPseudoElement()) {
-            // FIXME: This cached pseudo style will only exist if the animation has been run at least once.
-            style = style->getCachedPseudoStyle(m_pseudoElementSpecifier);
+        bool forceFullLayout = isLayoutDependent(propertyID, style, renderer)
+            || styledNode->isInShadowTree()
+            || (document->styleResolverIfExists() && document->styleResolverIfExists()->hasViewportDependentMediaQueries() && document->ownerElement())
+            || document->seamlessParentIFrame();
+
+        if (forceFullLayout) {
+            document->updateLayoutIgnorePendingStylesheets();
+            styledNode = this->styledNode();
+            style = computeRenderStyle(propertyID);
+            renderer = styledNode->renderer();
         }
-    } else
-        style = styledNode->computedStyle(styledNode->isPseudoElement() ? NOPSEUDO : m_pseudoElementSpecifier);
+    } else {
+        style = computeRenderStyle(propertyID);
+    }
 
     if (!style)
         return 0;
@@ -1841,11 +1866,11 @@
             return cssValuePool().createValue(style->display());
         case CSSPropertyEmptyCells:
             return cssValuePool().createValue(style->emptyCells());
-        case CSSPropertyWebkitAlignContent:
+        case CSSPropertyAlignContent:
             return cssValuePool().createValue(style->alignContent());
-        case CSSPropertyWebkitAlignItems:
+        case CSSPropertyAlignItems:
             return cssValuePool().createValue(style->alignItems());
-        case CSSPropertyWebkitAlignSelf:
+        case CSSPropertyAlignSelf:
             if (style->alignSelf() == AlignAuto) {
                 Node* parent = styledNode->parentNode();
                 if (parent && parent->computedStyle())
@@ -1853,23 +1878,23 @@
                 return cssValuePool().createValue(AlignStretch);
             }
             return cssValuePool().createValue(style->alignSelf());
-        case CSSPropertyWebkitFlex:
-            return getCSSPropertyValuesForShorthandProperties(webkitFlexShorthand());
-        case CSSPropertyWebkitFlexBasis:
+        case CSSPropertyFlex:
+            return getCSSPropertyValuesForShorthandProperties(flexShorthand());
+        case CSSPropertyFlexBasis:
             return cssValuePool().createValue(style->flexBasis());
-        case CSSPropertyWebkitFlexDirection:
+        case CSSPropertyFlexDirection:
             return cssValuePool().createValue(style->flexDirection());
-        case CSSPropertyWebkitFlexFlow:
-            return getCSSPropertyValuesForShorthandProperties(webkitFlexFlowShorthand());
-        case CSSPropertyWebkitFlexGrow:
+        case CSSPropertyFlexFlow:
+            return getCSSPropertyValuesForShorthandProperties(flexFlowShorthand());
+        case CSSPropertyFlexGrow:
             return cssValuePool().createValue(style->flexGrow());
-        case CSSPropertyWebkitFlexShrink:
+        case CSSPropertyFlexShrink:
             return cssValuePool().createValue(style->flexShrink());
-        case CSSPropertyWebkitFlexWrap:
+        case CSSPropertyFlexWrap:
             return cssValuePool().createValue(style->flexWrap());
-        case CSSPropertyWebkitJustifyContent:
+        case CSSPropertyJustifyContent:
             return cssValuePool().createValue(style->justifyContent());
-        case CSSPropertyWebkitOrder:
+        case CSSPropertyOrder:
             return cssValuePool().createValue(style->order(), CSSPrimitiveValue::CSS_NUMBER);
         case CSSPropertyFloat:
             if (style->display() != NONE && style->hasOutOfFlowPosition())
@@ -1919,19 +1944,19 @@
             return cssValuePool().createValue(style->gridAutoFlow());
         case CSSPropertyGridAutoRows:
             return valueForGridTrackSize(style->gridAutoRows(), style.get(), m_node->document()->renderView());
-        case CSSPropertyGridColumns:
-            return valueForGridTrackList(style->gridColumns(), style->namedGridColumnLines(), style.get(), m_node->document()->renderView());
-        case CSSPropertyGridRows:
-            return valueForGridTrackList(style->gridRows(), style->namedGridRowLines(), style.get(), m_node->document()->renderView());
+        case CSSPropertyGridDefinitionColumns:
+            return valueForGridTrackList(style->gridDefinitionColumns(), style->namedGridColumnLines(), style.get(), m_node->document()->renderView());
+        case CSSPropertyGridDefinitionRows:
+            return valueForGridTrackList(style->gridDefinitionRows(), style->namedGridRowLines(), style.get(), m_node->document()->renderView());
 
-        case CSSPropertyGridStart:
-            return valueForGridPosition(style->gridStart());
-        case CSSPropertyGridEnd:
-            return valueForGridPosition(style->gridEnd());
-        case CSSPropertyGridBefore:
-            return valueForGridPosition(style->gridBefore());
-        case CSSPropertyGridAfter:
-            return valueForGridPosition(style->gridAfter());
+        case CSSPropertyGridColumnStart:
+            return valueForGridPosition(style->gridColumnStart());
+        case CSSPropertyGridColumnEnd:
+            return valueForGridPosition(style->gridColumnEnd());
+        case CSSPropertyGridRowStart:
+            return valueForGridPosition(style->gridRowStart());
+        case CSSPropertyGridRowEnd:
+            return valueForGridPosition(style->gridRowEnd());
         case CSSPropertyGridColumn:
             return getCSSPropertyValuesForGridShorthand(gridColumnShorthand());
         case CSSPropertyGridRow:
@@ -2090,22 +2115,30 @@
             return cssValuePool().createValue(style->overflowX());
         case CSSPropertyOverflowY:
             return cssValuePool().createValue(style->overflowY());
-        case CSSPropertyPaddingTop:
-            if (renderer && renderer->isBox())
-                return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingTop(), style.get());
-            return zoomAdjustedPixelValueForLength(style->paddingTop(), style.get());
-        case CSSPropertyPaddingRight:
-            if (renderer && renderer->isBox())
-                return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingRight(), style.get());
-            return zoomAdjustedPixelValueForLength(style->paddingRight(), style.get());
-        case CSSPropertyPaddingBottom:
-            if (renderer && renderer->isBox())
-                return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingBottom(), style.get());
-            return zoomAdjustedPixelValueForLength(style->paddingBottom(), style.get());
-        case CSSPropertyPaddingLeft:
-            if (renderer && renderer->isBox())
-                return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingLeft(), style.get());
-            return zoomAdjustedPixelValueForLength(style->paddingLeft(), style.get());
+        case CSSPropertyPaddingTop: {
+            Length paddingTop = style->paddingTop();
+            if (paddingTop.isFixed() || !renderer || !renderer->isBox())
+                return zoomAdjustedPixelValueForLength(paddingTop, style.get());
+            return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingTop(), style.get());
+        }
+        case CSSPropertyPaddingRight: {
+            Length paddingRight = style->paddingRight();
+            if (paddingRight.isFixed() || !renderer || !renderer->isBox())
+                return zoomAdjustedPixelValueForLength(paddingRight, style.get());
+            return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingRight(), style.get());
+        }
+        case CSSPropertyPaddingBottom: {
+            Length paddingBottom = style->paddingBottom();
+            if (paddingBottom.isFixed() || !renderer || !renderer->isBox())
+                return zoomAdjustedPixelValueForLength(paddingBottom, style.get());
+            return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingBottom(), style.get());
+        }
+        case CSSPropertyPaddingLeft: {
+            Length paddingLeft = style->paddingLeft();
+            if (paddingLeft.isFixed() || !renderer || !renderer->isBox())
+                return zoomAdjustedPixelValueForLength(paddingLeft, style.get());
+            return zoomAdjustedPixelValue(toRenderBox(renderer)->computedCSSPaddingLeft(), style.get());
+        }
         case CSSPropertyPageBreakAfter:
             return cssValuePool().createValue(style->pageBreakAfter());
         case CSSPropertyPageBreakBefore:
@@ -2576,24 +2609,24 @@
         case CSSPropertyWebkitShapeInside:
             if (!style->shapeInside())
                 return cssValuePool().createIdentifierValue(CSSValueAuto);
-            if (style->shapeInside()->type() == ExclusionShapeValue::Outside)
+            if (style->shapeInside()->type() == ShapeValue::Outside)
                 return cssValuePool().createIdentifierValue(CSSValueOutsideShape);
-            if (style->shapeInside()->type() == ExclusionShapeValue::Image) {
+            if (style->shapeInside()->type() == ShapeValue::Image) {
                 if (style->shapeInside()->image())
                     return style->shapeInside()->image()->cssValue();
                 return cssValuePool().createIdentifierValue(CSSValueNone);
             }
-            ASSERT(style->shapeInside()->type() == ExclusionShapeValue::Shape);
+            ASSERT(style->shapeInside()->type() == ShapeValue::Shape);
             return valueForBasicShape(style->shapeInside()->shape());
         case CSSPropertyWebkitShapeOutside:
             if (!style->shapeOutside())
                 return cssValuePool().createIdentifierValue(CSSValueAuto);
-            if (style->shapeOutside()->type() == ExclusionShapeValue::Image) {
+            if (style->shapeOutside()->type() == ShapeValue::Image) {
                 if (style->shapeOutside()->image())
                     return style->shapeOutside()->image()->cssValue();
                 return cssValuePool().createIdentifierValue(CSSValueNone);
             }
-            ASSERT(style->shapeOutside()->type() == ExclusionShapeValue::Shape);
+            ASSERT(style->shapeOutside()->type() == ShapeValue::Shape);
             return valueForBasicShape(style->shapeOutside()->shape());
         case CSSPropertyWebkitWrapThrough:
             return cssValuePool().createValue(style->wrapThrough());
diff --git a/Source/core/css/CSSComputedStyleDeclaration.h b/Source/core/css/CSSComputedStyleDeclaration.h
index 05c7cb3..e628cd8 100644
--- a/Source/core/css/CSSComputedStyleDeclaration.h
+++ b/Source/core/css/CSSComputedStyleDeclaration.h
@@ -85,6 +85,7 @@
     virtual CSSRule* parentRule() const;
     virtual unsigned length() const;
     virtual String item(unsigned index) const;
+    PassRefPtr<RenderStyle> computeRenderStyle(CSSPropertyID) const;
     virtual PassRefPtr<CSSValue> getPropertyCSSValue(const String& propertyName);
     virtual String getPropertyValue(const String& propertyName);
     virtual String getPropertyPriority(const String& propertyName);
diff --git a/Source/core/css/CSSCrossfadeValue.h b/Source/core/css/CSSCrossfadeValue.h
index 9496f5d..c0c953c 100644
--- a/Source/core/css/CSSCrossfadeValue.h
+++ b/Source/core/css/CSSCrossfadeValue.h
@@ -32,7 +32,6 @@
 #include "core/loader/cache/CachedImageClient.h"
 #include "core/loader/cache/CachedResourceHandle.h"
 #include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/ImageObserver.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSCursorImageValue.cpp b/Source/core/css/CSSCursorImageValue.cpp
index 62bff86..a9f27c2 100644
--- a/Source/core/css/CSSCursorImageValue.cpp
+++ b/Source/core/css/CSSCursorImageValue.cpp
@@ -35,10 +35,9 @@
 #include "core/svg/SVGCursorElement.h"
 #include "core/svg/SVGLengthContext.h"
 #include "core/svg/SVGURIReference.h"
-#include <wtf/MathExtras.h>
-#include <wtf/MemoryInstrumentationHashSet.h>
-#include <wtf/UnusedParam.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/MathExtras.h"
+#include "wtf/MemoryInstrumentationHashSet.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -122,10 +121,10 @@
     return false;
 }
 
-StyleImage* CSSCursorImageValue::cachedImage(CachedResourceLoader* loader)
+StyleImage* CSSCursorImageValue::cachedImage(CachedResourceLoader* loader, float deviceScaleFactor)
 {
     if (m_imageValue->isImageSetValue())
-        return static_cast<CSSImageSetValue*>(m_imageValue.get())->cachedImageSet(loader);
+        return static_cast<CSSImageSetValue*>(m_imageValue.get())->cachedImageSet(loader, deviceScaleFactor);
 
     if (!m_accessedImage) {
         m_accessedImage = true;
@@ -154,11 +153,11 @@
     return 0;
 }
 
-StyleImage* CSSCursorImageValue::cachedOrPendingImage(Document* document)
+StyleImage* CSSCursorImageValue::cachedOrPendingImage(float deviceScaleFactor)
 {
     // Need to delegate completely so that changes in device scale factor can be handled appropriately.
     if (m_imageValue->isImageSetValue())
-        return static_cast<CSSImageSetValue*>(m_imageValue.get())->cachedOrPendingImageSet(document);
+        return static_cast<CSSImageSetValue*>(m_imageValue.get())->cachedOrPendingImageSet(deviceScaleFactor);
 
     if (!m_image)
         m_image = StylePendingImage::create(this);
@@ -204,7 +203,7 @@
 {
     MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
     m_imageValue->reportMemoryUsage(memoryObjectInfo);
-    // No need to report m_image as it is counted as part of RenderArena.
+    // FIXME: report m_image. It has never been allocated from any of our rendering custom heaps.
     info.addMember(m_referencedElements, "referencedElements");
 }
 
diff --git a/Source/core/css/CSSCursorImageValue.h b/Source/core/css/CSSCursorImageValue.h
index e3a85e2..04723dd 100644
--- a/Source/core/css/CSSCursorImageValue.h
+++ b/Source/core/css/CSSCursorImageValue.h
@@ -27,7 +27,6 @@
 
 namespace WebCore {
 
-class Document;
 class Element;
 class SVGElement;
 
@@ -52,8 +51,8 @@
     String customCssText() const;
 
     bool updateIfSVGCursorIsUsed(Element*);
-    StyleImage* cachedImage(CachedResourceLoader*);
-    StyleImage* cachedOrPendingImage(Document*);
+    StyleImage* cachedImage(CachedResourceLoader*, float deviceScaleFactor);
+    StyleImage* cachedOrPendingImage(float deviceScaleFactor);
 
     void removeReferencedElement(SVGElement*);
 
diff --git a/Source/core/css/CSSFilterValue.h b/Source/core/css/CSSFilterValue.h
index 22500ed..5bf7355 100644
--- a/Source/core/css/CSSFilterValue.h
+++ b/Source/core/css/CSSFilterValue.h
@@ -28,7 +28,6 @@
 
 #include "core/css/CSSValueList.h"
 #include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSFontFace.cpp b/Source/core/css/CSSFontFace.cpp
index 4400c92..9196a3c 100644
--- a/Source/core/css/CSSFontFace.cpp
+++ b/Source/core/css/CSSFontFace.cpp
@@ -31,7 +31,6 @@
 #include "core/css/CSSSegmentedFontFace.h"
 #include "core/css/FontLoader.h"
 #include "core/dom/Document.h"
-#include "RuntimeEnabledFeatures.h"
 #include "core/platform/graphics/SimpleFontData.h"
 
 namespace WebCore {
@@ -88,11 +87,11 @@
     CSSFontSelector* fontSelector = (*m_segmentedFontFaces.begin())->fontSelector();
     fontSelector->fontLoaded();
 
-    if (RuntimeEnabledFeatures::fontLoadEventsEnabled() && m_loadState == Loading) {
+    if (m_loadState == Loading) {
         if (source->ensureFontData())
-            notifyFontLoader(Loaded);
+            setLoadState(Loaded);
         else if (!isValid())
-            notifyFontLoader(Error);
+            setLoadState(Error);
     }
 
     HashSet<CSSSegmentedFontFace*>::iterator end = m_segmentedFontFaces.end();
@@ -109,25 +108,25 @@
     ASSERT(!m_segmentedFontFaces.isEmpty());
     CSSFontSelector* fontSelector = (*m_segmentedFontFaces.begin())->fontSelector();
 
-    if (RuntimeEnabledFeatures::fontLoadEventsEnabled() && m_loadState == NotLoaded)
-        notifyFontLoader(Loading);
+    if (m_loadState == NotLoaded)
+        setLoadState(Loading);
 
     size_t size = m_sources.size();
     for (size_t i = 0; i < size; ++i) {
         if (RefPtr<SimpleFontData> result = m_sources[i]->getFontData(fontDescription, syntheticBold, syntheticItalic, fontSelector)) {
             m_activeSource = m_sources[i].get();
-            if (RuntimeEnabledFeatures::fontLoadEventsEnabled() && m_loadState == Loading && m_sources[i]->isLoaded())
-                notifyFontLoader(Loaded);
+            if (m_loadState == Loading && m_sources[i]->isLoaded())
+                setLoadState(Loaded);
             return result.release();
         }
     }
 
-    if (RuntimeEnabledFeatures::fontLoadEventsEnabled() && m_loadState == Loading)
-        notifyFontLoader(Error);
+    if (m_loadState == Loading)
+        setLoadState(Error);
     return 0;
 }
 
-void CSSFontFace::notifyFontLoader(LoadState newState)
+void CSSFontFace::setLoadState(LoadState newState)
 {
     m_loadState = newState;
 
diff --git a/Source/core/css/CSSFontFace.h b/Source/core/css/CSSFontFace.h
index 0acf394..31bf1b5 100644
--- a/Source/core/css/CSSFontFace.h
+++ b/Source/core/css/CSSFontFace.h
@@ -29,12 +29,11 @@
 #include "core/css/CSSFontFaceRule.h"
 #include "core/css/CSSFontFaceSource.h"
 #include "core/platform/graphics/FontTraitsMask.h"
-#include <wtf/Forward.h>
-#include <wtf/HashSet.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/unicode/Unicode.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/HashSet.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -99,6 +98,7 @@
     {
         UNUSED_PARAM(rule);
     }
+    void setLoadState(LoadState);
 
     FontTraitsMask m_traitsMask;
     Vector<UnicodeRange> m_ranges;
@@ -108,7 +108,6 @@
     bool m_isLocalFallback;
     LoadState m_loadState;
     RefPtr<CSSFontFaceRule> m_rule;
-    void notifyFontLoader(LoadState);
 };
 
 }
diff --git a/Source/core/css/CSSFontFaceLoadEvent.h b/Source/core/css/CSSFontFaceLoadEvent.h
index ac1a137..c2aca89 100644
--- a/Source/core/css/CSSFontFaceLoadEvent.h
+++ b/Source/core/css/CSSFontFaceLoadEvent.h
@@ -32,12 +32,11 @@
 #define CSSFontFaceLoadEvent_h
 
 #include "core/css/CSSFontFaceRule.h"
-#include "core/css/CSSValue.h"
 #include "core/dom/DOMError.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSFontSelector.h b/Source/core/css/CSSFontSelector.h
index 625dc0a..7c4da6d 100644
--- a/Source/core/css/CSSFontSelector.h
+++ b/Source/core/css/CSSFontSelector.h
@@ -29,11 +29,10 @@
 #include "core/loader/cache/CachedResourceHandle.h"
 #include "core/platform/Timer.h"
 #include "core/platform/graphics/FontSelector.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/StringHash.h>
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/HashSet.h"
+#include "wtf/text/StringHash.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSFunctionValue.cpp b/Source/core/css/CSSFunctionValue.cpp
index 07af686..176f856 100644
--- a/Source/core/css/CSSFunctionValue.cpp
+++ b/Source/core/css/CSSFunctionValue.cpp
@@ -29,8 +29,7 @@
 #include "core/css/CSSParserValues.h"
 #include "core/css/CSSValueList.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/PassOwnPtr.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSGradientValue.cpp b/Source/core/css/CSSGradientValue.cpp
index 2ad4d59..4c1fe6b 100644
--- a/Source/core/css/CSSGradientValue.cpp
+++ b/Source/core/css/CSSGradientValue.cpp
@@ -28,7 +28,7 @@
 
 #include "CSSValueKeywords.h"
 #include "core/css/CSSCalculationValue.h"
-#include "core/css/resolver/StyleResolver.h"
+#include "core/css/resolver/StyleResolverState.h"
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/platform/graphics/GeneratorGeneratedImage.h"
@@ -114,11 +114,11 @@
     { }
 };
 
-PassRefPtr<CSSGradientValue> CSSGradientValue::gradientWithStylesResolved(StyleResolver* styleResolver)
+PassRefPtr<CSSGradientValue> CSSGradientValue::gradientWithStylesResolved(StyleResolverState& styleResolverState)
 {
     bool derived = false;
     for (unsigned i = 0; i < m_stops.size(); i++)
-        if (styleResolver->colorFromPrimitiveValueIsDerivedFromElement(m_stops[i].m_color.get())) {
+        if (m_stops[i].m_color->colorIsDerivedFromElement()) {
             m_stops[i].m_colorIsDerivedFromElement = true;
             derived = true;
             break;
@@ -137,7 +137,7 @@
     }
 
     for (unsigned i = 0; i < result->m_stops.size(); i++)
-        result->m_stops[i].m_resolvedColor = styleResolver->colorFromPrimitiveValue(result->m_stops[i].m_color.get());
+        result->m_stops[i].m_resolvedColor = styleResolverState.resolveColorFromPrimitiveValue(result->m_stops[i].m_color.get());
 
     return result.release();
 }
diff --git a/Source/core/css/CSSGradientValue.h b/Source/core/css/CSSGradientValue.h
index ab8576f..1ed7c95 100644
--- a/Source/core/css/CSSGradientValue.h
+++ b/Source/core/css/CSSGradientValue.h
@@ -35,6 +35,7 @@
 
 class FloatPoint;
 class Gradient;
+class StyleResolverState;
 
 enum CSSGradientType {
     CSSDeprecatedLinearGradient,
@@ -89,7 +90,7 @@
     bool knownToBeOpaque(const RenderObject*) const;
 
     void loadSubimages(CachedResourceLoader*) { }
-    PassRefPtr<CSSGradientValue> gradientWithStylesResolved(StyleResolver*);
+    PassRefPtr<CSSGradientValue> gradientWithStylesResolved(StyleResolverState&);
 
 protected:
     CSSGradientValue(ClassType classType, CSSGradientRepeat repeat, CSSGradientType gradientType)
diff --git a/Source/core/css/CSSGrammar.y.in b/Source/core/css/CSSGrammar.y.in
index 9a4c5db..b398b89 100644
--- a/Source/core/css/CSSGrammar.y.in
+++ b/Source/core/css/CSSGrammar.y.in
@@ -77,6 +77,7 @@
     case CALCFUNCTION:
     case MINFUNCTION:
     case MAXFUNCTION:
+    case VARFUNCTION:
     case VAR_DEFINITION:
     case UNICODERANGE:
         return true;
@@ -132,17 +133,16 @@
 %token HOST_SYM
 %token CHARSET_SYM
 %token NAMESPACE_SYM
-%token VARFUNCTION
 %token VIEWPORT_RULE_SYM
 %token INTERNAL_DECLS_SYM
 %token INTERNAL_MEDIALIST_SYM
 %token INTERNAL_RULE_SYM
 %token INTERNAL_SELECTOR_SYM
 %token INTERNAL_VALUE_SYM
-%token WEBKIT_KEYFRAME_RULE_SYM
+%token INTERNAL_KEYFRAME_RULE_SYM
+%token INTERNAL_SUPPORTS_CONDITION_SYM
 %token WEBKIT_KEYFRAMES_SYM
 %token WEBKIT_REGION_RULE_SYM
-%token WEBKIT_SUPPORTS_CONDITION_SYM
 %token WEBKIT_FILTER_RULE_SYM
 %token <marginBox> TOPLEFTCORNER_SYM
 %token <marginBox> TOPLEFT_SYM
@@ -214,6 +214,7 @@
 %token <string> CALCFUNCTION
 %token <string> MINFUNCTION
 %token <string> MAXFUNCTION
+%token <string> VARFUNCTION
 %token <string> VAR_DEFINITION
 
 %token <string> UNICODERANGE
@@ -234,7 +235,7 @@
 %type <rule> rule
 %type <rule> valid_rule
 %type <ruleList> block_rule_body
-%type <ruleList> block_rule_list 
+%type <ruleList> block_rule_list
 %type <ruleList> region_block_rule_body
 %type <ruleList> region_block_rule_list
 %type <rule> block_rule
@@ -328,36 +329,36 @@
 
 stylesheet:
     maybe_charset maybe_sgml rule_list
-  | internal_decls maybe_space
-  | internal_rule maybe_space
-  | internal_selector maybe_space
-  | internal_value maybe_space
+  | internal_decls
+  | internal_rule
+  | internal_selector
+  | internal_value
   | internal_medialist
-  | webkit_keyframe_rule maybe_space
-  | webkit_supports_condition maybe_space
+  | internal_keyframe_rule
+  | internal_supports_condition
   ;
 
 internal_rule:
-    INTERNAL_RULE_SYM '{' maybe_space valid_rule maybe_space '}' {
-        parser->m_rule = $4;
+    INTERNAL_RULE_SYM maybe_space valid_rule maybe_space TOKEN_EOF {
+        parser->m_rule = $3;
     }
 ;
 
-webkit_keyframe_rule:
-    WEBKIT_KEYFRAME_RULE_SYM '{' maybe_space keyframe_rule maybe_space '}' {
-        parser->m_keyframe = $4;
+internal_keyframe_rule:
+    INTERNAL_KEYFRAME_RULE_SYM maybe_space keyframe_rule maybe_space TOKEN_EOF {
+        parser->m_keyframe = $3;
     }
 ;
 
 internal_decls:
-    INTERNAL_DECLS_SYM '{' maybe_space_before_declaration declaration_list '}' {
+    INTERNAL_DECLS_SYM maybe_space_before_declaration declaration_list TOKEN_EOF {
         /* can be empty */
     }
 ;
 
 internal_value:
-    INTERNAL_VALUE_SYM '{' maybe_space expr '}' {
-        parser->m_valueList = parser->sinkFloatingValueList($4);
+    INTERNAL_VALUE_SYM maybe_space expr TOKEN_EOF {
+        parser->m_valueList = parser->sinkFloatingValueList($3);
         int oldParsedProperties = parser->m_parsedProperties.size();
         if (!parser->parseValue(parser->m_id, parser->m_important))
             parser->rollbackLastProperties(parser->m_parsedProperties.size() - oldParsedProperties);
@@ -366,21 +367,21 @@
 ;
 
 internal_medialist:
-    INTERNAL_MEDIALIST_SYM maybe_space maybe_media_list TOKEN_EOF {
-        parser->m_mediaList = $3;
+    INTERNAL_MEDIALIST_SYM maybe_space location_label maybe_media_list TOKEN_EOF {
+        parser->m_mediaList = $4;
     }
 ;
 
 internal_selector:
-    INTERNAL_SELECTOR_SYM '{' maybe_space selector_list '}' {
+    INTERNAL_SELECTOR_SYM maybe_space selector_list TOKEN_EOF {
         if (parser->m_selectorListForParseSelector)
-            parser->m_selectorListForParseSelector->adoptSelectorVector(*$4);
+            parser->m_selectorListForParseSelector->adoptSelectorVector(*$3);
     }
 ;
 
-webkit_supports_condition:
-    WEBKIT_SUPPORTS_CONDITION_SYM '{' maybe_space supports_condition '}' {
-        parser->m_supportsCondition = $4;
+internal_supports_condition:
+    INTERNAL_SUPPORTS_CONDITION_SYM maybe_space supports_condition TOKEN_EOF {
+        parser->m_supportsCondition = $3;
     }
 ;
 
@@ -410,8 +411,18 @@
   | %prec LOWEST_PREC TOKEN_EOF
   ;
 
+closing_square_bracket:
+    ']'
+  | %prec LOWEST_PREC TOKEN_EOF
+  ;
+
+semi_or_eof:
+    ';'
+  | TOKEN_EOF
+  ;
+
 charset:
-  CHARSET_SYM maybe_space STRING maybe_space ';' {
+  CHARSET_SYM maybe_space STRING maybe_space semi_or_eof {
      if (parser->m_styleSheet)
          parser->m_styleSheet->parserSetEncodingFromCharsetRule($3);
      parser->startEndUnknownRule();
@@ -457,9 +468,9 @@
   | block_rule_list error error_location rule_error_recovery {
         parser->reportError($3, CSSParser::InvalidRuleError);
     }
-    ; 
+    ;
 
-block_rule_list: 
+block_rule_list:
     /* empty */ { $$ = 0; }
   | block_rule_list block_rule maybe_sgml {
       $$ = $1;
@@ -523,13 +534,10 @@
     ;
 
 import:
-    before_import_rule IMPORT_SYM at_import_header_end_maybe_space string_or_uri maybe_space maybe_media_list ';' {
-        $$ = parser->createImportRule($4, $6);
+    before_import_rule IMPORT_SYM at_import_header_end_maybe_space string_or_uri maybe_space location_label maybe_media_list semi_or_eof {
+        $$ = parser->createImportRule($4, $7);
     }
-  | before_import_rule IMPORT_SYM at_import_header_end_maybe_space string_or_uri maybe_space maybe_media_list TOKEN_EOF {
-        $$ = parser->createImportRule($4, $6);
-    }
-  | before_import_rule IMPORT_SYM at_import_header_end_maybe_space string_or_uri maybe_space maybe_media_list invalid_block {
+  | before_import_rule IMPORT_SYM at_import_header_end_maybe_space string_or_uri maybe_space location_label maybe_media_list invalid_block {
         $$ = 0;
         parser->endRuleBody(true);
     }
@@ -546,7 +554,7 @@
     ;
 
 namespace:
-    before_namespace_rule NAMESPACE_SYM maybe_space maybe_ns_prefix string_or_uri maybe_space ';' {
+    before_namespace_rule NAMESPACE_SYM maybe_space maybe_ns_prefix string_or_uri maybe_space semi_or_eof {
         parser->addNamespace($4, $5);
         $$ = 0;
     }
@@ -560,7 +568,7 @@
 
 maybe_ns_prefix:
 /* empty */ { $$.clear(); }
-| IDENT maybe_space { $$ = $1; }
+| IDENT maybe_space
 ;
 
 string_or_uri:
@@ -634,10 +642,11 @@
 media_query:
     valid_media_query
     | valid_media_query error error_location rule_error_recovery {
+        parser->reportError(parser->lastLocationLabel(), CSSParser::InvalidMediaQueryError);
         $$ = parser->createFloatingNotAllQuery();
     }
     | error error_location rule_error_recovery {
-        parser->reportError($2);
+        parser->reportError(parser->lastLocationLabel(), CSSParser::InvalidMediaQueryError);
         $$ = parser->createFloatingNotAllQuery();
     }
     ;
@@ -653,26 +662,23 @@
     media_query {
         $$ = parser->createMediaQuerySet();
         $$->addMediaQuery(parser->sinkFloatingMediaQuery($1));
-        parser->updateLastMediaLine($$);
     }
     | mq_list media_query {
         $$ = $1;
         $$->addMediaQuery(parser->sinkFloatingMediaQuery($2));
-        parser->updateLastMediaLine($$);
     }
     | mq_list {
         $$ = $1;
         $$->addMediaQuery(parser->sinkFloatingMediaQuery(parser->createFloatingNotAllQuery()));
-        parser->updateLastMediaLine($$);
     }
     ;
 
 mq_list:
-    media_query ',' maybe_space {
+    media_query ',' maybe_space location_label {
         $$ = parser->createMediaQuerySet();
         $$->addMediaQuery(parser->sinkFloatingMediaQuery($1));
     }
-    | mq_list media_query ',' maybe_space {
+    | mq_list media_query ',' maybe_space location_label {
         $$ = $1;
         $$->addMediaQuery(parser->sinkFloatingMediaQuery($2));
     }
@@ -697,13 +703,13 @@
     ;
 
 media:
-    before_media_rule MEDIA_SYM maybe_space media_list at_rule_header_end '{' at_rule_body_start maybe_space block_rule_body closing_brace {
-        $$ = parser->createMediaRule($4, $9);
+    before_media_rule MEDIA_SYM maybe_space location_label media_list at_rule_header_end '{' at_rule_body_start maybe_space block_rule_body closing_brace {
+        $$ = parser->createMediaRule($5, $10);
     }
     | before_media_rule MEDIA_SYM at_rule_header_end_maybe_space '{' at_rule_body_start maybe_space block_rule_body closing_brace {
         $$ = parser->createMediaRule(0, $7);
     }
-    | before_media_rule MEDIA_SYM maybe_space media_list ';' {
+    | before_media_rule MEDIA_SYM maybe_space location_label media_list semi_or_eof {
         $$ = 0;
         parser->endRuleBody(true);
     }
@@ -714,9 +720,7 @@
     ;
 
 medium:
-  IDENT maybe_space {
-      $$ = $1;
-  }
+  IDENT maybe_space
   ;
 
 supports:
@@ -777,18 +781,18 @@
     ;
 
 supports_condition_in_parens:
-    '(' maybe_space supports_condition ')' maybe_space {
+    '(' maybe_space supports_condition closing_parenthesis maybe_space {
         $$ = $3;
     }
     | supports_declaration_condition
-    | '(' error error_location error_recovery ')' maybe_space {
+    | '(' error error_location error_recovery closing_parenthesis maybe_space {
         parser->reportError($3, CSSParser::InvalidSupportsConditionError);
         $$ = false;
     }
     ;
 
 supports_declaration_condition:
-    '(' maybe_space IDENT maybe_space ':' maybe_space expr prio ')' maybe_space {
+    '(' maybe_space IDENT maybe_space ':' maybe_space expr prio closing_parenthesis maybe_space {
         $$ = false;
         CSSPropertyID id = cssPropertyID($3);
         if (id != CSSPropertyInvalid) {
@@ -802,7 +806,7 @@
         parser->m_valueList = nullptr;
         parser->endProperty($8, false);
     }
-    | '(' maybe_space IDENT maybe_space ':' maybe_space error error_recovery ')' maybe_space {
+    | '(' maybe_space IDENT maybe_space ':' maybe_space error error_recovery closing_parenthesis maybe_space {
         $$ = false;
         parser->endProperty(false, false, CSSParser::GeneralError);
     }
@@ -815,15 +819,15 @@
     ;
 
 keyframes:
-    before_keyframes_rule WEBKIT_KEYFRAMES_SYM maybe_space keyframe_name at_rule_header_end_maybe_space '{' at_rule_body_start maybe_space keyframes_rule closing_brace {
-        $$ = parser->createKeyframesRule($4, parser->sinkFloatingKeyframeVector($9));
+    before_keyframes_rule WEBKIT_KEYFRAMES_SYM maybe_space keyframe_name at_rule_header_end_maybe_space '{' at_rule_body_start maybe_space location_label keyframes_rule closing_brace {
+        $$ = parser->createKeyframesRule($4, parser->sinkFloatingKeyframeVector($10));
     }
   | before_keyframes_rule WEBKIT_KEYFRAMES_SYM at_rule_recovery {
         $$ = 0;
         parser->endRuleBody(true);
     }
     ;
-  
+
 keyframe_name:
     IDENT
     | STRING
@@ -838,14 +842,15 @@
 keyframe_rule_list:
     /* empty */ {
         $$ = parser->createFloatingKeyframeVector();
+        parser->resumeErrorLogging();
     }
-    |  keyframe_rule_list keyframe_rule maybe_space {
+    |  keyframe_rule_list keyframe_rule maybe_space location_label {
         $$ = $1;
-        if ($2)
-            $$->append($2);
+        $$->append($2);
     }
-    | keyframe_rule_list keyframes_error_recovery invalid_block {
+    | keyframe_rule_list keyframes_error_recovery invalid_block maybe_space location_label {
         parser->clearProperties();
+        parser->resumeErrorLogging();
     }
     ;
 
@@ -862,8 +867,7 @@
     }
     | key_list ',' maybe_space key maybe_space {
         $$ = $1;
-        if ($$)
-            $$->addValue(parser->sinkFloatingValue($4));
+        $$->addValue(parser->sinkFloatingValue($4));
     }
     ;
 
@@ -883,7 +887,10 @@
     ;
 
 keyframes_error_recovery:
-    error error_location rule_error_recovery;
+    error rule_error_recovery {
+        parser->reportError(parser->lastLocationLabel(), CSSParser::InvalidKeyframeSelectorError);
+    }
+    ;
 
 before_page_rule:
     /* empty */ {
@@ -917,15 +924,12 @@
     }
     | IDENT pseudo_page maybe_space {
         $$ = $2;
-        if ($$) {
-            $$->prependTagSelector(QualifiedName(nullAtom, $1, parser->m_defaultNamespace));
-            $$->setForPage();
-        }
+        $$->prependTagSelector(QualifiedName(nullAtom, $1, parser->m_defaultNamespace));
+        $$->setForPage();
     }
     | pseudo_page maybe_space {
         $$ = $1;
-        if ($$)
-            $$->setForPage();
+        $$->setForPage();
     }
     | /* empty */ {
         $$ = parser->createFloatingSelector();
@@ -1099,8 +1103,8 @@
   ;
 
 maybe_unary_operator:
-    unary_operator { $$ = $1; }
-    | { $$ = 1; }
+    unary_operator
+    | /* empty */ { $$ = 1; }
     ;
 
 unary_operator:
@@ -1194,9 +1198,9 @@
 namespace_selector:
     /* empty */ '|' { $$.clear(); }
     | '*' '|' { static LChar star = '*'; $$.init(&star, 1); }
-    | IDENT '|' { $$ = $1; }
-;
-    
+    | IDENT '|'
+    ;
+
 simple_selector:
     element_name {
         $$ = parser->createFloatingSelectorWithTagName(QualifiedName(nullAtom, $1, parser->m_defaultNamespace));
@@ -1252,9 +1256,7 @@
   ;
 
 specifier_list:
-    specifier {
-        $$ = $1;
-    }
+    specifier
     | specifier_list specifier {
         $$ = parser->rewriteSpecifiers($1, $2);
     }
@@ -1303,29 +1305,29 @@
     ;
 
 attrib:
-    '[' maybe_space attr_name ']' {
+    '[' maybe_space attr_name closing_square_bracket {
         $$ = parser->createFloatingSelector();
         $$->setAttribute(QualifiedName(nullAtom, $3, nullAtom));
         $$->setMatch(CSSSelector::Set);
     }
-    | '[' maybe_space attr_name match maybe_space ident_or_string maybe_space ']' {
+    | '[' maybe_space attr_name match maybe_space ident_or_string maybe_space closing_square_bracket {
         $$ = parser->createFloatingSelector();
         $$->setAttribute(QualifiedName(nullAtom, $3, nullAtom));
         $$->setMatch((CSSSelector::Match)$4);
         $$->setValue($6);
     }
-    | '[' maybe_space namespace_selector attr_name ']' {
+    | '[' maybe_space namespace_selector attr_name closing_square_bracket {
         $$ = parser->createFloatingSelector();
         $$->setAttribute(parser->determineNameInNamespace($3, $4));
         $$->setMatch(CSSSelector::Set);
     }
-    | '[' maybe_space namespace_selector attr_name match maybe_space ident_or_string maybe_space ']' {
+    | '[' maybe_space namespace_selector attr_name match maybe_space ident_or_string maybe_space closing_square_bracket {
         $$ = parser->createFloatingSelector();
         $$->setAttribute(parser->determineNameInNamespace($3, $4));
         $$->setMatch((CSSSelector::Match)$5);
         $$->setValue($7);
     }
-    | '[' selector_recovery ']' {
+    | '[' selector_recovery closing_square_bracket {
         YYERROR;
     }
   ;
@@ -1368,27 +1370,31 @@
     }
 
 pseudo:
-    ':' IDENT {
+    ':' error_location IDENT {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoClass);
-        parser->tokenToLowerCase($2);
-        $$->setValue($2);
-        CSSSelector::PseudoType type = $$->pseudoType();
-        if (type == CSSSelector::PseudoUnknown)
-            YYERROR;
-    }
-    | ':' ':' IDENT {
-        $$ = parser->createFloatingSelector();
-        $$->setMatch(CSSSelector::PseudoElement);
         parser->tokenToLowerCase($3);
         $$->setValue($3);
+        CSSSelector::PseudoType type = $$->pseudoType();
+        if (type == CSSSelector::PseudoUnknown) {
+            parser->reportError($2, CSSParser::InvalidSelectorPseudoError);
+            YYERROR;
+        }
+    }
+    | ':' ':' error_location IDENT {
+        $$ = parser->createFloatingSelector();
+        $$->setMatch(CSSSelector::PseudoElement);
+        parser->tokenToLowerCase($4);
+        $$->setValue($4);
         // FIXME: This call is needed to force selector to compute the pseudoType early enough.
         CSSSelector::PseudoType type = $$->pseudoType();
-        if (type == CSSSelector::PseudoUnknown)
+        if (type == CSSSelector::PseudoUnknown) {
+            parser->reportError($3, CSSParser::InvalidSelectorPseudoError);
             YYERROR;
+        }
     }
     // used by ::cue(:past/:future)
-    | ':' ':' CUEFUNCTION maybe_space simple_selector_list maybe_space ')' {
+    | ':' ':' CUEFUNCTION maybe_space simple_selector_list maybe_space closing_parenthesis {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoClass);
         $$->adoptSelectorVector(*parser->sinkFloatingSelectorVector($5));
@@ -1397,17 +1403,17 @@
         if (type != CSSSelector::PseudoCue)
             YYERROR;
     }
-    | ':' ':' CUEFUNCTION selector_recovery ')' {
+    | ':' ':' CUEFUNCTION selector_recovery closing_parenthesis {
         YYERROR;
     }
-    | ':' ':' DISTRIBUTEDFUNCTION maybe_space relative_selector ')' {
+    | ':' ':' DISTRIBUTEDFUNCTION maybe_space relative_selector closing_parenthesis {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoElement);
         $$->setFunctionArgumentSelector($5);
         parser->tokenToLowerCase($3);
         $$->setValue($3);
     }
-    | ':' ':' DISTRIBUTEDFUNCTION selector_recovery ')' {
+    | ':' ':' DISTRIBUTEDFUNCTION selector_recovery closing_parenthesis {
         YYERROR;
     }
     // use by :-webkit-any.
@@ -1415,7 +1421,7 @@
     // Use simple_selector_list for now to match -moz-any.
     // See http://lists.w3.org/Archives/Public/www-style/2010Sep/0566.html for some
     // related discussion with respect to :not.
-    | ':' ANYFUNCTION maybe_space simple_selector_list maybe_space ')' {
+    | ':' ANYFUNCTION maybe_space simple_selector_list maybe_space closing_parenthesis {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoClass);
         $$->adoptSelectorVector(*parser->sinkFloatingSelectorVector($4));
@@ -1425,11 +1431,11 @@
         if (type != CSSSelector::PseudoAny)
             YYERROR;
     }
-    | ':' ANYFUNCTION selector_recovery ')' {
+    | ':' ANYFUNCTION selector_recovery closing_parenthesis {
         YYERROR;
     }
     // used by :nth-*(ax+b)
-    | ':' FUNCTION maybe_space NTH maybe_space ')' {
+    | ':' FUNCTION maybe_space NTH maybe_space closing_parenthesis {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoClass);
         $$->setArgument($4);
@@ -1439,7 +1445,7 @@
             YYERROR;
     }
     // used by :nth-*
-    | ':' FUNCTION maybe_space maybe_unary_operator INTEGER maybe_space ')' {
+    | ':' FUNCTION maybe_space maybe_unary_operator INTEGER maybe_space closing_parenthesis {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoClass);
         $$->setArgument(String::number($4 * $5));
@@ -1449,7 +1455,7 @@
             YYERROR;
     }
     // used by :nth-*(odd/even) and :lang
-    | ':' FUNCTION maybe_space IDENT maybe_space ')' {
+    | ':' FUNCTION maybe_space IDENT maybe_space closing_parenthesis {
         $$ = parser->createFloatingSelector();
         $$->setMatch(CSSSelector::PseudoClass);
         $$->setArgument($4);
@@ -1466,11 +1472,11 @@
                 YYERROR;
         }
     }
-    | ':' FUNCTION selector_recovery ')' {
+    | ':' FUNCTION selector_recovery closing_parenthesis {
         YYERROR;
     }
     // used by :not
-    | ':' NOTFUNCTION maybe_space simple_selector maybe_space ')' {
+    | ':' NOTFUNCTION maybe_space simple_selector maybe_space closing_parenthesis {
         if (!$4->isSimple())
             YYERROR;
         else {
@@ -1485,7 +1491,7 @@
             $$->setValue($2);
         }
     }
-    | ':' NOTFUNCTION selector_recovery ')' {
+    | ':' NOTFUNCTION selector_recovery closing_parenthesis {
         YYERROR;
     }
   ;
@@ -1495,17 +1501,11 @@
 
 declaration_list:
     /* empty */ { $$ = false; }
-    | declaration {
-        $$ = $1;
-    }
+    | declaration
     | decl_list declaration {
-        $$ = $1;
-        if ( $2 )
-            $$ = $2;
+        $$ = $1 || $2;
     }
-    | decl_list {
-        $$ = $1;
-    }
+    | decl_list
     ;
 
 decl_list:
@@ -1515,9 +1515,7 @@
     }
     | decl_list declaration ';' maybe_space {
         parser->startProperty();
-        $$ = $1;
-        if ($2)
-            $$ = $2;
+        $$ = $1 || $2;
     }
     ;
 
@@ -1591,10 +1589,13 @@
     }
     | expr operator term {
         $$ = $1;
-        if ($2)
-            $$->addValue(makeOperatorValue($2));
+        $$->addValue(makeOperatorValue($2));
         $$->addValue(parser->sinkFloatingValue($3));
     }
+    | expr term {
+        $$ = $1;
+        $$->addValue(parser->sinkFloatingValue($2));
+    }
   ;
 
 expr_recovery:
@@ -1610,13 +1611,10 @@
   | ',' maybe_space {
         $$ = ',';
     }
-  | /* empty */ {
-        $$ = 0;
-  }
   ;
 
 term:
-  unary_term maybe_space { $$ = $1; }
+  unary_term maybe_space
   | unary_operator unary_term maybe_space { $$ = $2; $$.fValue *= $1; }
   | STRING maybe_space { $$.id = CSSValueInvalid; $$.string = $1; $$.unit = CSSPrimitiveValue::CSS_STRING; }
   | IDENT maybe_space {
@@ -1636,16 +1634,13 @@
       $$.string = $3;
       $$.unit = CSSPrimitiveValue::CSS_VARIABLE_NAME;
   }
+  | VARFUNCTION maybe_space expr_recovery closing_parenthesis {
+      YYERROR;
+  }
   /* FIXME: according to the specs a function can have a unary_operator in front. I know no case where this makes sense */
-  | function maybe_space {
-      $$ = $1;
-  }
-  | calc_function maybe_space {
-      $$ = $1;
-  }
-  | min_or_max_function maybe_space {
-      $$ = $1;
-  }
+  | function maybe_space
+  | calc_function maybe_space
+  | min_or_max_function maybe_space
   | '%' maybe_space { /* Handle width: %; */
       $$.id = CSSValueInvalid; $$.unit = 0;
   }
@@ -1701,7 +1696,7 @@
   ;
 
 calc_func_term:
-  unary_term { $$ = $1; }
+  unary_term
   | VARFUNCTION maybe_space IDENT closing_parenthesis {
       $$.id = CSSValueInvalid;
       $$.string = $3;
@@ -1760,9 +1755,7 @@
   ;
 
 calc_func_expr_list:
-    calc_func_expr calc_maybe_space {
-        $$ = $1;
-    }    
+    calc_func_expr calc_maybe_space
     | calc_func_expr_list ',' maybe_space calc_func_expr calc_maybe_space {
         $$ = $1;
         $$->addValue(makeOperatorValue(','));
@@ -1781,18 +1774,14 @@
 
 
 min_or_max:
-    MINFUNCTION {
-        $$ = $1;
-    }
-    | MAXFUNCTION {
-        $$ = $1;
-    }
+    MINFUNCTION
+    | MAXFUNCTION
     ;
 
 min_or_max_function:
     min_or_max maybe_space calc_func_expr_list closing_parenthesis {
         $$.setFromFunction(parser->createFloatingFunction($1, parser->sinkFloatingValueList($3)));
-    } 
+    }
     | min_or_max maybe_space expr_recovery closing_parenthesis {
         YYERROR;
     }
@@ -1800,7 +1789,7 @@
 
 invalid_at:
     ATKEYWORD
-  | margin_sym 
+  | margin_sym
     ;
 
 at_rule_recovery:
@@ -1814,7 +1803,7 @@
     ;
 
 at_rule_end:
-    at_invalid_rule_header_end ';'
+    at_invalid_rule_header_end semi_or_eof
   | at_invalid_rule_header_end invalid_block
     ;
 
@@ -1843,8 +1832,7 @@
     ;
 
 invalid_square_brackets_block:
-    '[' error_recovery ']'
-  | '[' error_recovery TOKEN_EOF
+    '[' error_recovery closing_square_bracket
     ;
 
 invalid_parentheses_block:
@@ -1859,6 +1847,11 @@
     }
     ;
 
+location_label: {
+        parser->setLocationLabel(parser->currentLocation());
+    }
+    ;
+
 error_recovery:
     /* empty */
   | error_recovery error
diff --git a/Source/core/css/CSSGroupingRule.cpp b/Source/core/css/CSSGroupingRule.cpp
index 90b5256..3a592ff 100644
--- a/Source/core/css/CSSGroupingRule.cpp
+++ b/Source/core/css/CSSGroupingRule.cpp
@@ -38,8 +38,8 @@
 #include "core/css/StyleRule.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/MemoryInstrumentationVector.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/MemoryInstrumentationVector.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSImageGeneratorValue.cpp b/Source/core/css/CSSImageGeneratorValue.cpp
index a9f5eb6..a850d34 100644
--- a/Source/core/css/CSSImageGeneratorValue.cpp
+++ b/Source/core/css/CSSImageGeneratorValue.cpp
@@ -31,9 +31,8 @@
 #include "core/css/CSSGradientValue.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/platform/graphics/Image.h"
-#include <wtf/MemoryInstrumentationHashCountedSet.h>
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/MemoryInstrumentationHashCountedSet.h"
+#include "wtf/MemoryInstrumentationHashMap.h"
 
 
 namespace WTF {
diff --git a/Source/core/css/CSSImageSetValue.cpp b/Source/core/css/CSSImageSetValue.cpp
index 1353606..387081e 100644
--- a/Source/core/css/CSSImageSetValue.cpp
+++ b/Source/core/css/CSSImageSetValue.cpp
@@ -34,7 +34,6 @@
 #include "core/loader/cache/CachedResourceLoader.h"
 #include "core/loader/cache/CachedResourceRequest.h"
 #include "core/loader/cache/CachedResourceRequestInitiators.h"
-#include "core/page/Page.h"
 #include "core/rendering/style/StyleCachedImageSet.h"
 #include "core/rendering/style/StylePendingImage.h"
 #include <wtf/MemoryInstrumentationVector.h>
@@ -90,15 +89,11 @@
     return image;
 }
 
-StyleCachedImageSet* CSSImageSetValue::cachedImageSet(CachedResourceLoader* loader)
+StyleCachedImageSet* CSSImageSetValue::cachedImageSet(CachedResourceLoader* loader, float deviceScaleFactor)
 {
     ASSERT(loader);
 
-    Document* document = loader->document();
-    if (Page* page = document->page())
-        m_scaleFactor = page->deviceScaleFactor();
-    else
-        m_scaleFactor = 1;
+    m_scaleFactor = deviceScaleFactor;
 
     if (!m_imagesInSet.size())
         fillImageSet();
@@ -108,25 +103,23 @@
         // All forms of scale should be included: Page::pageScaleFactor(), Frame::pageZoomFactor(),
         // and any CSS transforms. https://bugs.webkit.org/show_bug.cgi?id=81698
         ImageWithScale image = bestImageForScaleFactor();
-        CachedResourceRequest request(ResourceRequest(document->completeURL(image.imageURL)), cachedResourceRequestInitiators().css);
-        if (CachedResourceHandle<CachedImage> cachedImage = loader->requestImage(request)) {
-            m_imageSet = StyleCachedImageSet::create(cachedImage.get(), image.scaleFactor, this);
-            m_accessedBestFitImage = true;
+        if (Document* document = loader->document()) {
+            CachedResourceRequest request(ResourceRequest(document->completeURL(image.imageURL)), cachedResourceRequestInitiators().css);
+            if (CachedResourceHandle<CachedImage> cachedImage = loader->requestImage(request)) {
+                m_imageSet = StyleCachedImageSet::create(cachedImage.get(), image.scaleFactor, this);
+                m_accessedBestFitImage = true;
+            }
         }
     }
 
     return (m_imageSet && m_imageSet->isCachedImageSet()) ? static_cast<StyleCachedImageSet*>(m_imageSet.get()) : 0;
 }
 
-StyleImage* CSSImageSetValue::cachedOrPendingImageSet(Document* document)
+StyleImage* CSSImageSetValue::cachedOrPendingImageSet(float deviceScaleFactor)
 {
-    if (!m_imageSet)
+    if (!m_imageSet) {
         m_imageSet = StylePendingImage::create(this);
-    else if (document && !m_imageSet->isPendingImage()) {
-        float deviceScaleFactor = 1;
-        if (Page* page = document->page())
-            deviceScaleFactor = page->deviceScaleFactor();
-
+    } else if (!m_imageSet->isPendingImage()) {
         // If the deviceScaleFactor has changed, we may not have the best image loaded, so we have to re-assess.
         if (deviceScaleFactor != m_scaleFactor) {
             m_accessedBestFitImage = false;
diff --git a/Source/core/css/CSSImageSetValue.h b/Source/core/css/CSSImageSetValue.h
index 2f8b037..da81ad2 100644
--- a/Source/core/css/CSSImageSetValue.h
+++ b/Source/core/css/CSSImageSetValue.h
@@ -31,7 +31,6 @@
 namespace WebCore {
 
 class CachedResourceLoader;
-class Document;
 class StyleCachedImageSet;
 class StyleImage;
 
@@ -44,10 +43,10 @@
     }
     ~CSSImageSetValue();
 
-    StyleCachedImageSet* cachedImageSet(CachedResourceLoader*);
+    StyleCachedImageSet* cachedImageSet(CachedResourceLoader*, float deviceScaleFactor);
 
     // Returns a StyleCachedImageSet if the best fit image has been cached already, otherwise a StylePendingImage.
-    StyleImage* cachedOrPendingImageSet(Document*);
+    StyleImage* cachedOrPendingImageSet(float);
 
     String customCssText() const;
 
diff --git a/Source/core/css/CSSImageValue.cpp b/Source/core/css/CSSImageValue.cpp
index 9ee0508..2769433 100644
--- a/Source/core/css/CSSImageValue.cpp
+++ b/Source/core/css/CSSImageValue.cpp
@@ -60,14 +60,14 @@
     return m_image.get();
 }
 
-StyleCachedImage* CSSImageValue::cachedImage(CachedResourceLoader* loader)
+StyleCachedImage* CSSImageValue::cachedImage(CachedResourceLoader* loader, const ResourceLoaderOptions& options)
 {
     ASSERT(loader);
 
     if (!m_accessedImage) {
         m_accessedImage = true;
 
-        CachedResourceRequest request(ResourceRequest(loader->document()->completeURL(m_url)), m_initiatorName.isEmpty() ? cachedResourceRequestInitiators().css : m_initiatorName);
+        CachedResourceRequest request(ResourceRequest(loader->document()->completeURL(m_url)), m_initiatorName.isEmpty() ? cachedResourceRequestInitiators().css : m_initiatorName, options);
         if (CachedResourceHandle<CachedImage> cachedImage = loader->requestImage(request))
             m_image = StyleCachedImage::create(cachedImage.get());
     }
@@ -107,7 +107,7 @@
 {
     MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
     info.addMember(m_url, "url");
-    // No need to report m_image as it is counted as part of RenderArena.
+    // FIXME: report m_image. It has never been allocated from any of our rendering custom heaps.
 }
 
 bool CSSImageValue::knownToBeOpaque(const RenderObject* renderer) const
diff --git a/Source/core/css/CSSImageValue.h b/Source/core/css/CSSImageValue.h
index 7b5522c..49e9818 100644
--- a/Source/core/css/CSSImageValue.h
+++ b/Source/core/css/CSSImageValue.h
@@ -22,11 +22,11 @@
 #define CSSImageValue_h
 
 #include "core/css/CSSValue.h"
+#include "core/loader/cache/CachedResourceLoader.h"
 #include <wtf/RefPtr.h>
 
 namespace WebCore {
 
-class CachedResourceLoader;
 class Element;
 class StyleCachedImage;
 class StyleImage;
@@ -38,7 +38,8 @@
     static PassRefPtr<CSSImageValue> create(const String& url, StyleImage* image) { return adoptRef(new CSSImageValue(url, image)); }
     ~CSSImageValue();
 
-    StyleCachedImage* cachedImage(CachedResourceLoader*);
+    StyleCachedImage* cachedImage(CachedResourceLoader*, const ResourceLoaderOptions&);
+    StyleCachedImage* cachedImage(CachedResourceLoader* loader) { return cachedImage(loader, CachedResourceLoader::defaultCachedResourceOptions()); }
     // Returns a StyleCachedImage if the image is cached already, otherwise a StylePendingImage.
     StyleImage* cachedOrPendingImage();
 
diff --git a/Source/core/css/CSSLineBoxContainValue.h b/Source/core/css/CSSLineBoxContainValue.h
index 79e36d5..5b68ba5 100644
--- a/Source/core/css/CSSLineBoxContainValue.h
+++ b/Source/core/css/CSSLineBoxContainValue.h
@@ -27,8 +27,7 @@
 #define CSSLineBoxContainValue_h
 
 #include "core/css/CSSValue.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSMatrix.h b/Source/core/css/CSSMatrix.h
index a353304..dea37ac 100644
--- a/Source/core/css/CSSMatrix.h
+++ b/Source/core/css/CSSMatrix.h
@@ -29,7 +29,6 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/platform/graphics/transforms/TransformationMatrix.h"
 #include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
diff --git a/Source/core/css/CSSMediaRule.cpp b/Source/core/css/CSSMediaRule.cpp
index c9b3548..b8f4ebb 100644
--- a/Source/core/css/CSSMediaRule.cpp
+++ b/Source/core/css/CSSMediaRule.cpp
@@ -25,8 +25,7 @@
 
 #include "core/css/StyleRule.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/MemoryInstrumentationVector.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSOMUtils.h b/Source/core/css/CSSOMUtils.h
index 878669c..3239ada 100644
--- a/Source/core/css/CSSOMUtils.h
+++ b/Source/core/css/CSSOMUtils.h
@@ -31,9 +31,8 @@
 #ifndef CSSOMUtils_h
 #define CSSOMUtils_h
 
-#include <wtf/Forward.h>
-#include <wtf/Vector.h>
-#include <wtf/unicode/Unicode.h>
+#include "wtf/Forward.h"
+#include "wtf/unicode/Unicode.h"
 
 // Utilities for CSSOM http://dev.w3.org/csswg/cssom/
 
diff --git a/Source/core/css/CSSPageRule.cpp b/Source/core/css/CSSPageRule.cpp
index c13ba3a..d29dddb 100644
--- a/Source/core/css/CSSPageRule.cpp
+++ b/Source/core/css/CSSPageRule.cpp
@@ -28,8 +28,7 @@
 #include "core/css/PropertySetCSSStyleDeclaration.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleRule.h"
-#include <wtf/text/StringBuilder.h>
-#include <wtf/Vector.h>
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSParser.cpp b/Source/core/css/CSSParser.cpp
index 3ef33b0..63f4985 100644
--- a/Source/core/css/CSSParser.cpp
+++ b/Source/core/css/CSSParser.cpp
@@ -79,7 +79,6 @@
 #include "core/page/Settings.h"
 #include "core/platform/FloatConversion.h"
 #include "core/platform/HashTools.h"
-#include "core/platform/HistogramSupport.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/svg/SVGParserUtilities.h"
 #include "wtf/BitArray.h"
@@ -340,7 +339,8 @@
     for (unsigned i = 0; i < m_parsedTextPrefixLength; i++)
         m_dataStart16[i] = prefix[i];
 
-    memcpy(m_dataStart16.get() + m_parsedTextPrefixLength, string.characters(), stringLength * sizeof(UChar));
+    ASSERT(stringLength);
+    memcpy(m_dataStart16.get() + m_parsedTextPrefixLength, string.characters16(), stringLength * sizeof(UChar));
 
     unsigned start = m_parsedTextPrefixLength + stringLength;
     unsigned end = start + suffixLength;
@@ -379,7 +379,7 @@
 {
     setStyleSheet(sheet);
     m_allowNamespaceDeclarations = false;
-    setupParser("@-internal-rule{", string, "} ");
+    setupParser("@-internal-rule ", string, "");
     cssyyparse(this);
     return m_rule.release();
 }
@@ -387,7 +387,7 @@
 PassRefPtr<StyleKeyframe> CSSParser::parseKeyframeRule(StyleSheetContents* sheet, const String& string)
 {
     setStyleSheet(sheet);
-    setupParser("@-webkit-keyframe-rule{ ", string, "} ");
+    setupParser("@-internal-keyframe-rule ", string, "");
     cssyyparse(this);
     return m_keyframe.release();
 }
@@ -395,7 +395,7 @@
 bool CSSParser::parseSupportsCondition(const String& string)
 {
     m_supportsCondition = false;
-    setupParser("@-webkit-supports-condition{ ", string, "} ");
+    setupParser("@-internal-supports-condition ", string, "");
     cssyyparse(this);
     return m_supportsCondition;
 }
@@ -762,27 +762,27 @@
         if (valueID == CSSValueStart || valueID == CSSValueEnd || valueID == CSSValueCenter || valueID == CSSValueJustify)
             return true;
         break;
-    case CSSPropertyWebkitAlignContent:
+    case CSSPropertyAlignContent:
          if (valueID == CSSValueFlexStart || valueID == CSSValueFlexEnd || valueID == CSSValueCenter || valueID == CSSValueSpaceBetween || valueID == CSSValueSpaceAround || valueID == CSSValueStretch)
              return true;
          break;
-    case CSSPropertyWebkitAlignItems:
+    case CSSPropertyAlignItems:
         if (valueID == CSSValueFlexStart || valueID == CSSValueFlexEnd || valueID == CSSValueCenter || valueID == CSSValueBaseline || valueID == CSSValueStretch)
             return true;
         break;
-    case CSSPropertyWebkitAlignSelf:
+    case CSSPropertyAlignSelf:
         if (valueID == CSSValueAuto || valueID == CSSValueFlexStart || valueID == CSSValueFlexEnd || valueID == CSSValueCenter || valueID == CSSValueBaseline || valueID == CSSValueStretch)
             return true;
         break;
-    case CSSPropertyWebkitFlexDirection:
+    case CSSPropertyFlexDirection:
         if (valueID == CSSValueRow || valueID == CSSValueRowReverse || valueID == CSSValueColumn || valueID == CSSValueColumnReverse)
             return true;
         break;
-    case CSSPropertyWebkitFlexWrap:
+    case CSSPropertyFlexWrap:
         if (valueID == CSSValueNowrap || valueID == CSSValueWrap || valueID == CSSValueWrapReverse)
              return true;
         break;
-    case CSSPropertyWebkitJustifyContent:
+    case CSSPropertyJustifyContent:
         if (valueID == CSSValueFlexStart || valueID == CSSValueFlexEnd || valueID == CSSValueCenter || valueID == CSSValueSpaceBetween || valueID == CSSValueSpaceAround)
             return true;
         break;
@@ -985,12 +985,12 @@
     case CSSPropertyWebkitColumnBreakBefore:
     case CSSPropertyWebkitColumnBreakInside:
     case CSSPropertyWebkitColumnRuleStyle:
-    case CSSPropertyWebkitAlignContent:
-    case CSSPropertyWebkitAlignItems:
-    case CSSPropertyWebkitAlignSelf:
-    case CSSPropertyWebkitFlexDirection:
-    case CSSPropertyWebkitFlexWrap:
-    case CSSPropertyWebkitJustifyContent:
+    case CSSPropertyAlignContent:
+    case CSSPropertyAlignItems:
+    case CSSPropertyAlignSelf:
+    case CSSPropertyFlexDirection:
+    case CSSPropertyFlexWrap:
+    case CSSPropertyJustifyContent:
     case CSSPropertyWebkitFontKerning:
     case CSSPropertyWebkitFontSmoothing:
     case CSSPropertyWebkitHyphens:
@@ -1196,7 +1196,7 @@
 
     setStyleSheet(contextStyleSheet);
 
-    setupParser("@-internal-value{", string, "} ");
+    setupParser("@-internal-value ", string, "");
 
     m_id = propertyID;
     m_important = important;
@@ -1246,7 +1246,7 @@
 
 bool CSSParser::parseColor(const String& string)
 {
-    setupParser("@-internal-decls{color:", string, "} ");
+    setupParser("@-internal-decls color:", string, "");
     cssyyparse(this);
     m_rule = 0;
 
@@ -1272,7 +1272,7 @@
 {
     m_selectorListForParseSelector = &selectorList;
 
-    setupParser("@-internal-selector{", string, "}");
+    setupParser("@-internal-selector ", string, "");
 
     cssyyparse(this);
 
@@ -1291,7 +1291,7 @@
 {
     setStyleSheet(contextStyleSheet);
 
-    setupParser("@-internal-decls{", string, "} ");
+    setupParser("@-internal-decls ", string, "");
     cssyyparse(this);
     m_rule = 0;
 
@@ -1310,7 +1310,7 @@
 
     m_sourceDataHandler = sourceDataHandler;
 
-    setupParser("@-internal-decls{", string, "} ");
+    setupParser("@-internal-decls ", string, "");
     if (m_sourceDataHandler) {
         m_sourceDataHandler->startRuleHeader(CSSRuleSourceData::STYLE_RULE, 0);
         m_sourceDataHandler->endRuleHeader(1);
@@ -2287,28 +2287,28 @@
 
         validPrimitive = true;
         break;
-    case CSSPropertyWebkitFlex: {
+    case CSSPropertyFlex: {
         ShorthandScope scope(this, propId);
         if (id == CSSValueNone) {
-            addProperty(CSSPropertyWebkitFlexGrow, cssValuePool().createValue(0, CSSPrimitiveValue::CSS_NUMBER), important);
-            addProperty(CSSPropertyWebkitFlexShrink, cssValuePool().createValue(0, CSSPrimitiveValue::CSS_NUMBER), important);
-            addProperty(CSSPropertyWebkitFlexBasis, cssValuePool().createIdentifierValue(CSSValueAuto), important);
+            addProperty(CSSPropertyFlexGrow, cssValuePool().createValue(0, CSSPrimitiveValue::CSS_NUMBER), important);
+            addProperty(CSSPropertyFlexShrink, cssValuePool().createValue(0, CSSPrimitiveValue::CSS_NUMBER), important);
+            addProperty(CSSPropertyFlexBasis, cssValuePool().createIdentifierValue(CSSValueAuto), important);
             return true;
         }
         return parseFlex(m_valueList.get(), important);
     }
-    case CSSPropertyWebkitFlexBasis:
+    case CSSPropertyFlexBasis:
         // FIXME: Support intrinsic dimensions too.
         if (id == CSSValueAuto)
             validPrimitive = true;
         else
             validPrimitive = (!id && validUnit(value, FLength | FPercent | FNonNeg));
         break;
-    case CSSPropertyWebkitFlexGrow:
-    case CSSPropertyWebkitFlexShrink:
+    case CSSPropertyFlexGrow:
+    case CSSPropertyFlexShrink:
         validPrimitive = validUnit(value, FNumber | FNonNeg);
         break;
-    case CSSPropertyWebkitOrder:
+    case CSSPropertyOrder:
         if (validUnit(value, FInteger, CSSStrictMode)) {
             // We restrict the smallest value to int min + 2 because we use int min and int min + 1 as special values in a hash set.
             parsedValue = cssValuePool().createValue(max(static_cast<double>(std::numeric_limits<int>::min() + 2), value->fValue),
@@ -2432,19 +2432,19 @@
     case CSSPropertyGridAutoRows:
         if (!RuntimeEnabledFeatures::cssGridLayoutEnabled())
             return false;
-        parsedValue = parseGridTrackSize();
+        parsedValue = parseGridTrackSize(*m_valueList);
         break;
 
-    case CSSPropertyGridColumns:
-    case CSSPropertyGridRows:
+    case CSSPropertyGridDefinitionColumns:
+    case CSSPropertyGridDefinitionRows:
         if (!RuntimeEnabledFeatures::cssGridLayoutEnabled())
             return false;
         return parseGridTrackList(propId, important);
 
-    case CSSPropertyGridStart:
-    case CSSPropertyGridEnd:
-    case CSSPropertyGridBefore:
-    case CSSPropertyGridAfter:
+    case CSSPropertyGridColumnEnd:
+    case CSSPropertyGridColumnStart:
+    case CSSPropertyGridRowEnd:
+    case CSSPropertyGridRowStart:
         if (!RuntimeEnabledFeatures::cssGridLayoutEnabled())
             return false;
         parsedValue = parseGridPosition();
@@ -2647,8 +2647,8 @@
     case CSSPropertyPadding:
         // <padding-width>{1,4} | inherit
         return parse4Values(propId, paddingShorthand().properties(), important);
-    case CSSPropertyWebkitFlexFlow:
-        return parseShorthand(propId, webkitFlexFlowShorthand(), important);
+    case CSSPropertyFlexFlow:
+        return parseShorthand(propId, flexFlowShorthand(), important);
     case CSSPropertyFont:
         // [ [ 'font-style' || 'font-variant' || 'font-weight' ]? 'font-size' [ / 'line-height' ]?
         // 'font-family' ] | caption | icon | menu | message-box | small-caption | status-bar | inherit
@@ -2795,12 +2795,12 @@
     case CSSPropertyWebkitColumnBreakBefore:
     case CSSPropertyWebkitColumnBreakInside:
     case CSSPropertyWebkitColumnRuleStyle:
-    case CSSPropertyWebkitAlignContent:
-    case CSSPropertyWebkitAlignItems:
-    case CSSPropertyWebkitAlignSelf:
-    case CSSPropertyWebkitFlexDirection:
-    case CSSPropertyWebkitFlexWrap:
-    case CSSPropertyWebkitJustifyContent:
+    case CSSPropertyAlignContent:
+    case CSSPropertyAlignItems:
+    case CSSPropertyAlignSelf:
+    case CSSPropertyFlexDirection:
+    case CSSPropertyFlexWrap:
+    case CSSPropertyJustifyContent:
     case CSSPropertyWebkitFontKerning:
     case CSSPropertyWebkitFontSmoothing:
     case CSSPropertyWebkitHyphens:
@@ -3049,7 +3049,7 @@
     if (!value)
         return;
 
-    static const unsigned prefixLength = sizeof("-webkit-var-") - 1;
+    static const unsigned prefixLength = sizeof("var-") - 1;
 
     ASSERT(name.length() > prefixLength);
     AtomicString variableName = name.atomicSubstring(prefixLength, name.length() - prefixLength);
@@ -4595,34 +4595,93 @@
     }
 
     RefPtr<CSSValueList> values = CSSValueList::createSpaceSeparated();
-    size_t currentLineNumber = 0;
-    while (m_valueList->current()) {
+    // Handle leading <string>*.
+    while (m_valueList->current() && m_valueList->current()->unit == CSSPrimitiveValue::CSS_STRING) {
+        RefPtr<CSSPrimitiveValue> name = createPrimitiveStringValue(m_valueList->current());
+        values->append(name);
+        m_valueList->next();
+    }
+
+    bool seenTrackSizeOrRepeatFunction = false;
+    while (CSSParserValue* currentValue = m_valueList->current()) {
+        if (currentValue->unit == CSSParserValue::Function && equalIgnoringCase(currentValue->function->name, "repeat(")) {
+            if (!parseGridTrackRepeatFunction(*values))
+                return false;
+            seenTrackSizeOrRepeatFunction = true;
+        } else {
+            RefPtr<CSSPrimitiveValue> primitiveValue = parseGridTrackSize(*m_valueList);
+            if (!primitiveValue)
+                return false;
+            values->append(primitiveValue);
+            seenTrackSizeOrRepeatFunction = true;
+        }
+
+        // This will handle the trailing <string>* in the grammar.
         while (m_valueList->current() && m_valueList->current()->unit == CSSPrimitiveValue::CSS_STRING) {
             RefPtr<CSSPrimitiveValue> name = createPrimitiveStringValue(m_valueList->current());
             values->append(name);
             m_valueList->next();
         }
-
-        // This allows trailing <string>* per the specification.
-        if (!m_valueList->current())
-            break;
-
-        RefPtr<CSSPrimitiveValue> primitiveValue = parseGridTrackSize();
-        if (!primitiveValue)
-            return false;
-
-        values->append(primitiveValue.release());
     }
+
+    // We should have found a <track-size> or else it is not a valid <track-list>
+    if (!seenTrackSizeOrRepeatFunction)
+        return false;
+
     addProperty(propId, values.release(), important);
     return true;
 }
 
-PassRefPtr<CSSPrimitiveValue> CSSParser::parseGridTrackSize()
+bool CSSParser::parseGridTrackRepeatFunction(CSSValueList& list)
+{
+    CSSParserValueList* arguments = m_valueList->current()->function->args.get();
+    if (!arguments || arguments->size() < 3 || !validUnit(arguments->valueAt(0), FPositiveInteger) || !isComma(arguments->valueAt(1)))
+        return false;
+
+    ASSERT_WITH_SECURITY_IMPLICATION(arguments->valueAt(0)->fValue > 0);
+    size_t repetitions = arguments->valueAt(0)->fValue;
+    RefPtr<CSSValueList> repeatedValues = CSSValueList::createSpaceSeparated();
+    arguments->next(); // Skip the repetition count.
+    arguments->next(); // Skip the comma.
+
+    // Handle leading <string>*.
+    while (arguments->current() && arguments->current()->unit == CSSPrimitiveValue::CSS_STRING) {
+        RefPtr<CSSPrimitiveValue> name = createPrimitiveStringValue(arguments->current());
+        repeatedValues->append(name);
+        arguments->next();
+    }
+
+    while (CSSParserValue* argumentValue = arguments->current()) {
+        RefPtr<CSSPrimitiveValue> trackSize = parseGridTrackSize(*arguments);
+        if (!trackSize)
+            return false;
+
+        repeatedValues->append(trackSize);
+
+        // This takes care of any trailing <string>* in the grammar.
+        while (arguments->current() && arguments->current()->unit == CSSPrimitiveValue::CSS_STRING) {
+            RefPtr<CSSPrimitiveValue> name = createPrimitiveStringValue(arguments->current());
+            repeatedValues->append(name);
+            arguments->next();
+        }
+    }
+
+    for (size_t i = 0; i < repetitions; ++i) {
+        for (size_t j = 0; j < repeatedValues->length(); ++j)
+            list.append(repeatedValues->itemWithoutBoundsCheck(j));
+    }
+
+    // parseGridTrackSize iterated over the repeat arguments, move to the next value.
+    m_valueList->next();
+    return true;
+}
+
+PassRefPtr<CSSPrimitiveValue> CSSParser::parseGridTrackSize(CSSParserValueList& inputList)
 {
     ASSERT(RuntimeEnabledFeatures::cssGridLayoutEnabled());
 
-    CSSParserValue* currentValue = m_valueList->current();
-    m_valueList->next();
+    CSSParserValue* currentValue = inputList.current();
+    inputList.next();
 
     if (currentValue->id == CSSValueAuto)
         return cssValuePool().createIdentifierValue(CSSValueAuto);
@@ -4644,15 +4703,12 @@
         return createPrimitiveValuePair(minTrackBreadth, maxTrackBreadth);
     }
 
-    if (PassRefPtr<CSSPrimitiveValue> trackBreadth = parseGridBreadth(currentValue))
-        return trackBreadth;
-
-    return 0;
+    return parseGridBreadth(currentValue);
 }
 
 PassRefPtr<CSSPrimitiveValue> CSSParser::parseGridBreadth(CSSParserValue* currentValue)
 {
-    if (currentValue->id == CSSValueWebkitMinContent || currentValue->id == CSSValueWebkitMaxContent)
+    if (currentValue->id == CSSValueMinContent || currentValue->id == CSSValueMaxContent)
         return cssValuePool().createIdentifierValue(currentValue->id);
 
     if (currentValue->unit == CSSPrimitiveValue::CSS_FR) {
@@ -6276,9 +6332,9 @@
     if (!flexBasis)
         flexBasis = cssValuePool().createValue(0, CSSPrimitiveValue::CSS_PX);
 
-    addProperty(CSSPropertyWebkitFlexGrow, cssValuePool().createValue(clampToFloat(flexGrow), CSSPrimitiveValue::CSS_NUMBER), important);
-    addProperty(CSSPropertyWebkitFlexShrink, cssValuePool().createValue(clampToFloat(flexShrink), CSSPrimitiveValue::CSS_NUMBER), important);
-    addProperty(CSSPropertyWebkitFlexBasis, flexBasis, important);
+    addProperty(CSSPropertyFlexGrow, cssValuePool().createValue(clampToFloat(flexGrow), CSSPrimitiveValue::CSS_NUMBER), important);
+    addProperty(CSSPropertyFlexShrink, cssValuePool().createValue(clampToFloat(flexShrink), CSSPrimitiveValue::CSS_NUMBER), important);
+    addProperty(CSSPropertyFlexBasis, flexBasis, important);
     return true;
 }
 
@@ -7708,7 +7764,7 @@
             const LChar* start = string.characters8();
             parseDouble(start, start + length, 'x', imageScaleFactor);
         } else {
-            const UChar* start = string.characters();
+            const UChar* start = string.characters16();
             parseDouble(start, start + length, 'x', imageScaleFactor);
         }
         if (imageScaleFactor <= 0)
@@ -8686,7 +8742,7 @@
 
 bool CSSParser::parseFlowThread(const String& flowName)
 {
-    setupParser("@-internal-decls{-webkit-flow-into:", flowName, "}");
+    setupParser("@-internal-decls -webkit-flow-into:", flowName, "");
     cssyyparse(this);
 
     m_rule = 0;
@@ -9871,6 +9927,10 @@
             m_token = CUEFUNCTION;
             return true;
         }
+        if (RuntimeEnabledFeatures::cssVariablesEnabled() && isASCIIAlphaCaselessEqual(name[0], 'v') && isASCIIAlphaCaselessEqual(name[1], 'a') && isASCIIAlphaCaselessEqual(name[2], 'r')) {
+            m_token = VARFUNCTION;
+            return true;
+        }
         return false;
 
     case 4:
@@ -10067,8 +10127,6 @@
             m_token = MINFUNCTION;
         else if (isASCIIAlphaCaselessEqual(name[10], 'x') && isEqualToCSSIdentifier(name + 1, "webkit-ma"))
             m_token = MAXFUNCTION;
-        else if (RuntimeEnabledFeatures::cssVariablesEnabled() && isASCIIAlphaCaselessEqual(name[10], 'r') && isEqualToCSSIdentifier(name + 1, "webkit-va"))
-            m_token = VARFUNCTION;
     } else if (length == 12 && isEqualToCSSIdentifier(name + 1, "webkit-calc"))
         m_token = CALCFUNCTION;
     else if (length == 19 && isEqualToCSSIdentifier(name + 1, "webkit-distributed"))
@@ -10281,15 +10339,15 @@
             }
             return;
 
-        case 22:
-            if (!hasEscape && isEqualToCSSIdentifier(name + 2, "webkit-keyframe-rule"))
-                m_token = WEBKIT_KEYFRAME_RULE_SYM;
+        case 24:
+            if (!hasEscape && isEqualToCSSIdentifier(name + 2, "internal-keyframe-rule"))
+                m_token = INTERNAL_KEYFRAME_RULE_SYM;
             return;
 
-        case 27:
-            if (isEqualToCSSIdentifier(name + 2, "webkit-supports-condition")) {
+        case 29:
+            if (isEqualToCSSIdentifier(name + 2, "internal-supports-condition")) {
                 m_parsingMode = SupportsMode;
-                m_token = WEBKIT_SUPPORTS_CONDITION_SYM;
+                m_token = INTERNAL_SUPPORTS_CONDITION_SYM;
             }
             return;
         }
@@ -10314,16 +10372,17 @@
 }
 
 template <typename CharacterType>
-inline bool CSSParser::detectCSSVariablesToken(int length)
+inline void CSSParser::detectCSSVariableDefinitionToken(int length)
 {
-    ASSERT(tokenStart<CharacterType>()[0] == '-');
-    if (length < sizeof("-webkit-var-*") - 1)
-        return false;
+    static const unsigned prefixLength = sizeof("var-") - 1;
+    if (length <= prefixLength)
+        return;
     CharacterType* name = tokenStart<CharacterType>();
-    return name[11] == '-' && isIdentifierStartAfterDash(name + 12) && isEqualToCSSCaseSensitiveIdentifier(name + 1, "webkit-var");
+    COMPILE_ASSERT(prefixLength > 0, CSS_variable_prefix_must_be_nonempty);
+    if (name[prefixLength - 1] == '-' && isIdentifierStartAfterDash(name + prefixLength) && isEqualToCSSCaseSensitiveIdentifier(name, "var"))
+        m_token = VAR_DEFINITION;
 }
 
-
 template <typename SrcCharacterType>
 int CSSParser::realLex(void* yylvalWithoutType)
 {
@@ -10412,6 +10471,8 @@
                     }
                 }
             }
+        } else if (UNLIKELY(RuntimeEnabledFeatures::cssVariablesEnabled())) {
+            detectCSSVariableDefinitionToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
         }
         break;
 
@@ -10498,9 +10559,7 @@
             parseIdentifier(result, resultString, hasEscape);
             m_token = IDENT;
 
-            if (RuntimeEnabledFeatures::cssVariablesEnabled() && detectCSSVariablesToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>()))
-                m_token = VAR_DEFINITION;
-            else if (*currentCharacter<SrcCharacterType>() == '(') {
+            if (*currentCharacter<SrcCharacterType>() == '(') {
                 m_token = FUNCTION;
                 if (!hasEscape)
                     detectDashToken<SrcCharacterType>(result - tokenStart<SrcCharacterType>());
@@ -10622,6 +10681,7 @@
     case CharacterSlash:
         // Ignore comments. They are not even considered as white spaces.
         if (*currentCharacter<SrcCharacterType>() == '*') {
+            const CSSParserLocation startLocation = currentLocation();
             if (m_sourceDataHandler) {
                 unsigned startOffset = (is8BitSource() ? currentCharacter<LChar>() - m_dataStart8.get() : currentCharacter<UChar>() - m_dataStart16.get()) - 1; // Start with a slash.
                 m_sourceDataHandler->startComment(startOffset - m_parsedTextPrefixLength);
@@ -10633,6 +10693,7 @@
                 if (*currentCharacter<SrcCharacterType>() == '\0') {
                     // Unterminated comments are simply ignored.
                     currentCharacter<SrcCharacterType>() -= 2;
+                    reportError(startLocation, UnterminatedCommentError);
                     break;
                 }
                 ++currentCharacter<SrcCharacterType>();
@@ -11029,7 +11090,7 @@
 
     m_ignoreErrors = true;
     CSSParserString content = location.token;
-    if (error == InvalidPropertyValueError || error == InvalidSelectorError) {
+    if (error == InvalidPropertyValueError || error == InvalidSelectorError || error == InvalidMediaQueryError || error == InvalidKeyframeSelectorError) {
         if (m_source) {
             if (is8BitSource())
                 content.init(*m_source, location.token.characters8() - m_dataStart8.get(), tokenStart<LChar>() - location.token.characters8());
@@ -11068,14 +11129,28 @@
         builder.appendLiteral("Invalid CSS rule at: ");
         break;
 
+    case InvalidMediaQueryError:
+        builder.appendLiteral("Invalid CSS media query: ");
+        break;
+
+    case InvalidSelectorPseudoError:
+        builder.appendLiteral("Invalid CSS selector pseudoclass: ");
+        break;
+
+    case InvalidKeyframeSelectorError:
+        builder.appendLiteral("Invalid CSS keyframe selector: ");
+        break;
+
+    case UnterminatedCommentError:
+        content.setLength(0);
+        builder.appendLiteral("Unterminated CSS comment");
+        break;
+
     default:
         builder.appendLiteral("Unexpected CSS token: ");
     }
 
-    if (content.is8Bit())
-        builder.append(content.characters8(), content.length());
-    else
-        builder.append(content.characters16(), content.length());
+    builder.append(content);
 
     logError(builder.toString(), location.lineNumber);
 }
@@ -11398,11 +11473,6 @@
     m_lastSelectorLineNumber = m_lineNumber;
 }
 
-void CSSParser::updateLastMediaLine(MediaQuerySet* media)
-{
-    media->setLastLine(m_lineNumber);
-}
-
 void CSSParser::startRuleHeader(CSSRuleSourceData::Type ruleType)
 {
     resumeErrorLogging();
@@ -11596,7 +11666,7 @@
     if (length > maxCSSPropertyNameLength)
         return CSSPropertyInvalid;
 
-    return string.is8Bit() ? cssPropertyID(string.characters8(), length) : cssPropertyID(string.characters(), length);
+    return string.is8Bit() ? cssPropertyID(string.characters8(), length) : cssPropertyID(string.characters16(), length);
 }
 
 CSSPropertyID cssPropertyID(const CSSParserString& string)
@@ -11682,7 +11752,7 @@
 
     if (string.is8Bit())
         return isCSSTokenizerIdentifier(string.characters8(), length);
-    return isCSSTokenizerIdentifier(string.characters(), length);
+    return isCSSTokenizerIdentifier(string.characters16(), length);
 }
 
 template <typename CharacterType>
@@ -11722,7 +11792,7 @@
 
     if (string.is8Bit())
         return isCSSTokenizerURL(string.characters8(), length);
-    return isCSSTokenizerURL(string.characters(), length);
+    return isCSSTokenizerURL(string.characters16(), length);
 }
 
 
diff --git a/Source/core/css/CSSParser.h b/Source/core/css/CSSParser.h
index 5631695..d1ecd6b 100644
--- a/Source/core/css/CSSParser.h
+++ b/Source/core/css/CSSParser.h
@@ -36,7 +36,6 @@
 #include "core/css/MediaQuery.h"
 #include "core/page/UseCounter.h"
 #include "core/platform/graphics/Color.h"
-#include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
 #include "wtf/OwnArrayPtr.h"
 #include "wtf/Vector.h"
@@ -66,9 +65,11 @@
 class StyleRuleKeyframes;
 class StyleKeyframe;
 class StyleSheetContents;
-class StyledElement;
 
-struct CSSParserLocation;
+struct CSSParserLocation {
+    int lineNumber;
+    CSSParserString token;
+};
 
 class CSSParser {
     friend inline int cssyylex(void*, CSSParser*);
@@ -83,6 +84,10 @@
         InvalidSelectorError,
         InvalidSupportsConditionError,
         InvalidRuleError,
+        InvalidMediaQueryError,
+        InvalidKeyframeSelectorError,
+        InvalidSelectorPseudoError,
+        UnterminatedCommentError,
         GeneralError
     };
 
@@ -166,7 +171,8 @@
     bool parseIntegerOrStringFromGridPosition(RefPtr<CSSPrimitiveValue>& numericValue, RefPtr<CSSPrimitiveValue>& gridLineName);
     bool parseGridItemPositionShorthand(CSSPropertyID, bool important);
     bool parseGridTrackList(CSSPropertyID, bool important);
-    PassRefPtr<CSSPrimitiveValue> parseGridTrackSize();
+    bool parseGridTrackRepeatFunction(CSSValueList&);
+    PassRefPtr<CSSPrimitiveValue> parseGridTrackSize(CSSParserValueList& inputList);
     PassRefPtr<CSSPrimitiveValue> parseGridBreadth(CSSParserValue*);
 
     bool parseClipShape(CSSPropertyID, bool important);
@@ -343,7 +349,6 @@
     Vector<OwnPtr<CSSParserSelector> >* reusableRegionSelectorVector() { return &m_reusableRegionSelectorVector; }
 
     void updateLastSelectorLineAndPosition();
-    void updateLastMediaLine(MediaQuerySet*);
 
     void clearProperties();
 
@@ -397,6 +402,8 @@
     void endInvalidRuleHeader();
     void reportError(const CSSParserLocation&, ErrorType = GeneralError);
     void resumeErrorLogging() { m_ignoreErrors = false; }
+    void setLocationLabel(const CSSParserLocation& location) { m_locationLabel = location; }
+    const CSSParserLocation& lastLocationLabel() const { return m_locationLabel; }
 
     inline int lex(void* yylval) { return (this->*m_lexFunc)(yylval); }
 
@@ -508,7 +515,7 @@
     template <typename CharacterType>
     inline void detectSupportsToken(int);
     template <typename CharacterType>
-    inline bool detectCSSVariablesToken(int);
+    inline void detectCSSVariableDefinitionToken(int);
 
     void setStyleSheet(StyleSheetContents* styleSheet) { m_styleSheet = styleSheet; }
 
@@ -590,6 +597,8 @@
     bool inViewport() const { return m_inViewport; }
     bool m_inViewport;
 
+    CSSParserLocation m_locationLabel;
+
     int (CSSParser::*m_lexFunc)(void*);
 
     Vector<RefPtr<StyleRuleBase> > m_parsedRules;
@@ -685,11 +694,6 @@
     CSSParser* m_parser;
 };
 
-struct CSSParserLocation {
-    int lineNumber;
-    CSSParserString token;
-};
-
 class CSSParser::SourceDataHandler {
 public:
     virtual void startRuleHeader(CSSRuleSourceData::Type, unsigned offset) = 0;
diff --git a/Source/core/css/CSSParserValues.h b/Source/core/css/CSSParserValues.h
index 79888d6..b136975 100644
--- a/Source/core/css/CSSParserValues.h
+++ b/Source/core/css/CSSParserValues.h
@@ -56,11 +56,11 @@
     void init(const String& string, unsigned startOffset, unsigned length)
     {
         m_length = length;
-        if (m_length && string.is8Bit()) {
+        if (!m_length || string.is8Bit()) {
             m_data.characters8 = const_cast<LChar*>(string.characters8()) + startOffset;
             m_is8Bit = true;
         } else {
-            m_data.characters16 = const_cast<UChar*>(string.characters()) + startOffset;
+            m_data.characters16 = const_cast<UChar*>(string.characters16()) + startOffset;
             m_is8Bit = false;
         }
     }
@@ -69,7 +69,7 @@
     {
         m_data.characters8 = 0;
         m_length = 0;
-        m_is8Bit = false;
+        m_is8Bit = true;
     }
 
     void trimTrailingWhitespace();
@@ -111,7 +111,7 @@
         return is8Bit() ? WTF::equalIgnoringCase(str, characters8(), strLength) : WTF::equalIgnoringCase(str, characters16(), strLength);
     }
 
-    operator String() const { return is8Bit() ? String(m_data.characters8, m_length) : String(m_data.characters16, m_length); }
+    operator String() const { return is8Bit() ? String(m_data.characters8, m_length) : StringImpl::create8BitIfPossible(m_data.characters16, m_length); }
     operator AtomicString() const { return is8Bit() ? AtomicString(m_data.characters8, m_length) : AtomicString(m_data.characters16, m_length); }
 
     AtomicString atomicSubstring(unsigned position, unsigned length) const;
diff --git a/Source/core/css/CSSPrimitiveValue.cpp b/Source/core/css/CSSPrimitiveValue.cpp
index 92f8ada..f1345e1 100644
--- a/Source/core/css/CSSPrimitiveValue.cpp
+++ b/Source/core/css/CSSPrimitiveValue.cpp
@@ -38,11 +38,10 @@
 #include "core/platform/LayoutUnit.h"
 #include "core/platform/graphics/Color.h"
 #include "core/rendering/style/RenderStyle.h"
-#include <wtf/ASCIICType.h>
-#include <wtf/DecimalNumber.h>
-#include <wtf/StdLibExtras.h>
-#include <wtf/text/StringBuffer.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/DecimalNumber.h"
+#include "wtf/StdLibExtras.h"
+#include "wtf/text/StringBuffer.h"
+#include "wtf/text/StringBuilder.h"
 
 using namespace WTF;
 
@@ -157,6 +156,20 @@
     }
 }
 
+bool CSSPrimitiveValue::colorIsDerivedFromElement() const
+{
+    int valueID = getValueID();
+    switch (valueID) {
+    case CSSValueWebkitText:
+    case CSSValueWebkitLink:
+    case CSSValueWebkitActivelink:
+    case CSSValueCurrentcolor:
+        return true;
+    default:
+        return false;
+    }
+}
+
 typedef HashMap<const CSSPrimitiveValue*, String> CSSTextCache;
 static CSSTextCache& cssTextCache()
 {
@@ -284,11 +297,11 @@
             break;
         case MinContent:
             m_primitiveUnitType = CSS_VALUE_ID;
-            m_value.valueID = CSSValueWebkitMinContent;
+            m_value.valueID = CSSValueMinContent;
             break;
         case MaxContent:
             m_primitiveUnitType = CSS_VALUE_ID;
-            m_value.valueID = CSSValueWebkitMaxContent;
+            m_value.valueID = CSSValueMaxContent;
             break;
         case FillAvailable:
             m_primitiveUnitType = CSS_VALUE_ID;
@@ -860,7 +873,7 @@
     return formatNumber(number, characters, characterCount - 1);
 }
 
-String CSSPrimitiveValue::customCssText() const
+String CSSPrimitiveValue::customCssText(CssTextFormattingFlags formattingFlag) const
 {
     // FIXME: return the original value instead of a generated one (e.g. color
     // name if it was specified) - check what spec says about this
@@ -949,7 +962,7 @@
             text = m_value.string;
             break;
         case CSS_STRING:
-            text = quoteCSSStringIfNeeded(m_value.string);
+            text = formattingFlag == AlwaysQuoteCSSString ? quoteCSSString(m_value.string) : quoteCSSStringIfNeeded(m_value.string);
             break;
         case CSS_URI:
             text = "url(" + quoteCSSURLIfNeeded(m_value.string) + ")";
@@ -1066,7 +1079,7 @@
             text = formatNumber(m_value.num, "vmax");
             break;
         case CSS_VARIABLE_NAME:
-            text = "-webkit-var(" + String(m_value.string) + ")";
+            text = "var(" + String(m_value.string) + ")";
             break;
     }
 
diff --git a/Source/core/css/CSSPrimitiveValue.h b/Source/core/css/CSSPrimitiveValue.h
index 8e677b1..3571cb0 100644
--- a/Source/core/css/CSSPrimitiveValue.h
+++ b/Source/core/css/CSSPrimitiveValue.h
@@ -120,7 +120,7 @@
         // This is used internally for counter names (as opposed to counter values)
         CSS_COUNTER_NAME = 110,
 
-        // This is used by the CSS Exclusions draft
+        // This is used by the CSS Shapes draft
         CSS_SHAPE = 111,
 
         // Used by border images.
@@ -195,6 +195,7 @@
     bool isViewportPercentageLength() const { return m_primitiveUnitType >= CSS_VW && m_primitiveUnitType <= CSS_VMAX; }
     bool isFlex() const { return primitiveType() == CSS_FR; }
     bool isValueID() const { return m_primitiveUnitType == CSS_VALUE_ID; }
+    bool colorIsDerivedFromElement() const;
 
     static PassRefPtr<CSSPrimitiveValue> createIdentifier(CSSValueID valueID) { return adoptRef(new CSSPrimitiveValue(valueID)); }
     static PassRefPtr<CSSPrimitiveValue> createIdentifier(CSSPropertyID propertyID) { return adoptRef(new CSSPrimitiveValue(propertyID)); }
@@ -305,7 +306,7 @@
 
     template<typename T> inline operator T() const; // Defined in CSSPrimitiveValueMappings.h
 
-    String customCssText() const;
+    String customCssText(CssTextFormattingFlags = QuoteCSSStringIfNeeded) const;
     String customSerializeResolvingVariables(const HashMap<AtomicString, String>&) const;
     bool hasVariableReference() const;
 
diff --git a/Source/core/css/CSSPrimitiveValueMappings.h b/Source/core/css/CSSPrimitiveValueMappings.h
index 28ff567..d9a01fb 100644
--- a/Source/core/css/CSSPrimitiveValueMappings.h
+++ b/Source/core/css/CSSPrimitiveValueMappings.h
@@ -1242,10 +1242,10 @@
         m_value.valueID = CSSValueWebkitInlineBox;
         break;
     case FLEX:
-        m_value.valueID = CSSValueWebkitFlex;
+        m_value.valueID = CSSValueFlex;
         break;
     case INLINE_FLEX:
-        m_value.valueID = CSSValueWebkitInlineFlex;
+        m_value.valueID = CSSValueInlineFlex;
         break;
     case GRID:
         m_value.valueID = CSSValueGrid;
@@ -1267,6 +1267,11 @@
     if (m_value.valueID == CSSValueNone)
         return NONE;
 
+    if (m_value.valueID == CSSValueWebkitFlex)
+        return FLEX;
+    if (m_value.valueID == CSSValueWebkitInlineFlex)
+        return INLINE_FLEX;
+
     EDisplay display = static_cast<EDisplay>(m_value.valueID - CSSValueInline);
     ASSERT(display >= INLINE && display <= NONE);
     return display;
diff --git a/Source/core/css/CSSProperties.in b/Source/core/css/CSSProperties.in
index 5ccc5c5..cefab14 100644
--- a/Source/core/css/CSSProperties.in
+++ b/Source/core/css/CSSProperties.in
@@ -2,6 +2,9 @@
 //   should use this for make_css_property_names.py
 // Note: Mandatory blank line to skip parameter parsing phase
 
+align-content
+align-items
+align-self type_name=EAlignItems
 background-attachment custom_all
 background-blend-mode custom_all
 background-clip custom_all
@@ -28,9 +31,15 @@
 clear
 color custom_all
 empty-cells type_name=EEmptyCell
+flex-basis apply_type=length, use_auto
+flex-direction
+flex-grow type_name=float
+flex-shrink type_name=float
+flex-wrap
 float type_name=EFloat, name_for_methods=Floating
 grid-auto-flow type_name=GridAutoFlow
 height apply_type=length, initial=initialSize, use_auto, use_intrinsic
+justify-content
 image-rendering
 left apply_type=length, initial=initialOffset, use_auto
 list-style-position
@@ -45,6 +54,7 @@
 min-width apply_type=length, initial=initialMinSize, use_auto, use_intrinsic
 mix-blend-mode type_name=BlendMode, name_for_methods=BlendMode
 opacity type_name=float
+order type_name=int
 orphans type_name=short, custom_all
 outline-color custom_all
 overflow-wrap
@@ -80,9 +90,14 @@
 zoom custom_all
 z-index type_name=int, custom_all
 
--webkit-align-content
--webkit-align-items
--webkit-align-self type_name=EAlignItems
+-webkit-animation-delay custom_all
+-webkit-animation-direction custom_all
+-webkit-animation-duration custom_all
+-webkit-animation-fillMode custom_all
+-webkit-animation-iteration-count custom_all
+-webkit-animation-name custom_all
+-webkit-animation-play-state custom_all
+-webkit-animation-timing-function custom_all
 -webkit-appearance type_name=ControlPart
 -webkit-backface-visibility
 -webkit-background-clip use_handlers_for=CSSPropertyBackgroundClip
@@ -111,11 +126,6 @@
 -webkit-column-rule-style type_name=EBorderStyle, initial=initialBorderStyle
 -webkit-column-span type_name=ColumnSpan
 -webkit-column-width type_name=float, custom_all
--webkit-flex-basis apply_type=length, use_auto
--webkit-flex-direction
--webkit-flex-grow type_name=float
--webkit-flex-shrink type_name=float
--webkit-flex-wrap
 -webkit-flow-from type_name=const AtomicString&, name_for_methods=RegionThread, custom_value
 -webkit-flow-into type_name=const AtomicString&, name_for_methods=FlowThread, custom_value
 -webkit-highlight type_name=const AtomicString&, custom_value
@@ -124,7 +134,6 @@
 -webkit-hyphenate-limit-before type_name=short, name_for_methods=HyphenationLimitBefore, custom_value
 -webkit-hyphenate-limit-lines type_name=short, name_for_methods=HyphenationLimitLines, custom_value
 -webkit-hyphens type_name=Hyphens
--webkit-justify-content
 -webkit-line-align type_name=LineAlign
 -webkit-line-break type_name=LineBreak
 -webkit-line-clamp type_name=LineClampValue
@@ -148,7 +157,6 @@
 -webkit-mask-repeat-x custom_all
 -webkit-mask-repeat-y custom_all
 -webkit-mask-size custom_all
--webkit-order type_name=int
 -webkit-perspective-origin-x apply_type=length
 -webkit-perspective-origin-y apply_type=length
 -webkit-print-color-adjust type_name=PrintColorAdjust
@@ -170,6 +178,10 @@
 -webkit-transform-origin-x apply_type=length
 -webkit-transform-origin-y apply_type=length
 -webkit-transform-style name_for_methods=TransformStyle3D
+-webkit-transition-delay custom_all
+-webkit-transition-duration custom_all
+-webkit-transition-property custom_all
+-webkit-transition-timing-function custom_all
 -webkit-user-drag
 -webkit-user-modify
 -webkit-user-select
diff --git a/Source/core/css/CSSProperty.cpp b/Source/core/css/CSSProperty.cpp
index d5cca5e..57f9439 100644
--- a/Source/core/css/CSSProperty.cpp
+++ b/Source/core/css/CSSProperty.cpp
@@ -26,8 +26,6 @@
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 
-#include <wtf/text/StringBuilder.h>
-
 namespace WebCore {
 
 struct SameSizeAsCSSProperty {
@@ -503,9 +501,9 @@
     case CSSPropertyUnicodeRange:
     case CSSPropertyVectorEffect:
     case CSSPropertyVerticalAlign:
-    case CSSPropertyWebkitAlignContent:
-    case CSSPropertyWebkitAlignItems:
-    case CSSPropertyWebkitAlignSelf:
+    case CSSPropertyAlignContent:
+    case CSSPropertyAlignItems:
+    case CSSPropertyAlignSelf:
     case CSSPropertyWebkitAnimation:
     case CSSPropertyWebkitAnimationDelay:
     case CSSPropertyWebkitAnimationDirection:
@@ -566,27 +564,27 @@
     case CSSPropertyWebkitColumnWidth:
     case CSSPropertyWebkitColumns:
     case CSSPropertyWebkitFilter:
-    case CSSPropertyWebkitFlex:
-    case CSSPropertyWebkitFlexBasis:
-    case CSSPropertyWebkitFlexDirection:
-    case CSSPropertyWebkitFlexFlow:
-    case CSSPropertyWebkitFlexGrow:
-    case CSSPropertyWebkitFlexShrink:
-    case CSSPropertyWebkitFlexWrap:
+    case CSSPropertyFlex:
+    case CSSPropertyFlexBasis:
+    case CSSPropertyFlexDirection:
+    case CSSPropertyFlexFlow:
+    case CSSPropertyFlexGrow:
+    case CSSPropertyFlexShrink:
+    case CSSPropertyFlexWrap:
     case CSSPropertyWebkitFontSizeDelta:
-    case CSSPropertyGridAfter:
+    case CSSPropertyGridArea:
     case CSSPropertyGridAutoColumns:
     case CSSPropertyGridAutoFlow:
     case CSSPropertyGridAutoRows:
-    case CSSPropertyGridBefore:
     case CSSPropertyGridColumn:
-    case CSSPropertyGridColumns:
-    case CSSPropertyGridEnd:
+    case CSSPropertyGridColumnEnd:
+    case CSSPropertyGridColumnStart:
+    case CSSPropertyGridDefinitionColumns:
+    case CSSPropertyGridDefinitionRows:
     case CSSPropertyGridRow:
-    case CSSPropertyGridRows:
-    case CSSPropertyGridStart:
-    case CSSPropertyGridArea:
-    case CSSPropertyWebkitJustifyContent:
+    case CSSPropertyGridRowEnd:
+    case CSSPropertyGridRowStart:
+    case CSSPropertyJustifyContent:
     case CSSPropertyWebkitLineClamp:
     case CSSPropertyWebkitLogicalHeight:
     case CSSPropertyWebkitLogicalWidth:
@@ -604,7 +602,7 @@
     case CSSPropertyWebkitMarqueeIncrement:
     case CSSPropertyWebkitMarqueeRepetition:
     case CSSPropertyWebkitMarqueeSpeed:
-    case CSSPropertyWebkitOrder:
+    case CSSPropertyOrder:
     case CSSPropertyWebkitMarqueeStyle:
     case CSSPropertyWebkitMask:
     case CSSPropertyWebkitMaskBoxImage:
diff --git a/Source/core/css/CSSProperty.h b/Source/core/css/CSSProperty.h
index 1435888..7b12f9b 100644
--- a/Source/core/css/CSSProperty.h
+++ b/Source/core/css/CSSProperty.h
@@ -25,7 +25,6 @@
 #include "core/css/CSSValue.h"
 #include "core/platform/text/TextDirection.h"
 #include "core/platform/text/WritingMode.h"
-#include "core/rendering/style/RenderStyleConstants.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
 
diff --git a/Source/core/css/CSSPropertyNames.in b/Source/core/css/CSSPropertyNames.in
index 4cf9805..7faa2a5 100644
--- a/Source/core/css/CSSPropertyNames.in
+++ b/Source/core/css/CSSPropertyNames.in
@@ -265,30 +265,41 @@
 -webkit-columns
 -webkit-box-decoration-break
 -webkit-filter
--webkit-align-content
--webkit-align-items
--webkit-align-self
--webkit-flex
--webkit-flex-basis
--webkit-flex-direction
--webkit-flex-flow
--webkit-flex-grow
--webkit-flex-shrink
--webkit-flex-wrap
--webkit-justify-content
+align-content
+-webkit-align-content alias_for=align-content
+align-items
+-webkit-align-items alias_for=align-items
+align-self
+-webkit-align-self alias_for=align-self
+flex
+-webkit-flex alias_for=flex
+flex-basis
+-webkit-flex-basis alias_for=flex-basis
+flex-direction
+-webkit-flex-direction alias_for=flex-direction
+flex-flow
+-webkit-flex-flow alias_for=flex-flow
+flex-grow
+-webkit-flex-grow alias_for=flex-grow
+flex-shrink
+-webkit-flex-shrink alias_for=flex-shrink
+flex-wrap
+-webkit-flex-wrap alias_for=flex-wrap
+justify-content
+-webkit-justify-content alias_for=justify-content
 -webkit-font-size-delta
 grid-auto-columns
-grid-auto-rows
-grid-columns
-grid-rows
-grid-start
-grid-end
-grid-before
-grid-after
-grid-column
-grid-row
 grid-auto-flow
+grid-auto-rows
 grid-area
+grid-column
+grid-column-end
+grid-column-start
+grid-definition-columns
+grid-definition-rows
+grid-row
+grid-row-end
+grid-row-start
 -webkit-highlight
 -webkit-hyphenate-character
 -webkit-hyphenate-limit-after
@@ -341,7 +352,8 @@
 -webkit-max-logical-height
 -webkit-min-logical-width
 -webkit-min-logical-height
--webkit-order
+order
+-webkit-order alias_for=order
 -webkit-padding-after
 -webkit-padding-before
 -webkit-padding-end
diff --git a/Source/core/css/CSSPropertySourceData.h b/Source/core/css/CSSPropertySourceData.h
index 8dd3d43..f08deea 100644
--- a/Source/core/css/CSSPropertySourceData.h
+++ b/Source/core/css/CSSPropertySourceData.h
@@ -31,12 +31,10 @@
 #ifndef CSSPropertySourceData_h
 #define CSSPropertySourceData_h
 
-#include <utility>
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/RefCounted.h>
-#include <wtf/Vector.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/Forward.h"
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSReflectValue.cpp b/Source/core/css/CSSReflectValue.cpp
index 56ac5d0..6a8d2c9 100644
--- a/Source/core/css/CSSReflectValue.cpp
+++ b/Source/core/css/CSSReflectValue.cpp
@@ -28,7 +28,6 @@
 
 #include "core/css/CSSPrimitiveValue.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/text/StringBuilder.h>
 
 using namespace std;
 
diff --git a/Source/core/css/CSSReflectValue.h b/Source/core/css/CSSReflectValue.h
index 7a97e3d..82b5ea8 100644
--- a/Source/core/css/CSSReflectValue.h
+++ b/Source/core/css/CSSReflectValue.h
@@ -26,10 +26,9 @@
 #ifndef CSSReflectValue_h
 #define CSSReflectValue_h
 
-#include "core/css/CSSReflectionDirection.h"
 #include "core/css/CSSValue.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSRegionRule.cpp b/Source/core/css/CSSRegionRule.cpp
index 7a34ab1..27278dc 100644
--- a/Source/core/css/CSSRegionRule.cpp
+++ b/Source/core/css/CSSRegionRule.cpp
@@ -33,10 +33,7 @@
 #include "core/css/CSSRegionRule.h"
 
 #include "RuntimeEnabledFeatures.h"
-#include "core/css/CSSParser.h"
-#include "core/css/CSSRuleList.h"
 #include "core/css/StyleRule.h"
-#include "wtf/MemoryInstrumentationVector.h"
 #include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
diff --git a/Source/core/css/CSSRuleList.cpp b/Source/core/css/CSSRuleList.cpp
index 8b7fcea..3a21a47 100644
--- a/Source/core/css/CSSRuleList.cpp
+++ b/Source/core/css/CSSRuleList.cpp
@@ -23,7 +23,7 @@
 #include "core/css/CSSRuleList.h"
 
 #include "core/css/CSSRule.h"
-#include <wtf/MemoryInstrumentationVector.h>
+#include "wtf/MemoryInstrumentationVector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSRuleList.h b/Source/core/css/CSSRuleList.h
index d7bf17d..f63c3cd 100644
--- a/Source/core/css/CSSRuleList.h
+++ b/Source/core/css/CSSRuleList.h
@@ -23,11 +23,9 @@
 #define CSSRuleList_h
 
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Vector.h>
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSSegmentedFontFace.h b/Source/core/css/CSSSegmentedFontFace.h
index 6507d17..662045d 100644
--- a/Source/core/css/CSSSegmentedFontFace.h
+++ b/Source/core/css/CSSSegmentedFontFace.h
@@ -26,11 +26,10 @@
 #ifndef CSSSegmentedFontFace_h
 #define CSSSegmentedFontFace_h
 
-#include <wtf/HashMap.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/Vector.h>
-#include <wtf/unicode/Unicode.h>
+#include "wtf/HashMap.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSSelector.cpp b/Source/core/css/CSSSelector.cpp
index 74adeb1..9d471fb 100644
--- a/Source/core/css/CSSSelector.cpp
+++ b/Source/core/css/CSSSelector.cpp
@@ -30,11 +30,10 @@
 #include "RuntimeEnabledFeatures.h"
 #include "core/css/CSSOMUtils.h"
 #include "core/css/CSSSelectorList.h"
-#include <wtf/Assertions.h>
-#include <wtf/HashMap.h>
-#include <wtf/StdLibExtras.h>
-#include <wtf/text/StringBuilder.h>
-#include <wtf/Vector.h>
+#include "wtf/Assertions.h"
+#include "wtf/HashMap.h"
+#include "wtf/StdLibExtras.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
@@ -182,8 +181,6 @@
         return FULL_SCREEN_DOCUMENT;
     case PseudoFullScreenAncestor:
         return FULL_SCREEN_ANCESTOR;
-    case PseudoAnimatingFullScreenTransition:
-        return ANIMATING_FULL_SCREEN_TRANSITION;
     case PseudoUnknown:
     case PseudoEmpty:
     case PseudoFirstChild:
@@ -327,7 +324,6 @@
     DEFINE_STATIC_LOCAL(AtomicString, fullScreen, ("-webkit-full-screen", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, fullScreenDocument, ("-webkit-full-screen-document", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, fullScreenAncestor, ("-webkit-full-screen-ancestor", AtomicString::ConstructFromLiteral));
-    DEFINE_STATIC_LOCAL(AtomicString, animatingFullScreenTransition, ("-webkit-animating-full-screen-transition", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, cue, ("cue(", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, futureCue, ("future", AtomicString::ConstructFromLiteral));
     DEFINE_STATIC_LOCAL(AtomicString, pastCue, ("past", AtomicString::ConstructFromLiteral));
@@ -408,7 +404,6 @@
         nameToPseudoType->set(fullScreen.impl(), CSSSelector::PseudoFullScreen);
         nameToPseudoType->set(fullScreenDocument.impl(), CSSSelector::PseudoFullScreenDocument);
         nameToPseudoType->set(fullScreenAncestor.impl(), CSSSelector::PseudoFullScreenAncestor);
-        nameToPseudoType->set(animatingFullScreenTransition.impl(), CSSSelector::PseudoAnimatingFullScreenTransition);
         nameToPseudoType->set(cue.impl(), CSSSelector::PseudoCue);
         nameToPseudoType->set(futureCue.impl(), CSSSelector::PseudoFutureCue);
         nameToPseudoType->set(pastCue.impl(), CSSSelector::PseudoPastCue);
@@ -526,7 +521,6 @@
     case PseudoFullScreen:
     case PseudoFullScreenDocument:
     case PseudoFullScreenAncestor:
-    case PseudoAnimatingFullScreenTransition:
     case PseudoSeamlessDocument:
     case PseudoInRange:
     case PseudoOutOfRange:
diff --git a/Source/core/css/CSSSelector.h b/Source/core/css/CSSSelector.h
index e8fc3ae..6a460c8 100644
--- a/Source/core/css/CSSSelector.h
+++ b/Source/core/css/CSSSelector.h
@@ -24,9 +24,8 @@
 
 #include "core/dom/QualifiedName.h"
 #include "core/rendering/style/RenderStyleConstants.h"
-#include <wtf/Noncopyable.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
     class CSSSelectorList;
@@ -153,7 +152,6 @@
             PseudoFullScreen,
             PseudoFullScreenDocument,
             PseudoFullScreenAncestor,
-            PseudoAnimatingFullScreenTransition,
             PseudoInRange,
             PseudoOutOfRange,
             PseudoUserAgentCustomElement,
diff --git a/Source/core/css/CSSStyleDeclaration.h b/Source/core/css/CSSStyleDeclaration.h
index 69939ce..68405ad 100644
--- a/Source/core/css/CSSStyleDeclaration.h
+++ b/Source/core/css/CSSStyleDeclaration.h
@@ -33,7 +33,6 @@
 class CSSValue;
 class MutableStylePropertySet;
 class StylePropertySet;
-class StyledElement;
 
 typedef int ExceptionCode;
 
diff --git a/Source/core/css/CSSStyleSheet.h b/Source/core/css/CSSStyleSheet.h
index bcc6550..37f83ab 100644
--- a/Source/core/css/CSSStyleSheet.h
+++ b/Source/core/css/CSSStyleSheet.h
@@ -21,12 +21,9 @@
 #ifndef CSSStyleSheet_h
 #define CSSStyleSheet_h
 
-#include "core/css/CSSParserMode.h"
 #include "core/css/CSSRule.h"
 #include "core/css/StyleSheet.h"
-#include "wtf/HashMap.h"
 #include "wtf/Noncopyable.h"
-#include "wtf/text/AtomicStringHash.h"
 #include "wtf/text/TextPosition.h"
 
 namespace WebCore {
diff --git a/Source/core/css/CSSSupportsRule.cpp b/Source/core/css/CSSSupportsRule.cpp
index 8c96b05..08244c6 100644
--- a/Source/core/css/CSSSupportsRule.cpp
+++ b/Source/core/css/CSSSupportsRule.cpp
@@ -31,8 +31,7 @@
 
 #include "core/css/CSSRule.h"
 #include "core/css/StyleRule.h"
-#include <wtf/MemoryInstrumentationVector.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSTransformValue.h b/Source/core/css/CSSTransformValue.h
index 635a608..de0637a 100644
--- a/Source/core/css/CSSTransformValue.h
+++ b/Source/core/css/CSSTransformValue.h
@@ -28,7 +28,6 @@
 
 #include "core/css/CSSValueList.h"
 #include "wtf/PassRefPtr.h"
-#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSUnicodeRangeValue.h b/Source/core/css/CSSUnicodeRangeValue.h
index 6360df2..3fa3647 100644
--- a/Source/core/css/CSSUnicodeRangeValue.h
+++ b/Source/core/css/CSSUnicodeRangeValue.h
@@ -27,8 +27,7 @@
 #define CSSUnicodeRangeValue_h
 
 #include "core/css/CSSValue.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/unicode/Unicode.h>
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSValue.h b/Source/core/css/CSSValue.h
index 18c0cb6..9fe4b60 100644
--- a/Source/core/css/CSSValue.h
+++ b/Source/core/css/CSSValue.h
@@ -31,6 +31,8 @@
 
 class StyleSheetContents;
 
+enum CssTextFormattingFlags { QuoteCSSStringIfNeeded, AlwaysQuoteCSSString };
+
 // FIXME: The current CSSValue and subclasses should be turned into internal types (StyleValue).
 // The few subtypes that are actually exposed in CSSOM can be seen in the cloneForCSSOM() function.
 // They should be handled by separate wrapper classes.
diff --git a/Source/core/css/CSSValueKeywords.in b/Source/core/css/CSSValueKeywords.in
index 6dfc4fa..a7d1e7e 100644
--- a/Source/core/css/CSSValueKeywords.in
+++ b/Source/core/css/CSSValueKeywords.in
@@ -340,12 +340,14 @@
 table-caption
 -webkit-box
 -webkit-inline-box
--webkit-flex
--webkit-inline-flex
+flex
+inline-flex
 grid
 inline-grid
 lazy-block
 //none
+-webkit-flex
+-webkit-inline-flex
 //
 // CSS_PROP_CURSOR:
 // The order here must match the order of the ECursor enum in RenderStyleConstants.h.
@@ -581,6 +583,9 @@
 -webkit-max-content
 -webkit-fill-available
 -webkit-fit-content
+// Unprefixed for CSS Grid Layout.
+min-content
+max-content
 
 //
 // CSS_PROP_TEXT_OVERFLOW
diff --git a/Source/core/css/CSSValueList.cpp b/Source/core/css/CSSValueList.cpp
index 1a6adf9..960ef32 100644
--- a/Source/core/css/CSSValueList.cpp
+++ b/Source/core/css/CSSValueList.cpp
@@ -23,9 +23,8 @@
 
 #include "core/css/CSSParserValues.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/MemoryInstrumentationVector.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/MemoryInstrumentationVector.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
@@ -97,7 +96,7 @@
     return newList.release();
 }
 
-String CSSValueList::customCssText() const
+String CSSValueList::customCssText(CssTextFormattingFlags formattingFlag) const
 {
     StringBuilder result;
     String separator;
@@ -119,7 +118,10 @@
     for (unsigned i = 0; i < size; i++) {
         if (!result.isEmpty())
             result.append(separator);
-        result.append(m_values[i]->cssText());
+        if (formattingFlag == AlwaysQuoteCSSString && m_values[i]->isPrimitiveValue())
+            result.append(toCSSPrimitiveValue(m_values[i].get())->customCssText(AlwaysQuoteCSSString));
+        else
+            result.append(m_values[i]->cssText());
     }
 
     return result.toString();
diff --git a/Source/core/css/CSSValueList.h b/Source/core/css/CSSValueList.h
index 7532e37..ef47a42 100644
--- a/Source/core/css/CSSValueList.h
+++ b/Source/core/css/CSSValueList.h
@@ -59,7 +59,7 @@
     bool hasValue(CSSValue*) const;
     PassRefPtr<CSSValueList> copy();
 
-    String customCssText() const;
+    String customCssText(CssTextFormattingFlags = QuoteCSSStringIfNeeded) const;
     bool equals(const CSSValueList&) const;
     bool equals(const CSSValue&) const;
     String customSerializeResolvingVariables(const HashMap<AtomicString, String>&) const;
diff --git a/Source/core/css/DeprecatedStyleBuilder.cpp b/Source/core/css/DeprecatedStyleBuilder.cpp
index d3292f3..1553246 100644
--- a/Source/core/css/DeprecatedStyleBuilder.cpp
+++ b/Source/core/css/DeprecatedStyleBuilder.cpp
@@ -43,10 +43,10 @@
 #include "core/rendering/RenderView.h"
 #include "core/rendering/style/BasicShapes.h"
 #include "core/rendering/style/CursorList.h"
-#include "core/rendering/style/ExclusionShapeValue.h"
 #include "core/rendering/style/RenderStyle.h"
-#include <wtf/StdLibExtras.h>
-#include <wtf/UnusedParam.h>
+#include "core/rendering/style/ShapeValue.h"
+#include "wtf/StdLibExtras.h"
+#include "wtf/UnusedParam.h"
 
 using namespace std;
 
@@ -1282,82 +1282,6 @@
     static PropertyHandler createHandler() { return PropertyHandler(&applyInheritValue, &applyInitialValue, &applyValue); }
 };
 
-template <typename T,
-          T (CSSAnimationData::*getterFunction)() const,
-          void (CSSAnimationData::*setterFunction)(T),
-          bool (CSSAnimationData::*testFunction)() const,
-          void (CSSAnimationData::*clearFunction)(),
-          T (*initialFunction)(),
-          void (CSSToStyleMap::*mapFunction)(CSSAnimationData*, CSSValue*),
-          CSSAnimationDataList* (RenderStyle::*animationGetterFunction)(),
-          const CSSAnimationDataList* (RenderStyle::*immutableAnimationGetterFunction)() const>
-class ApplyPropertyAnimation {
-public:
-    static void setValue(CSSAnimationData* animation, T value) { (animation->*setterFunction)(value); }
-    static T value(const CSSAnimationData* animation) { return (animation->*getterFunction)(); }
-    static bool test(const CSSAnimationData* animation) { return (animation->*testFunction)(); }
-    static void clear(CSSAnimationData* animation) { (animation->*clearFunction)(); }
-    static T initial() { return (*initialFunction)(); }
-    static void map(StyleResolver* styleResolver, CSSAnimationData* animation, CSSValue* value) { (styleResolver->styleMap()->*mapFunction)(animation, value); }
-    static CSSAnimationDataList* accessAnimations(RenderStyle* style) { return (style->*animationGetterFunction)(); }
-    static const CSSAnimationDataList* animations(RenderStyle* style) { return (style->*immutableAnimationGetterFunction)(); }
-
-    static void applyInheritValue(CSSPropertyID, StyleResolver* styleResolver)
-    {
-        CSSAnimationDataList* list = accessAnimations(styleResolver->style());
-        const CSSAnimationDataList* parentList = animations(styleResolver->parentStyle());
-        size_t i = 0, parentSize = parentList ? parentList->size() : 0;
-        for ( ; i < parentSize && test(parentList->animation(i)); ++i) {
-            if (list->size() <= i)
-                list->append(CSSAnimationData::create());
-            setValue(list->animation(i), value(parentList->animation(i)));
-            list->animation(i)->setAnimationMode(parentList->animation(i)->animationMode());
-        }
-
-        /* Reset any remaining animations to not have the property set. */
-        for ( ; i < list->size(); ++i)
-            clear(list->animation(i));
-    }
-
-    static void applyInitialValue(CSSPropertyID propertyID, StyleResolver* styleResolver)
-    {
-        CSSAnimationDataList* list = accessAnimations(styleResolver->style());
-        if (list->isEmpty())
-            list->append(CSSAnimationData::create());
-        setValue(list->animation(0), initial());
-        if (propertyID == CSSPropertyWebkitTransitionProperty)
-            list->animation(0)->setAnimationMode(CSSAnimationData::AnimateAll);
-        for (size_t i = 1; i < list->size(); ++i)
-            clear(list->animation(i));
-    }
-
-    static void applyValue(CSSPropertyID, StyleResolver* styleResolver, CSSValue* value)
-    {
-        CSSAnimationDataList* list = accessAnimations(styleResolver->style());
-        size_t childIndex = 0;
-        if (value->isValueList()) {
-            /* Walk each value and put it into an animation, creating new animations as needed. */
-            for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
-                if (childIndex <= list->size())
-                    list->append(CSSAnimationData::create());
-                map(styleResolver, list->animation(childIndex), i.value());
-                ++childIndex;
-            }
-        } else {
-            if (list->isEmpty())
-                list->append(CSSAnimationData::create());
-            map(styleResolver, list->animation(childIndex), value);
-            childIndex = 1;
-        }
-        for ( ; childIndex < list->size(); ++childIndex) {
-            /* Reset all remaining animations to not have the property set. */
-            clear(list->animation(childIndex));
-        }
-    }
-
-    static PropertyHandler createHandler() { return PropertyHandler(&applyInheritValue, &applyInitialValue, &applyValue); }
-};
-
 class ApplyPropertyOutlineStyle {
 public:
     static void applyInheritValue(CSSPropertyID propertyID, StyleResolver* styleResolver)
@@ -1537,10 +1461,10 @@
     }
 };
 
-template <ExclusionShapeValue* (RenderStyle::*getterFunction)() const, void (RenderStyle::*setterFunction)(PassRefPtr<ExclusionShapeValue>), ExclusionShapeValue* (*initialFunction)()>
-class ApplyPropertyExclusionShape {
+template <ShapeValue* (RenderStyle::*getterFunction)() const, void (RenderStyle::*setterFunction)(PassRefPtr<ShapeValue>), ShapeValue* (*initialFunction)()>
+class ApplyPropertyShape {
 public:
-    static void setValue(RenderStyle* style, PassRefPtr<ExclusionShapeValue> value) { (style->*setterFunction)(value); }
+    static void setValue(RenderStyle* style, PassRefPtr<ShapeValue> value) { (style->*setterFunction)(value); }
     static void applyValue(CSSPropertyID property, StyleResolver* styleResolver, CSSValue* value)
     {
         if (value->isPrimitiveValue()) {
@@ -1549,19 +1473,19 @@
                 setValue(styleResolver->style(), 0);
             // FIXME Bug 102571: Layout for the value 'outside-shape' is not yet implemented
             else if (primitiveValue->getValueID() == CSSValueOutsideShape)
-                setValue(styleResolver->style(), ExclusionShapeValue::createOutsideValue());
+                setValue(styleResolver->style(), ShapeValue::createOutsideValue());
             else if (primitiveValue->isShape()) {
-                RefPtr<ExclusionShapeValue> shape = ExclusionShapeValue::createShapeValue(basicShapeForValue(styleResolver, primitiveValue->getShapeValue()));
+                RefPtr<ShapeValue> shape = ShapeValue::createShapeValue(basicShapeForValue(styleResolver, primitiveValue->getShapeValue()));
                 setValue(styleResolver->style(), shape.release());
             }
         } else if (value->isImageValue()) {
-            RefPtr<ExclusionShapeValue> shape = ExclusionShapeValue::createImageValue(styleResolver->styleImage(property, value));
+            RefPtr<ShapeValue> shape = ShapeValue::createImageValue(styleResolver->styleImage(property, value));
             setValue(styleResolver->style(), shape.release());
         }
     }
     static PropertyHandler createHandler()
     {
-        PropertyHandler handler = ApplyPropertyDefaultBase<ExclusionShapeValue*, getterFunction, PassRefPtr<ExclusionShapeValue>, setterFunction, ExclusionShapeValue*, initialFunction>::createHandler();
+        PropertyHandler handler = ApplyPropertyDefaultBase<ShapeValue*, getterFunction, PassRefPtr<ShapeValue>, setterFunction, ShapeValue*, initialFunction>::createHandler();
         return PropertyHandler(handler.inheritFunction(), handler.initialFunction(), &applyValue);
     }
 };
@@ -1671,14 +1595,6 @@
     setPropertyHandler(CSSPropertyTextIndent, ApplyPropertyTextIndent::createHandler());
     setPropertyHandler(CSSPropertyTextRendering, ApplyPropertyFont<TextRenderingMode, &FontDescription::textRenderingMode, &FontDescription::setTextRenderingMode, AutoTextRendering>::createHandler());
     setPropertyHandler(CSSPropertyVerticalAlign, ApplyPropertyVerticalAlign::createHandler());
-    setPropertyHandler(CSSPropertyWebkitAnimationDelay, ApplyPropertyAnimation<double, &CSSAnimationData::delay, &CSSAnimationData::setDelay, &CSSAnimationData::isDelaySet, &CSSAnimationData::clearDelay, &CSSAnimationData::initialAnimationDelay, &CSSToStyleMap::mapAnimationDelay, &RenderStyle::accessAnimations, &RenderStyle::animations>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitAnimationDirection, ApplyPropertyAnimation<CSSAnimationData::AnimationDirection, &CSSAnimationData::direction, &CSSAnimationData::setDirection, &CSSAnimationData::isDirectionSet, &CSSAnimationData::clearDirection, &CSSAnimationData::initialAnimationDirection, &CSSToStyleMap::mapAnimationDirection, &RenderStyle::accessAnimations, &RenderStyle::animations>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitAnimationDuration, ApplyPropertyAnimation<double, &CSSAnimationData::duration, &CSSAnimationData::setDuration, &CSSAnimationData::isDurationSet, &CSSAnimationData::clearDuration, &CSSAnimationData::initialAnimationDuration, &CSSToStyleMap::mapAnimationDuration, &RenderStyle::accessAnimations, &RenderStyle::animations>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitAnimationFillMode, ApplyPropertyAnimation<unsigned, &CSSAnimationData::fillMode, &CSSAnimationData::setFillMode, &CSSAnimationData::isFillModeSet, &CSSAnimationData::clearFillMode, &CSSAnimationData::initialAnimationFillMode, &CSSToStyleMap::mapAnimationFillMode, &RenderStyle::accessAnimations, &RenderStyle::animations>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitAnimationIterationCount, ApplyPropertyAnimation<double, &CSSAnimationData::iterationCount, &CSSAnimationData::setIterationCount, &CSSAnimationData::isIterationCountSet, &CSSAnimationData::clearIterationCount, &CSSAnimationData::initialAnimationIterationCount, &CSSToStyleMap::mapAnimationIterationCount, &RenderStyle::accessAnimations, &RenderStyle::animations>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitAnimationName, ApplyPropertyAnimation<const String&, &CSSAnimationData::name, &CSSAnimationData::setName, &CSSAnimationData::isNameSet, &CSSAnimationData::clearName, &CSSAnimationData::initialAnimationName, &CSSToStyleMap::mapAnimationName, &RenderStyle::accessAnimations, &RenderStyle::animations>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitAnimationPlayState, ApplyPropertyAnimation<EAnimPlayState, &CSSAnimationData::playState, &CSSAnimationData::setPlayState, &CSSAnimationData::isPlayStateSet, &CSSAnimationData::clearPlayState, &CSSAnimationData::initialAnimationPlayState, &CSSToStyleMap::mapAnimationPlayState, &RenderStyle::accessAnimations, &RenderStyle::animations>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitAnimationTimingFunction, ApplyPropertyAnimation<const PassRefPtr<TimingFunction>, &CSSAnimationData::timingFunction, &CSSAnimationData::setTimingFunction, &CSSAnimationData::isTimingFunctionSet, &CSSAnimationData::clearTimingFunction, &CSSAnimationData::initialAnimationTimingFunction, &CSSToStyleMap::mapAnimationTimingFunction, &RenderStyle::accessAnimations, &RenderStyle::animations>::createHandler());
     setPropertyHandler(CSSPropertyWebkitAspectRatio, ApplyPropertyAspectRatio::createHandler());
     setPropertyHandler(CSSPropertyWebkitBorderHorizontalSpacing, ApplyPropertyComputeLength<short, &RenderStyle::horizontalBorderSpacing, &RenderStyle::setHorizontalBorderSpacing, &RenderStyle::initialHorizontalBorderSpacing>::createHandler());
     setPropertyHandler(CSSPropertyWebkitBorderVerticalSpacing, ApplyPropertyComputeLength<short, &RenderStyle::verticalBorderSpacing, &RenderStyle::setVerticalBorderSpacing, &RenderStyle::initialVerticalBorderSpacing>::createHandler());
@@ -1695,13 +1611,9 @@
     setPropertyHandler(CSSPropertyWebkitPerspectiveOrigin, ApplyPropertyExpanding<SuppressValue, CSSPropertyWebkitPerspectiveOriginX, CSSPropertyWebkitPerspectiveOriginY>::createHandler());
     setPropertyHandler(CSSPropertyWebkitTextEmphasisStyle, ApplyPropertyTextEmphasisStyle::createHandler());
     setPropertyHandler(CSSPropertyWebkitTransformOriginZ, ApplyPropertyComputeLength<float, &RenderStyle::transformOriginZ, &RenderStyle::setTransformOriginZ, &RenderStyle::initialTransformOriginZ>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitTransitionDelay, ApplyPropertyAnimation<double, &CSSAnimationData::delay, &CSSAnimationData::setDelay, &CSSAnimationData::isDelaySet, &CSSAnimationData::clearDelay, &CSSAnimationData::initialAnimationDelay, &CSSToStyleMap::mapAnimationDelay, &RenderStyle::accessTransitions, &RenderStyle::transitions>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitTransitionDuration, ApplyPropertyAnimation<double, &CSSAnimationData::duration, &CSSAnimationData::setDuration, &CSSAnimationData::isDurationSet, &CSSAnimationData::clearDuration, &CSSAnimationData::initialAnimationDuration, &CSSToStyleMap::mapAnimationDuration, &RenderStyle::accessTransitions, &RenderStyle::transitions>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitTransitionProperty, ApplyPropertyAnimation<CSSPropertyID, &CSSAnimationData::property, &CSSAnimationData::setProperty, &CSSAnimationData::isPropertySet, &CSSAnimationData::clearProperty, &CSSAnimationData::initialAnimationProperty, &CSSToStyleMap::mapAnimationProperty, &RenderStyle::accessTransitions, &RenderStyle::transitions>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitTransitionTimingFunction, ApplyPropertyAnimation<const PassRefPtr<TimingFunction>, &CSSAnimationData::timingFunction, &CSSAnimationData::setTimingFunction, &CSSAnimationData::isTimingFunctionSet, &CSSAnimationData::clearTimingFunction, &CSSAnimationData::initialAnimationTimingFunction, &CSSToStyleMap::mapAnimationTimingFunction, &RenderStyle::accessTransitions, &RenderStyle::transitions>::createHandler());
     setPropertyHandler(CSSPropertyWebkitClipPath, ApplyPropertyClipPath<&RenderStyle::clipPath, &RenderStyle::setClipPath, &RenderStyle::initialClipPath>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitShapeInside, ApplyPropertyExclusionShape<&RenderStyle::shapeInside, &RenderStyle::setShapeInside, &RenderStyle::initialShapeInside>::createHandler());
-    setPropertyHandler(CSSPropertyWebkitShapeOutside, ApplyPropertyExclusionShape<&RenderStyle::shapeOutside, &RenderStyle::setShapeOutside, &RenderStyle::initialShapeOutside>::createHandler());
+    setPropertyHandler(CSSPropertyWebkitShapeInside, ApplyPropertyShape<&RenderStyle::shapeInside, &RenderStyle::setShapeInside, &RenderStyle::initialShapeInside>::createHandler());
+    setPropertyHandler(CSSPropertyWebkitShapeOutside, ApplyPropertyShape<&RenderStyle::shapeOutside, &RenderStyle::setShapeOutside, &RenderStyle::initialShapeOutside>::createHandler());
     setPropertyHandler(CSSPropertyWordSpacing, ApplyPropertyComputeLength<int, &RenderStyle::wordSpacing, &RenderStyle::setWordSpacing, &RenderStyle::initialLetterWordSpacing, NormalEnabled, ThicknessDisabled, SVGZoomEnabled>::createHandler());
 }
 
diff --git a/Source/core/css/DeprecatedStyleBuilder.h b/Source/core/css/DeprecatedStyleBuilder.h
index a21d42f..4d4d254 100644
--- a/Source/core/css/DeprecatedStyleBuilder.h
+++ b/Source/core/css/DeprecatedStyleBuilder.h
@@ -27,8 +27,6 @@
 
 #include "CSSPropertyNames.h"
 #include "core/css/StylePropertyShorthand.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
 
 namespace WebCore {
 
diff --git a/Source/core/css/DocumentRuleSets.cpp b/Source/core/css/DocumentRuleSets.cpp
index 213e9fb..4e72f57 100644
--- a/Source/core/css/DocumentRuleSets.cpp
+++ b/Source/core/css/DocumentRuleSets.cpp
@@ -31,7 +31,6 @@
 
 #include "core/css/CSSDefaultStyleSheets.h"
 #include "core/css/CSSStyleSheet.h"
-#include "core/css/MediaQueryEvaluator.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/DocumentStyleSheetCollection.h"
@@ -40,14 +39,14 @@
 
 namespace WebCore {
 
-void ShadowDistributedRules::addRule(StyleRule* rule, size_t selectorIndex, ContainerNode* scope, AddRuleFlags addRuleFlags)
+void ShadowDistributedRules::addRule(StyleRule* rule, size_t selectorIndex, ContainerNode* scopingNode, AddRuleFlags addRuleFlags)
 {
-    if (m_shadowDistributedRuleSetMap.contains(scope))
-        m_shadowDistributedRuleSetMap.get(scope)->addRule(rule, selectorIndex, addRuleFlags);
+    if (m_shadowDistributedRuleSetMap.contains(scopingNode))
+        m_shadowDistributedRuleSetMap.get(scopingNode)->addRule(rule, selectorIndex, addRuleFlags);
     else {
-        OwnPtr<RuleSet> ruleSetForScope = adoptPtr(new RuleSet());
+        OwnPtr<RuleSet> ruleSetForScope = RuleSet::create();
         ruleSetForScope->addRule(rule, selectorIndex, addRuleFlags);
-        m_shadowDistributedRuleSetMap.add(scope, ruleSetForScope.release());
+        m_shadowDistributedRuleSetMap.add(scopingNode, ruleSetForScope.release());
     }
 }
 
@@ -57,6 +56,11 @@
         matchRequests.append(MatchRequest(it->value.get(), includeEmptyRules, it->key));
 }
 
+void ShadowDistributedRules::reset(const ContainerNode* scopingNode)
+{
+    m_shadowDistributedRuleSetMap.remove(scopingNode);
+}
+
 void ShadowDistributedRules::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
 {
     MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
@@ -84,7 +88,7 @@
         tempUserStyle->addRulesFromSheet(pageUserSheet->contents(), medium, &resolver);
     collectRulesFromUserStyleSheets(styleSheetCollection->injectedUserStyleSheets(), *tempUserStyle, medium, resolver);
     collectRulesFromUserStyleSheets(styleSheetCollection->documentUserStyleSheets(), *tempUserStyle, medium, resolver);
-    if (tempUserStyle->m_ruleCount > 0 || tempUserStyle->m_pageRules.size() > 0)
+    if (tempUserStyle->ruleCount() > 0 || tempUserStyle->pageRules().size() > 0)
         m_userStyle = tempUserStyle.release();
 }
 
diff --git a/Source/core/css/DocumentRuleSets.h b/Source/core/css/DocumentRuleSets.h
index 77a024d..dd047ea 100644
--- a/Source/core/css/DocumentRuleSets.h
+++ b/Source/core/css/DocumentRuleSets.h
@@ -42,9 +42,10 @@
 
 class ShadowDistributedRules {
 public:
-    void addRule(StyleRule*, size_t selectorIndex, ContainerNode* scope, AddRuleFlags);
+    void addRule(StyleRule*, size_t selectorIndex, ContainerNode* scopingNode, AddRuleFlags);
     void collectMatchRequests(bool includeEmptyRules, Vector<MatchRequest>&);
     void clear() { m_shadowDistributedRuleSetMap.clear(); }
+    void reset(const ContainerNode* scopingNode);
     bool isEmpty() const { return m_shadowDistributedRuleSetMap.isEmpty(); }
     void reportMemoryUsage(MemoryObjectInfo*) const;
     void collectFeaturesTo(RuleFeatureSet&);
diff --git a/Source/core/css/ElementRuleCollector.cpp b/Source/core/css/ElementRuleCollector.cpp
index a89f953..3f6e411 100644
--- a/Source/core/css/ElementRuleCollector.cpp
+++ b/Source/core/css/ElementRuleCollector.cpp
@@ -34,11 +34,8 @@
 #include "core/css/SelectorCheckerFastPath.h"
 #include "core/css/SiblingTraversalStrategies.h"
 #include "core/css/StylePropertySet.h"
-#include "core/dom/StyledElement.h"
 #include "core/rendering/RenderRegion.h"
 
-#include <wtf/TemporaryChange.h>
-
 namespace WebCore {
 
 StyleResolver::MatchResult& ElementRuleCollector::matchedResult()
@@ -92,7 +89,7 @@
 
     const StyleResolverState& state = m_state;
     Element* element = state.element();
-    const StyledElement* styledElement = state.styledElement();
+    const Element* styledElement = state.styledElement();
     const AtomicString& pseudoId = element->shadowPseudoId();
     if (!pseudoId.isEmpty()) {
         ASSERT(styledElement);
@@ -209,57 +206,66 @@
     return true;
 }
 
+void ElementRuleCollector::collectRuleIfMatches(const RuleData& ruleData, const MatchRequest& matchRequest, StyleResolver::RuleRange& ruleRange)
+{
+    if (m_canUseFastReject && m_selectorFilter.fastRejectSelector(ruleData.selector()))
+        return;
+
+    StyleRule* rule = ruleData.rule();
+    InspectorInstrumentationCookie cookie = InspectorInstrumentation::willMatchRule(document(), rule, m_inspectorCSSOMWrappers, document()->styleSheetCollection());
+    PseudoId dynamicPseudo = NOPSEUDO;
+    if (ruleMatches(ruleData, matchRequest.scope, dynamicPseudo)) {
+        // If the rule has no properties to apply, then ignore it in the non-debug mode.
+        const StylePropertySet* properties = rule->properties();
+        if (!properties || (properties->isEmpty() && !matchRequest.includeEmptyRules)) {
+            InspectorInstrumentation::didMatchRule(cookie, false);
+            return;
+        }
+        // FIXME: Exposing the non-standard getMatchedCSSRules API to web is the only reason this is needed.
+        if (m_sameOriginOnly && !ruleData.hasDocumentSecurityOrigin()) {
+            InspectorInstrumentation::didMatchRule(cookie, false);
+            return;
+        }
+        // If we're matching normal rules, set a pseudo bit if
+        // we really just matched a pseudo-element.
+        if (dynamicPseudo != NOPSEUDO && m_pseudoStyleRequest.pseudoId == NOPSEUDO) {
+            if (m_mode == SelectorChecker::CollectingRules) {
+                InspectorInstrumentation::didMatchRule(cookie, false);
+                return;
+            }
+            if (dynamicPseudo < FIRST_INTERNAL_PSEUDOID)
+                m_state.style()->setHasPseudoStyle(dynamicPseudo);
+        } else {
+            // Update our first/last rule indices in the matched rules array.
+            ++ruleRange.lastRuleIndex;
+            if (ruleRange.firstRuleIndex == -1)
+                ruleRange.firstRuleIndex = ruleRange.lastRuleIndex;
+
+            // Add this rule to our list of matched rules.
+            addMatchedRule(&ruleData);
+            InspectorInstrumentation::didMatchRule(cookie, true);
+            return;
+        }
+    }
+    InspectorInstrumentation::didMatchRule(cookie, false);
+}
+
+void ElementRuleCollector::collectMatchingRulesForList(const RuleData* rules, const MatchRequest& matchRequest, StyleResolver::RuleRange& ruleRange)
+{
+    if (!rules)
+        return;
+    while (!rules->isLastInArray())
+        collectRuleIfMatches(*rules++, matchRequest, ruleRange);
+    collectRuleIfMatches(*rules, matchRequest, ruleRange);
+}
+
 void ElementRuleCollector::collectMatchingRulesForList(const Vector<RuleData>* rules, const MatchRequest& matchRequest, StyleResolver::RuleRange& ruleRange)
 {
     if (!rules)
         return;
-
-    const StyleResolverState& state = m_state;
-
     unsigned size = rules->size();
-    for (unsigned i = 0; i < size; ++i) {
-        const RuleData& ruleData = rules->at(i);
-        if (m_canUseFastReject && m_selectorFilter.fastRejectSelector<RuleData::maximumIdentifierCount>(ruleData.descendantSelectorIdentifierHashes()))
-            continue;
-
-        StyleRule* rule = ruleData.rule();
-        InspectorInstrumentationCookie cookie = InspectorInstrumentation::willMatchRule(document(), rule, m_inspectorCSSOMWrappers, document()->styleSheetCollection());
-        PseudoId dynamicPseudo = NOPSEUDO;
-        if (ruleMatches(ruleData, matchRequest.scope, dynamicPseudo)) {
-            // If the rule has no properties to apply, then ignore it in the non-debug mode.
-            const StylePropertySet* properties = rule->properties();
-            if (!properties || (properties->isEmpty() && !matchRequest.includeEmptyRules)) {
-                InspectorInstrumentation::didMatchRule(cookie, false);
-                continue;
-            }
-            // FIXME: Exposing the non-standard getMatchedCSSRules API to web is the only reason this is needed.
-            if (m_sameOriginOnly && !ruleData.hasDocumentSecurityOrigin()) {
-                InspectorInstrumentation::didMatchRule(cookie, false);
-                continue;
-            }
-            // If we're matching normal rules, set a pseudo bit if
-            // we really just matched a pseudo-element.
-            if (dynamicPseudo != NOPSEUDO && m_pseudoStyleRequest.pseudoId == NOPSEUDO) {
-                if (m_mode == SelectorChecker::CollectingRules) {
-                    InspectorInstrumentation::didMatchRule(cookie, false);
-                    continue;
-                }
-                if (dynamicPseudo < FIRST_INTERNAL_PSEUDOID)
-                    state.style()->setHasPseudoStyle(dynamicPseudo);
-            } else {
-                // Update our first/last rule indices in the matched rules array.
-                ++ruleRange.lastRuleIndex;
-                if (ruleRange.firstRuleIndex == -1)
-                    ruleRange.firstRuleIndex = ruleRange.lastRuleIndex;
-
-                // Add this rule to our list of matched rules.
-                addMatchedRule(&ruleData);
-                InspectorInstrumentation::didMatchRule(cookie, true);
-                continue;
-            }
-        }
-        InspectorInstrumentation::didMatchRule(cookie, false);
-    }
+    for (unsigned i = 0; i < size; ++i)
+        collectRuleIfMatches(rules->at(i), matchRequest, ruleRange);
 }
 
 static inline bool compareRules(const RuleData* r1, const RuleData* r2)
diff --git a/Source/core/css/ElementRuleCollector.h b/Source/core/css/ElementRuleCollector.h
index 4f34110..5d4328b 100644
--- a/Source/core/css/ElementRuleCollector.h
+++ b/Source/core/css/ElementRuleCollector.h
@@ -22,11 +22,10 @@
 #ifndef ElementRuleCollector_h
 #define ElementRuleCollector_h
 
-#include "core/css/MediaQueryEvaluator.h"
 #include "core/css/SelectorChecker.h"
 #include "core/css/resolver/StyleResolver.h"
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -78,7 +77,9 @@
 private:
     Document* document() { return m_state.document(); }
 
+    void collectRuleIfMatches(const RuleData&, const MatchRequest&, StyleResolver::RuleRange&);
     void collectMatchingRulesForList(const Vector<RuleData>*, const MatchRequest&, StyleResolver::RuleRange&);
+    void collectMatchingRulesForList(const RuleData*, const MatchRequest&, StyleResolver::RuleRange&);
     bool ruleMatches(const RuleData&, const ContainerNode* scope, PseudoId&);
 
     void sortMatchedRules();
diff --git a/Source/core/css/FontLoader.cpp b/Source/core/css/FontLoader.cpp
index 564cfd8..6005643 100644
--- a/Source/core/css/FontLoader.cpp
+++ b/Source/core/css/FontLoader.cpp
@@ -34,8 +34,10 @@
 #include "core/css/CSSSegmentedFontFace.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/resolver/StyleResolver.h"
+#include "core/dom/DOMException.h"
 #include "core/dom/Document.h"
 #include "core/page/FrameView.h"
+#include "core/platform/HistogramSupport.h"
 
 namespace WebCore {
 
@@ -147,6 +149,10 @@
 
 void FontLoader::didLayout()
 {
+    if (m_document->page() && m_document->page()->mainFrame() == m_document->frame())
+        m_histogram.record();
+    if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
+        return;
     if (m_loadingCount || (!m_pendingDoneEvent && m_fontsReadyCallbacks.isEmpty()))
         return;
     if (!m_timer.isActive())
@@ -198,6 +204,10 @@
 
 void FontLoader::beginFontLoading(CSSFontFaceRule* rule)
 {
+    m_histogram.incrementCount();
+    if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
+        return;
+
     ++m_loadingCount;
     if (m_loadingCount == 1 && !m_pendingDoneEvent)
         scheduleEvent(CSSFontFaceLoadEvent::createForFontFaceRule(eventNames().loadingEvent, rule));
@@ -207,14 +217,18 @@
 
 void FontLoader::fontLoaded(CSSFontFaceRule* rule)
 {
+    if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
+        return;
     scheduleEvent(CSSFontFaceLoadEvent::createForFontFaceRule(eventNames().loadEvent, rule));
     queueDoneEvent(rule);
 }
 
 void FontLoader::loadError(CSSFontFaceRule* rule, CSSFontFaceSource* source)
 {
+    if (!RuntimeEnabledFeatures::fontLoadEventsEnabled())
+        return;
     // FIXME: We should report NetworkError in case of timeout, etc.
-    String errorName = (source && source->isDecodeError()) ? "InvalidFontDataError" : ExceptionCodeDescription(NOT_FOUND_ERR).name;
+    String errorName = (source && source->isDecodeError()) ? "InvalidFontDataError" : DOMException::getErrorName(NOT_FOUND_ERR);
     scheduleEvent(CSSFontFaceLoadEvent::createForError(rule, DOMError::create(errorName)));
     queueDoneEvent(rule);
 }
@@ -349,4 +363,12 @@
     return true;
 }
 
+void FontLoader::FontLoadHistogram::record()
+{
+    if (m_recorded)
+        return;
+    m_recorded = true;
+    HistogramSupport::histogramCustomCounts("WebFont.WebFontsInPage", m_count, 1, 100, 50);
+}
+
 } // namespace WebCore
diff --git a/Source/core/css/FontLoader.h b/Source/core/css/FontLoader.h
index 1e17800..b8e39d8 100644
--- a/Source/core/css/FontLoader.h
+++ b/Source/core/css/FontLoader.h
@@ -82,6 +82,17 @@
     void scheduleCallback(PassRefPtr<VoidCallback>);
 
 private:
+    class FontLoadHistogram {
+    public:
+        FontLoadHistogram() : m_count(0), m_recorded(false) { }
+        void incrementCount() { m_count++; }
+        void record();
+
+    private:
+        int m_count;
+        bool m_recorded;
+    };
+
     FontLoader(Document*);
 
     virtual void refEventTarget() { ref(); }
@@ -105,6 +116,7 @@
     Vector<RefPtr<VoidCallback> > m_fontsReadyCallbacks;
     RefPtr<Event> m_pendingDoneEvent;
     Timer<FontLoader> m_timer;
+    FontLoadHistogram m_histogram;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/FontSize.h b/Source/core/css/FontSize.h
index 3c309f3..bcc624e 100644
--- a/Source/core/css/FontSize.h
+++ b/Source/core/css/FontSize.h
@@ -22,8 +22,6 @@
 #ifndef FontSize_h
 #define FontSize_h
 
-#include "core/platform/graphics/FontDescription.h"
-
 namespace WebCore {
 
 class Document;
diff --git a/Source/core/css/InspectorCSSOMWrappers.cpp b/Source/core/css/InspectorCSSOMWrappers.cpp
index a84449a..fb1d485 100644
--- a/Source/core/css/InspectorCSSOMWrappers.cpp
+++ b/Source/core/css/InspectorCSSOMWrappers.cpp
@@ -41,8 +41,8 @@
 #include "core/css/StyleSheetContents.h"
 #include "core/dom/DocumentStyleSheetCollection.h"
 
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/MemoryInstrumentationHashSet.h>
+#include "wtf/MemoryInstrumentationHashMap.h"
+#include "wtf/MemoryInstrumentationHashSet.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/InspectorCSSOMWrappers.h b/Source/core/css/InspectorCSSOMWrappers.h
index bfe15d7..aca07f7 100644
--- a/Source/core/css/InspectorCSSOMWrappers.h
+++ b/Source/core/css/InspectorCSSOMWrappers.h
@@ -23,11 +23,10 @@
 #ifndef InspectorCSSOMWrappers_h
 #define InspectorCSSOMWrappers_h
 
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/HashSet.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/MediaList.cpp b/Source/core/css/MediaList.cpp
index 5d63f29..e746db2 100644
--- a/Source/core/css/MediaList.cpp
+++ b/Source/core/css/MediaList.cpp
@@ -55,13 +55,11 @@
  */
 
 MediaQuerySet::MediaQuerySet()
-    : m_lastLine(0)
 {
 }
 
 MediaQuerySet::MediaQuerySet(const MediaQuerySet& o)
     : RefCounted<MediaQuerySet>()
-    , m_lastLine(o.m_lastLine)
     , m_queries(o.m_queries.size())
 {
     for (unsigned i = 0; i < m_queries.size(); ++i)
diff --git a/Source/core/css/MediaList.h b/Source/core/css/MediaList.h
index 96b5af6..2702137 100644
--- a/Source/core/css/MediaList.h
+++ b/Source/core/css/MediaList.h
@@ -53,9 +53,6 @@
 
     const Vector<OwnPtr<MediaQuery> >& queryVector() const { return m_queries; }
 
-    int lastLine() const { return m_lastLine; }
-    void setLastLine(int lastLine) { m_lastLine = lastLine; }
-
     String mediaText() const;
 
     PassRefPtr<MediaQuerySet> copy() const { return adoptRef(new MediaQuerySet(*this)); }
@@ -66,7 +63,6 @@
     MediaQuerySet();
     MediaQuerySet(const MediaQuerySet&);
 
-    unsigned m_lastLine;
     Vector<OwnPtr<MediaQuery> > m_queries;
 };
 
diff --git a/Source/core/css/MediaQueryEvaluator.cpp b/Source/core/css/MediaQueryEvaluator.cpp
index f647c4b..68d654c 100644
--- a/Source/core/css/MediaQueryEvaluator.cpp
+++ b/Source/core/css/MediaQueryEvaluator.cpp
@@ -68,7 +68,7 @@
 {
 }
 
-MediaQueryEvaluator::MediaQueryEvaluator(const String& acceptedMediaType, bool mediaFeatureResult)
+MediaQueryEvaluator::MediaQueryEvaluator(const AtomicString& acceptedMediaType, bool mediaFeatureResult)
     : m_mediaType(acceptedMediaType)
     , m_frame(0)
     , m_style(0)
@@ -84,7 +84,7 @@
 {
 }
 
-MediaQueryEvaluator::MediaQueryEvaluator(const String& acceptedMediaType, Frame* frame, RenderStyle* style)
+MediaQueryEvaluator::MediaQueryEvaluator(const AtomicString& acceptedMediaType, Frame* frame, RenderStyle* style)
     : m_mediaType(acceptedMediaType)
     , m_frame(frame)
     , m_style(style)
@@ -96,7 +96,7 @@
 {
 }
 
-bool MediaQueryEvaluator::mediaTypeMatch(const String& mediaTypeToMatch) const
+bool MediaQueryEvaluator::mediaTypeMatch(const AtomicString& mediaTypeToMatch) const
 {
     return mediaTypeToMatch.isEmpty()
         || equalIgnoringCase(mediaTypeToMatch, "all")
@@ -108,7 +108,7 @@
     // Like mediaTypeMatch, but without the special cases for "" and "all".
     ASSERT(mediaTypeToMatch);
     ASSERT(mediaTypeToMatch[0] != '\0');
-    ASSERT(!equalIgnoringCase(mediaTypeToMatch, String("all")));
+    ASSERT(!equalIgnoringCase(mediaTypeToMatch, AtomicString("all")));
     return equalIgnoringCase(mediaTypeToMatch, m_mediaType);
 }
 
@@ -347,7 +347,7 @@
     }
 
     if (primitiveValue->isLength()) {
-        result = primitiveValue->computeLength<int>(style, rootStyle);
+        result = primitiveValue->computeLength<int>(style, rootStyle, 1.0 /* multiplier */, true /* computingFontSize */);
         return true;
     }
 
diff --git a/Source/core/css/MediaQueryEvaluator.h b/Source/core/css/MediaQueryEvaluator.h
index dec0c86..eb67ac7 100644
--- a/Source/core/css/MediaQueryEvaluator.h
+++ b/Source/core/css/MediaQueryEvaluator.h
@@ -62,15 +62,15 @@
      *  Evaluator  returns true for acceptedMediaType and returns value of \mediafeatureResult
      *  for any media features
      */
-    MediaQueryEvaluator(const String& acceptedMediaType, bool mediaFeatureResult = false);
+    MediaQueryEvaluator(const AtomicString& acceptedMediaType, bool mediaFeatureResult = false);
     MediaQueryEvaluator(const char* acceptedMediaType, bool mediaFeatureResult = false);
 
     /** Creates evaluator which evaluates full media queries */
-    MediaQueryEvaluator(const String& acceptedMediaType, Frame*, RenderStyle*);
+    MediaQueryEvaluator(const AtomicString& acceptedMediaType, Frame*, RenderStyle*);
 
     ~MediaQueryEvaluator();
 
-    bool mediaTypeMatch(const String& mediaTypeToMatch) const;
+    bool mediaTypeMatch(const AtomicString& mediaTypeToMatch) const;
     bool mediaTypeMatchSpecific(const char* mediaTypeToMatch) const;
 
     /** Evaluates a list of media queries */
@@ -80,7 +80,7 @@
     bool eval(const MediaQueryExp*) const;
 
 private:
-    String m_mediaType;
+    AtomicString m_mediaType;
     Frame* m_frame; // Not owned.
     RefPtr<RenderStyle> m_style;
     bool m_expResult;
diff --git a/Source/core/css/MediaQueryExp.cpp b/Source/core/css/MediaQueryExp.cpp
index d68df26..03a29f7 100644
--- a/Source/core/css/MediaQueryExp.cpp
+++ b/Source/core/css/MediaQueryExp.cpp
@@ -34,7 +34,6 @@
 #include "core/css/CSSAspectRatioValue.h"
 #include "core/css/CSSParser.h"
 #include "core/css/CSSPrimitiveValue.h"
-#include "core/css/CSSValueList.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "wtf/text/StringBuilder.h"
 
diff --git a/Source/core/css/MediaQueryListListener.h b/Source/core/css/MediaQueryListListener.h
index f1d4441..fccf99d 100644
--- a/Source/core/css/MediaQueryListListener.h
+++ b/Source/core/css/MediaQueryListListener.h
@@ -23,7 +23,6 @@
 #include "bindings/v8/ScriptState.h"
 #include "bindings/v8/ScriptValue.h"
 #include "wtf/RefCounted.h"
-#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/MediaQueryMatcher.cpp b/Source/core/css/MediaQueryMatcher.cpp
index 094341e..0d3e7c40 100644
--- a/Source/core/css/MediaQueryMatcher.cpp
+++ b/Source/core/css/MediaQueryMatcher.cpp
@@ -66,10 +66,10 @@
     m_document = 0;
 }
 
-String MediaQueryMatcher::mediaType() const
+AtomicString MediaQueryMatcher::mediaType() const
 {
     if (!m_document || !m_document->frame() || !m_document->frame()->view())
-        return String();
+        return nullAtom;
 
     return m_document->frame()->view()->mediaType();
 }
diff --git a/Source/core/css/MediaQueryMatcher.h b/Source/core/css/MediaQueryMatcher.h
index 6293f82..42945b4 100644
--- a/Source/core/css/MediaQueryMatcher.h
+++ b/Source/core/css/MediaQueryMatcher.h
@@ -71,7 +71,7 @@
 
     MediaQueryMatcher(Document*);
     PassOwnPtr<MediaQueryEvaluator> prepareEvaluator() const;
-    String mediaType() const;
+    AtomicString mediaType() const;
 
     Document* m_document;
     Vector<OwnPtr<Listener> > m_listeners;
diff --git a/Source/core/css/PageRuleCollector.cpp b/Source/core/css/PageRuleCollector.cpp
index b09d3a1..3caf4c0 100644
--- a/Source/core/css/PageRuleCollector.cpp
+++ b/Source/core/css/PageRuleCollector.cpp
@@ -71,6 +71,7 @@
     if (!rules)
         return;
 
+    rules->compactRulesIfNeeded();
     Vector<StyleRulePage*> matchedPageRules;
     matchPageRulesForList(matchedPageRules, rules->pageRules(), m_isLeftPage, m_isFirstPage, m_pageName);
     if (matchedPageRules.isEmpty())
diff --git a/Source/core/css/PageRuleCollector.h b/Source/core/css/PageRuleCollector.h
index 544ea38..4fd7dfd 100644
--- a/Source/core/css/PageRuleCollector.h
+++ b/Source/core/css/PageRuleCollector.h
@@ -22,10 +22,8 @@
 #ifndef PageRuleCollector_h
 #define PageRuleCollector_h
 
-#include "core/css/DocumentRuleSets.h"
 #include "core/css/resolver/StyleResolver.h"
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/PropertySetCSSStyleDeclaration.cpp b/Source/core/css/PropertySetCSSStyleDeclaration.cpp
index 356824f..e941cec 100644
--- a/Source/core/css/PropertySetCSSStyleDeclaration.cpp
+++ b/Source/core/css/PropertySetCSSStyleDeclaration.cpp
@@ -26,9 +26,9 @@
 #include "core/css/CSSParser.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/StylePropertySet.h"
+#include "core/dom/Element.h"
 #include "core/dom/MutationObserverInterestGroup.h"
 #include "core/dom/MutationRecord.h"
-#include "core/dom/StyledElement.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include <wtf/MemoryInstrumentationHashMap.h>
diff --git a/Source/core/css/PropertySetCSSStyleDeclaration.h b/Source/core/css/PropertySetCSSStyleDeclaration.h
index ea40793..96fabbe 100644
--- a/Source/core/css/PropertySetCSSStyleDeclaration.h
+++ b/Source/core/css/PropertySetCSSStyleDeclaration.h
@@ -36,13 +36,13 @@
 class CSSValue;
 class MutableStylePropertySet;
 class StyleSheetContents;
-class StyledElement;
+class Element;
 
 class PropertySetCSSStyleDeclaration : public CSSStyleDeclaration {
 public:
     PropertySetCSSStyleDeclaration(MutableStylePropertySet* propertySet) : m_propertySet(propertySet) { }
     
-    virtual StyledElement* parentElement() const { return 0; }
+    virtual Element* parentElement() const { return 0; }
     virtual void clearParentElement() { ASSERT_NOT_REACHED(); }
     StyleSheetContents* contextStyleSheet() const;
     
@@ -117,7 +117,7 @@
 class InlineCSSStyleDeclaration : public PropertySetCSSStyleDeclaration
 {
 public:
-    InlineCSSStyleDeclaration(MutableStylePropertySet* propertySet, StyledElement* parentElement)
+    InlineCSSStyleDeclaration(MutableStylePropertySet* propertySet, Element* parentElement)
         : PropertySetCSSStyleDeclaration(propertySet)
         , m_parentElement(parentElement) 
     {
@@ -127,12 +127,12 @@
     
 private:
     virtual CSSStyleSheet* parentStyleSheet() const OVERRIDE;
-    virtual StyledElement* parentElement() const OVERRIDE { return m_parentElement; }
+    virtual Element* parentElement() const OVERRIDE { return m_parentElement; }
     virtual void clearParentElement() OVERRIDE { m_parentElement = 0; }
 
     virtual void didMutate(MutationType) OVERRIDE;
 
-    StyledElement* m_parentElement;
+    Element* m_parentElement;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/RuleFeature.cpp b/Source/core/css/RuleFeature.cpp
index ea4ad36..29d233d 100644
--- a/Source/core/css/RuleFeature.cpp
+++ b/Source/core/css/RuleFeature.cpp
@@ -31,9 +31,8 @@
 
 #include "core/css/CSSSelector.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/MemoryInstrumentationHashSet.h>
-#include <wtf/MemoryInstrumentationVector.h>
+#include "wtf/MemoryInstrumentationHashSet.h"
+#include "wtf/MemoryInstrumentationVector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/RuleFeature.h b/Source/core/css/RuleFeature.h
index 0ffc6e5..1fd7a7c 100644
--- a/Source/core/css/RuleFeature.h
+++ b/Source/core/css/RuleFeature.h
@@ -22,10 +22,9 @@
 #ifndef RuleFeature_h
 #define RuleFeature_h
 
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/text/AtomicString.h>
+#include "wtf/Forward.h"
+#include "wtf/HashSet.h"
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/RuleSet.cpp b/Source/core/css/RuleSet.cpp
index d283692..7d81c94 100644
--- a/Source/core/css/RuleSet.cpp
+++ b/Source/core/css/RuleSet.cpp
@@ -29,9 +29,6 @@
 #include "config.h"
 #include "core/css/RuleSet.h"
 
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/MemoryInstrumentationHashSet.h>
-#include <wtf/MemoryInstrumentationVector.h>
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "core/css/CSSFontSelector.h"
@@ -47,9 +44,10 @@
 #include "core/css/StyleSheetContents.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include "weborigin/SecurityOrigin.h"
-
 #include "core/html/track/TextTrackCue.h"
+#include "weborigin/SecurityOrigin.h"
+#include "wtf/MemoryInstrumentationHashMap.h"
+#include "wtf/MemoryInstrumentationVector.h"
 
 namespace WebCore {
 
@@ -62,6 +60,11 @@
     return !scope || scope->isDocumentNode();
 }
 
+static inline bool isScopingNodeInShadowTree(const ContainerNode* scopingNode)
+{
+    return scopingNode && scopingNode->isInShadowTree();
+}
+
 static inline bool isSelectorMatchingHTMLBasedOnRuleHash(const CSSSelector* selector)
 {
     ASSERT(selector);
@@ -132,9 +135,80 @@
     return PropertyWhitelistNone;
 }
 
+namespace {
+
+// FIXME: Should we move this class to WTF?
+template<typename T>
+class TerminatedArrayBuilder {
+public:
+    explicit TerminatedArrayBuilder(PassOwnPtr<T> array)
+        : m_array(array)
+        , m_count(0)
+        , m_capacity(0)
+    {
+        if (!m_array)
+            return;
+        for (T* item = m_array.get(); !item->isLastInArray(); ++item)
+            ++m_count;
+        ++m_count; // To count the last item itself.
+        m_capacity = m_count;
+    }
+
+    void grow(size_t count)
+    {
+        ASSERT(count);
+        if (!m_array) {
+            ASSERT(!m_count);
+            ASSERT(!m_capacity);
+            m_capacity = count;
+            m_array = adoptPtr(static_cast<T*>(fastMalloc(m_capacity * sizeof(T))));
+            return;
+        }
+        m_capacity += count;
+        m_array = adoptPtr(static_cast<T*>(fastRealloc(m_array.leakPtr(), m_capacity * sizeof(T))));
+        m_array.get()[m_count - 1].setLastInArray(false);
+    }
+
+    void append(const T& item)
+    {
+        RELEASE_ASSERT(m_count < m_capacity);
+        ASSERT(!item.isLastInArray());
+        m_array.get()[m_count++] = item;
+    }
+
+    PassOwnPtr<T> release()
+    {
+        RELEASE_ASSERT(m_count == m_capacity);
+        if (m_array)
+            m_array.get()[m_count - 1].setLastInArray(true);
+        assertValid();
+        return m_array.release();
+    }
+
+private:
+#ifndef NDEBUG
+    void assertValid()
+    {
+        for (size_t i = 0; i < m_count; ++i) {
+            bool isLastInArray = (i + 1 == m_count);
+            ASSERT(m_array.get()[i].isLastInArray() == isLastInArray);
+        }
+    }
+#else
+    void assertValid() { }
+#endif
+
+    OwnPtr<T> m_array;
+    size_t m_count;
+    size_t m_capacity;
+};
+
+}
+
 RuleData::RuleData(StyleRule* rule, unsigned selectorIndex, unsigned position, AddRuleFlags addRuleFlags)
     : m_rule(rule)
     , m_selectorIndex(selectorIndex)
+    , m_isLastInArray(false)
     , m_position(position)
     , m_hasFastCheckableSelector((addRuleFlags & RuleCanUseFastCheckSelector) && SelectorCheckerFastPath::canUse(selector()))
     , m_specificity(selector()->specificity())
@@ -147,7 +221,6 @@
 {
     ASSERT(m_position == position);
     ASSERT(m_selectorIndex == selectorIndex);
-    SelectorFilter::collectIdentifierHashes(selector(), m_descendantSelectorIdentifierHashes, maximumIdentifierCount);
 }
 
 void RuleData::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
@@ -200,28 +273,28 @@
         features.uncommonAttributeRules.append(RuleFeature(ruleData.rule(), ruleData.selectorIndex(), ruleData.hasDocumentSecurityOrigin()));
 }
     
-void RuleSet::addToRuleSet(AtomicStringImpl* key, AtomRuleMap& map, const RuleData& ruleData)
+void RuleSet::addToRuleSet(AtomicStringImpl* key, PendingRuleMap& map, const RuleData& ruleData)
 {
     if (!key)
         return;
-    OwnPtr<Vector<RuleData> >& rules = map.add(key, nullptr).iterator->value;
+    OwnPtr<LinkedStack<RuleData> >& rules = map.add(key, nullptr).iterator->value;
     if (!rules)
-        rules = adoptPtr(new Vector<RuleData>);
-    rules->append(ruleData);
+        rules = adoptPtr(new LinkedStack<RuleData>);
+    rules->push(ruleData);
 }
 
 bool RuleSet::findBestRuleSetAndAdd(const CSSSelector* component, RuleData& ruleData)
 {
     if (component->m_match == CSSSelector::Id) {
-        addToRuleSet(component->value().impl(), m_idRules, ruleData);
+        addToRuleSet(component->value().impl(), ensurePendingRules()->idRules, ruleData);
         return true;
     }
     if (component->m_match == CSSSelector::Class) {
-        addToRuleSet(component->value().impl(), m_classRules, ruleData);
+        addToRuleSet(component->value().impl(), ensurePendingRules()->classRules, ruleData);
         return true;
     }
     if (component->isCustomPseudoElement()) {
-        addToRuleSet(component->value().impl(), m_shadowPseudoElementRules, ruleData);
+        addToRuleSet(component->value().impl(), ensurePendingRules()->shadowPseudoElementRules, ruleData);
         return true;
     }
     if (component->pseudoType() == CSSSelector::PseudoCue) {
@@ -252,7 +325,7 @@
                 && findBestRuleSetAndAdd(component->tagHistory(), ruleData))
                 return true;
 
-            addToRuleSet(component->tagQName().localName().impl(), m_tagRules, ruleData);
+            addToRuleSet(component->tagQName().localName().impl(), ensurePendingRules()->tagRules, ruleData);
             return true;
         }
     }
@@ -272,11 +345,13 @@
 
 void RuleSet::addPageRule(StyleRulePage* rule)
 {
+    ensurePendingRules(); // So that m_pageRules.shrinkToFit() gets called.
     m_pageRules.append(rule);
 }
 
 void RuleSet::addRegionRule(StyleRuleRegion* regionRule, bool hasDocumentSecurityOrigin)
 {
+    ensurePendingRules(); // So that m_regionSelectorsAndRuleSets.shrinkToFit() gets called.
     OwnPtr<RuleSet> regionRuleSet = RuleSet::create();
     // The region rule set should take into account the position inside the parent rule set.
     // Otherwise, the rules inside region block might be incorrectly positioned before other similar rules from
@@ -339,10 +414,14 @@
         else if (rule->isRegionRule() && resolver) {
             // FIXME (BUG 72472): We don't add @-webkit-region rules of scoped style sheets for the moment.
             addRegionRule(static_cast<StyleRuleRegion*>(rule), hasDocumentSecurityOrigin);
-        }
-        else if (rule->isHostRule())
+        } else if (rule->isHostRule() && resolver) {
+            if (!isScopingNodeInShadowTree(scope))
+                continue;
+            bool enabled = resolver->buildScopedStyleTreeInDocumentOrder();
+            resolver->setBuildScopedStyleTreeInDocumentOrder(false);
             resolver->ensureScopedStyleResolver(scope->shadowHost())->addHostRule(static_cast<StyleRuleHost*>(rule), hasDocumentSecurityOrigin, scope);
-        else if (RuntimeEnabledFeatures::cssViewportEnabled() && rule->isViewportRule() && resolver) {
+            resolver->setBuildScopedStyleTreeInDocumentOrder(enabled);
+        } else if (RuntimeEnabledFeatures::cssViewportEnabled() && rule->isViewportRule() && resolver) {
             // @viewport should not be scoped.
             if (!isDocumentScope(scope))
                 continue;
@@ -368,9 +447,6 @@
     AddRuleFlags addRuleFlags = static_cast<AddRuleFlags>((hasDocumentSecurityOrigin ? RuleHasDocumentSecurityOrigin : 0) | (!scope ? RuleCanUseFastCheckSelector : 0));
 
     addChildRules(sheet->childRules(), medium, resolver, scope, hasDocumentSecurityOrigin, addRuleFlags);
-
-    if (m_autoShrinkToFitEnabled)
-        shrinkToFit();
 }
 
 void RuleSet::addStyleRule(StyleRule* rule, AddRuleFlags addRuleFlags)
@@ -379,19 +455,32 @@
         addRule(rule, selectorIndex, addRuleFlags);
 }
 
-static inline void shrinkMapVectorsToFit(RuleSet::AtomRuleMap& map)
+void RuleSet::compactPendingRules(PendingRuleMap& pendingMap, CompactRuleMap& compactMap)
 {
-    RuleSet::AtomRuleMap::iterator end = map.end();
-    for (RuleSet::AtomRuleMap::iterator it = map.begin(); it != end; ++it)
-        it->value->shrinkToFit();
+    PendingRuleMap::iterator end = pendingMap.end();
+    for (PendingRuleMap::iterator it = pendingMap.begin(); it != end; ++it) {
+        OwnPtr<LinkedStack<RuleData> > pendingRules = it->value.release();
+        CompactRuleMap::iterator compactRules = compactMap.add(it->key, nullptr).iterator;
+
+        TerminatedArrayBuilder<RuleData> builder(compactRules->value.release());
+        builder.grow(pendingRules->size());
+        while (!pendingRules->isEmpty()) {
+            builder.append(pendingRules->peek());
+            pendingRules->pop();
+        }
+
+        compactRules->value = builder.release();
+    }
 }
 
-void RuleSet::shrinkToFit()
+void RuleSet::compactRules()
 {
-    shrinkMapVectorsToFit(m_idRules);
-    shrinkMapVectorsToFit(m_classRules);
-    shrinkMapVectorsToFit(m_tagRules);
-    shrinkMapVectorsToFit(m_shadowPseudoElementRules);
+    ASSERT(m_pendingRules);
+    OwnPtr<PendingRuleMaps> pendingRules = m_pendingRules.release();
+    compactPendingRules(pendingRules->idRules, m_idRules);
+    compactPendingRules(pendingRules->classRules, m_classRules);
+    compactPendingRules(pendingRules->tagRules, m_tagRules);
+    compactPendingRules(pendingRules->shadowPseudoElementRules, m_shadowPseudoElementRules);
     m_linkPseudoClassRules.shrinkToFit();
     m_cuePseudoRules.shrinkToFit();
     m_focusPseudoClassRules.shrinkToFit();
diff --git a/Source/core/css/RuleSet.h b/Source/core/css/RuleSet.h
index 82c3103..bddf7df 100644
--- a/Source/core/css/RuleSet.h
+++ b/Source/core/css/RuleSet.h
@@ -24,10 +24,9 @@
 
 #include "core/css/RuleFeature.h"
 #include "core/css/StyleRule.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/text/AtomicString.h>
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/LinkedStack.h"
 
 namespace WebCore {
 
@@ -52,6 +51,7 @@
 class StyleSheetContents;
 
 class RuleData {
+    NEW_DELETE_SAME_AS_MALLOC_FREE;
 public:
     RuleData(StyleRule*, unsigned selectorIndex, unsigned position, AddRuleFlags);
 
@@ -60,6 +60,9 @@
     const CSSSelector* selector() const { return m_rule->selectorList().selectorAt(m_selectorIndex); }
     unsigned selectorIndex() const { return m_selectorIndex; }
 
+    bool isLastInArray() const { return m_isLastInArray; }
+    void setLastInArray(bool flag) { m_isLastInArray = flag; }
+
     bool hasFastCheckableSelector() const { return m_hasFastCheckableSelector; }
     bool hasMultipartSelector() const { return m_hasMultipartSelector; }
     bool hasRightmostSelectorMatchingHTMLBasedOnRuleHash() const { return m_hasRightmostSelectorMatchingHTMLBasedOnRuleHash; }
@@ -68,15 +71,13 @@
     unsigned linkMatchType() const { return m_linkMatchType; }
     bool hasDocumentSecurityOrigin() const { return m_hasDocumentSecurityOrigin; }
     PropertyWhitelistType propertyWhitelistType(bool isMatchingUARules = false) const { return isMatchingUARules ? PropertyWhitelistNone : static_cast<PropertyWhitelistType>(m_propertyWhitelistType); }
-    // Try to balance between memory usage (there can be lots of RuleData objects) and good filtering performance.
-    static const unsigned maximumIdentifierCount = 4;
-    const unsigned* descendantSelectorIdentifierHashes() const { return m_descendantSelectorIdentifierHashes; }
 
     void reportMemoryUsage(MemoryObjectInfo*) const;
 
 private:
     StyleRule* m_rule;
-    unsigned m_selectorIndex : 13;
+    unsigned m_selectorIndex : 12;
+    unsigned m_isLastInArray : 1; // We store an array of RuleData objects in a primitive array.
     // This number was picked fairly arbitrarily. We can probably lower it if we need to.
     // Some simple testing showed <100,000 RuleData's on large sites.
     unsigned m_position : 18;
@@ -88,15 +89,12 @@
     unsigned m_linkMatchType : 2; //  SelectorChecker::LinkMatchMask
     unsigned m_hasDocumentSecurityOrigin : 1;
     unsigned m_propertyWhitelistType : 2;
-    // Use plain array instead of a Vector to minimize memory overhead.
-    unsigned m_descendantSelectorIdentifierHashes[maximumIdentifierCount];
 };
     
 struct SameSizeAsRuleData {
     void* a;
     unsigned b;
     unsigned c;
-    unsigned d[4];
 };
 
 COMPILE_ASSERT(sizeof(RuleData) == sizeof(SameSizeAsRuleData), RuleData_should_stay_small);
@@ -106,52 +104,33 @@
 public:
     static PassOwnPtr<RuleSet> create() { return adoptPtr(new RuleSet); }
 
-    typedef HashMap<AtomicStringImpl*, OwnPtr<Vector<RuleData> > > AtomRuleMap;
-
     void addRulesFromSheet(StyleSheetContents*, const MediaQueryEvaluator&, StyleResolver* = 0, const ContainerNode* = 0);
-
     void addStyleRule(StyleRule*, AddRuleFlags);
     void addRule(StyleRule*, unsigned selectorIndex, AddRuleFlags);
-    void addPageRule(StyleRulePage*);
-    void addToRuleSet(AtomicStringImpl* key, AtomRuleMap&, const RuleData&);
-    void addRegionRule(StyleRuleRegion*, bool hasDocumentSecurityOrigin);
-    void shrinkToFit();
-    void disableAutoShrinkToFit() { m_autoShrinkToFitEnabled = false; }
 
     const RuleFeatureSet& features() const { return m_features; }
 
-    const Vector<RuleData>* idRules(AtomicStringImpl* key) const { return m_idRules.get(key); }
-    const Vector<RuleData>* classRules(AtomicStringImpl* key) const { return m_classRules.get(key); }
-    const Vector<RuleData>* tagRules(AtomicStringImpl* key) const { return m_tagRules.get(key); }
-    const Vector<RuleData>* shadowPseudoElementRules(AtomicStringImpl* key) const { return m_shadowPseudoElementRules.get(key); }
-    const Vector<RuleData>* linkPseudoClassRules() const { return &m_linkPseudoClassRules; }
-    const Vector<RuleData>* cuePseudoRules() const { return &m_cuePseudoRules; }
-    const Vector<RuleData>* focusPseudoClassRules() const { return &m_focusPseudoClassRules; }
-    const Vector<RuleData>* universalRules() const { return &m_universalRules; }
-    const Vector<StyleRulePage*>& pageRules() const { return m_pageRules; }
+    const RuleData* idRules(AtomicStringImpl* key) const { ASSERT(!m_pendingRules); return m_idRules.get(key); }
+    const RuleData* classRules(AtomicStringImpl* key) const { ASSERT(!m_pendingRules); return m_classRules.get(key); }
+    const RuleData* tagRules(AtomicStringImpl* key) const { ASSERT(!m_pendingRules); return m_tagRules.get(key); }
+    const RuleData* shadowPseudoElementRules(AtomicStringImpl* key) const { ASSERT(!m_pendingRules); return m_shadowPseudoElementRules.get(key); }
+    const Vector<RuleData>* linkPseudoClassRules() const { ASSERT(!m_pendingRules); return &m_linkPseudoClassRules; }
+    const Vector<RuleData>* cuePseudoRules() const { ASSERT(!m_pendingRules); return &m_cuePseudoRules; }
+    const Vector<RuleData>* focusPseudoClassRules() const { ASSERT(!m_pendingRules); return &m_focusPseudoClassRules; }
+    const Vector<RuleData>* universalRules() const { ASSERT(!m_pendingRules); return &m_universalRules; }
+    const Vector<StyleRulePage*>& pageRules() const { ASSERT(!m_pendingRules); return m_pageRules; }
+
+    unsigned ruleCount() const { return m_ruleCount; }
+
+    void compactRulesIfNeeded()
+    {
+        if (!m_pendingRules)
+            return;
+        compactRules();
+    }
 
     void reportMemoryUsage(MemoryObjectInfo*) const;
 
-private:
-    void addChildRules(const Vector<RefPtr<StyleRuleBase> >&, const MediaQueryEvaluator& medium, StyleResolver*, const ContainerNode* scope, bool hasDocumentSecurityOrigin, AddRuleFlags);
-    bool findBestRuleSetAndAdd(const CSSSelector*, RuleData&);
-
-public:
-    RuleSet();
-
-    AtomRuleMap m_idRules;
-    AtomRuleMap m_classRules;
-    AtomRuleMap m_tagRules;
-    AtomRuleMap m_shadowPseudoElementRules;
-    Vector<RuleData> m_linkPseudoClassRules;
-    Vector<RuleData> m_cuePseudoRules;
-    Vector<RuleData> m_focusPseudoClassRules;
-    Vector<RuleData> m_universalRules;
-    Vector<StyleRulePage*> m_pageRules;
-    unsigned m_ruleCount;
-    bool m_autoShrinkToFitEnabled;
-    RuleFeatureSet m_features;
-
     struct RuleSetSelectorPair {
         RuleSetSelectorPair(const CSSSelector* selector, PassOwnPtr<RuleSet> ruleSet) : selector(selector), ruleSet(ruleSet) { }
         RuleSetSelectorPair(const RuleSetSelectorPair& rs) : selector(rs.selector), ruleSet(const_cast<RuleSetSelectorPair*>(&rs)->ruleSet.release()) { }
@@ -162,13 +141,54 @@
     };
 
     Vector<RuleSetSelectorPair> m_regionSelectorsAndRuleSets;
-};
 
-inline RuleSet::RuleSet()
-    : m_ruleCount(0)
-    , m_autoShrinkToFitEnabled(true)
-{
-}
+private:
+    typedef HashMap<AtomicStringImpl*, OwnPtr<LinkedStack<RuleData> > > PendingRuleMap;
+    typedef HashMap<AtomicStringImpl*, OwnPtr<RuleData> > CompactRuleMap;
+
+    RuleSet()
+        : m_ruleCount(0)
+    {
+    }
+
+    void addToRuleSet(AtomicStringImpl* key, PendingRuleMap&, const RuleData&);
+    void addPageRule(StyleRulePage*);
+    void addRegionRule(StyleRuleRegion*, bool hasDocumentSecurityOrigin);
+
+    void addChildRules(const Vector<RefPtr<StyleRuleBase> >&, const MediaQueryEvaluator& medium, StyleResolver*, const ContainerNode* scope, bool hasDocumentSecurityOrigin, AddRuleFlags);
+    bool findBestRuleSetAndAdd(const CSSSelector*, RuleData&);
+
+    void compactRules();
+    static void compactPendingRules(PendingRuleMap&, CompactRuleMap&);
+
+    struct PendingRuleMaps {
+        PendingRuleMap idRules;
+        PendingRuleMap classRules;
+        PendingRuleMap tagRules;
+        PendingRuleMap shadowPseudoElementRules;
+    };
+
+    PendingRuleMaps* ensurePendingRules()
+    {
+        if (!m_pendingRules)
+            m_pendingRules = adoptPtr(new PendingRuleMaps);
+        return m_pendingRules.get();
+    }
+
+    CompactRuleMap m_idRules;
+    CompactRuleMap m_classRules;
+    CompactRuleMap m_tagRules;
+    CompactRuleMap m_shadowPseudoElementRules;
+    Vector<RuleData> m_linkPseudoClassRules;
+    Vector<RuleData> m_cuePseudoRules;
+    Vector<RuleData> m_focusPseudoClassRules;
+    Vector<RuleData> m_universalRules;
+    RuleFeatureSet m_features;
+    Vector<StyleRulePage*> m_pageRules;
+
+    unsigned m_ruleCount;
+    OwnPtr<PendingRuleMaps> m_pendingRules;
+};
 
 } // namespace WebCore
 
diff --git a/Source/core/css/SVGCSSStyleSelector.cpp b/Source/core/css/SVGCSSStyleSelector.cpp
index 912ddd9..3fb1bc7 100644
--- a/Source/core/css/SVGCSSStyleSelector.cpp
+++ b/Source/core/css/SVGCSSStyleSelector.cpp
@@ -30,7 +30,6 @@
 
 #include "core/css/resolver/StyleResolver.h"
 
-#include <stdlib.h>
 #include "CSSPropertyNames.h"
 #include "core/css/CSSPrimitiveValueMappings.h"
 #include "core/css/CSSValueList.h"
@@ -40,7 +39,7 @@
 #include "core/svg/SVGColor.h"
 #include "core/svg/SVGPaint.h"
 #include "core/svg/SVGURIReference.h"
-#include <wtf/MathExtras.h>
+#include "wtf/MathExtras.h"
 
 #define HANDLE_INHERIT(prop, Prop) \
 if (isInherit) \
@@ -566,7 +565,7 @@
             int blur = item->blur ? item->blur->computeLength<int>(state.style(), state.rootElementStyle()) : 0;
             Color color;
             if (item->color)
-                color = colorFromPrimitiveValue(item->color.get());
+                color = resolveColorFromPrimitiveValue(item->color.get());
 
             // -webkit-svg-shadow does should not have a spread or style
             ASSERT(!item->spread);
diff --git a/Source/core/css/SelectorChecker.cpp b/Source/core/css/SelectorChecker.cpp
index fb1a811..56757a9 100644
--- a/Source/core/css/SelectorChecker.cpp
+++ b/Source/core/css/SelectorChecker.cpp
@@ -33,9 +33,9 @@
 #include "core/css/CSSSelectorList.h"
 #include "core/css/SiblingTraversalStrategies.h"
 #include "core/dom/Document.h"
+#include "core/dom/Element.h"
 #include "core/dom/FullscreenController.h"
 #include "core/dom/NodeRenderStyle.h"
-#include "core/dom/StyledElement.h"
 #include "core/dom/Text.h"
 #include "core/dom/shadow/InsertionPoint.h"
 #include "core/dom/shadow/ShadowRoot.h"
@@ -340,7 +340,7 @@
         return SelectorChecker::tagMatches(element, selector->tagQName());
 
     if (selector->m_match == CSSSelector::Class)
-        return element->hasClass() && static_cast<StyledElement*>(element)->classNames().contains(selector->value());
+        return element->hasClass() && element->classNames().contains(selector->value());
 
     if (selector->m_match == CSSSelector::Id)
         return element->hasID() && element->idForStyleResolution() == selector->value();
@@ -688,7 +688,7 @@
             // element is an element in the document, the 'full-screen' pseudoclass applies to
             // that element. Also, an <iframe>, <object> or <embed> element whose child browsing
             // context's Document is in the fullscreen state has the 'full-screen' pseudoclass applied.
-            if (element->isFrameElementBase() && static_cast<HTMLFrameElementBase*>(element)->containsFullScreenElement())
+            if (element->isFrameElementBase() && element->containsFullScreenElement())
                 return true;
             if (FullscreenController* fullscreen = FullscreenController::fromIfExists(element->document())) {
                 if (!fullscreen->webkitIsFullScreen())
@@ -696,13 +696,6 @@
                 return element == fullscreen->webkitCurrentFullScreenElement();
             }
             return false;
-        case CSSSelector::PseudoAnimatingFullScreenTransition:
-            if (FullscreenController* fullscreen = FullscreenController::fromIfExists(element->document())) {
-                if (!fullscreen->isAnimatingFullScreen())
-                    return false;
-                return element == fullscreen->webkitCurrentFullScreenElement();
-            }
-            return false;
         case CSSSelector::PseudoFullScreenAncestor:
             return element->containsFullScreenElement();
         case CSSSelector::PseudoFullScreenDocument:
diff --git a/Source/core/css/SelectorChecker.h b/Source/core/css/SelectorChecker.h
index 2b192e7..c1f7fd1 100644
--- a/Source/core/css/SelectorChecker.h
+++ b/Source/core/css/SelectorChecker.h
@@ -29,10 +29,7 @@
 #define SelectorChecker_h
 
 #include "core/css/CSSSelector.h"
-#include "core/dom/SpaceSplitString.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include <wtf/HashSet.h>
-#include <wtf/Vector.h>
 
 namespace WebCore {
 
diff --git a/Source/core/css/SelectorCheckerFastPath.cpp b/Source/core/css/SelectorCheckerFastPath.cpp
index daf7449..7c8fecb 100644
--- a/Source/core/css/SelectorCheckerFastPath.cpp
+++ b/Source/core/css/SelectorCheckerFastPath.cpp
@@ -30,7 +30,7 @@
 #include "core/css/SelectorCheckerFastPath.h"
 
 #include "HTMLNames.h"
-#include "core/dom/StyledElement.h"
+#include "core/dom/Element.h"
 #include "core/html/HTMLDocument.h"
 
 namespace WebCore {
@@ -75,7 +75,7 @@
 
 inline bool checkClassValue(const Element* element, const CSSSelector* selector)
 {
-    return element->hasClass() && static_cast<const StyledElement*>(element)->classNames().contains(selector->value().impl());
+    return element->hasClass() && element->classNames().contains(selector->value().impl());
 }
 
 inline bool checkIDValue(const Element* element, const CSSSelector* selector)
diff --git a/Source/core/css/SelectorFilter.cpp b/Source/core/css/SelectorFilter.cpp
index 632a7ec..239bc45 100644
--- a/Source/core/css/SelectorFilter.cpp
+++ b/Source/core/css/SelectorFilter.cpp
@@ -30,7 +30,7 @@
 #include "core/css/SelectorFilter.h"
 
 #include "core/css/CSSSelector.h"
-#include "core/dom/StyledElement.h"
+#include "core/dom/Element.h"
 
 namespace WebCore {
 
@@ -42,9 +42,8 @@
     identifierHashes.append(element->localName().impl()->existingHash() * TagNameSalt);
     if (element->hasID())
         identifierHashes.append(element->idForStyleResolution().impl()->existingHash() * IdAttributeSalt);
-    const StyledElement* styledElement = element->isStyledElement() ? static_cast<const StyledElement*>(element) : 0;
-    if (styledElement && styledElement->hasClass()) {
-        const SpaceSplitString& classNames = styledElement->classNames();
+    if (element->isStyledElement() && element->hasClass()) {
+        const SpaceSplitString& classNames = element->classNames();
         size_t count = classNames.size();
         for (size_t i = 0; i < count; ++i)
             identifierHashes.append(classNames[i].impl()->existingHash() * ClassAttributeSalt);
@@ -110,30 +109,36 @@
     pushParentStackFrame(parent);
 }
 
-static inline void collectDescendantSelectorIdentifierHashes(const CSSSelector* selector, unsigned*& hash)
+static unsigned selectorIdentifierHash(const CSSSelector* selector)
 {
     switch (selector->m_match) {
     case CSSSelector::Id:
         if (!selector->value().isEmpty())
-            (*hash++) = selector->value().impl()->existingHash() * IdAttributeSalt;
+            return selector->value().impl()->existingHash() * IdAttributeSalt;
         break;
     case CSSSelector::Class:
         if (!selector->value().isEmpty())
-            (*hash++) = selector->value().impl()->existingHash() * ClassAttributeSalt;
+            return selector->value().impl()->existingHash() * ClassAttributeSalt;
         break;
     case CSSSelector::Tag:
         if (selector->tagQName().localName() != starAtom)
-            (*hash++) = selector->tagQName().localName().impl()->existingHash() * TagNameSalt;
+            return selector->tagQName().localName().impl()->existingHash() * TagNameSalt;
         break;
     default:
         break;
     }
+    return 0;
 }
 
-void SelectorFilter::collectIdentifierHashes(const CSSSelector* selector, unsigned* identifierHashes, unsigned maximumIdentifierCount)
+bool SelectorFilter::fastRejectSelector(const CSSSelector* selector) const
 {
-    unsigned* hash = identifierHashes;
-    unsigned* end = identifierHashes + maximumIdentifierCount;
+    ASSERT(m_ancestorIdentifierFilter);
+
+    // FIXME: Tune this parameter. This parameter was originally selected when
+    // we materialized the selector identifier hashes in RuleData objects,
+    // which meant that increasing increased memory usage.
+    size_t remainingHashesToCheck = 4;
+
     CSSSelector::Relation relation = selector->relation();
     bool relationIsForShadowDistributed = selector->relationIsForShadowDistributed();
 
@@ -143,8 +148,14 @@
         // Only collect identifiers that match ancestors.
         switch (relation) {
         case CSSSelector::SubSelector:
-            if (!skipOverSubselectors)
-                collectDescendantSelectorIdentifierHashes(selector, hash);
+            if (!skipOverSubselectors) {
+                if (unsigned hash = selectorIdentifierHash(selector)) {
+                    if (!m_ancestorIdentifierFilter->mayContain(hash))
+                        return true;
+                    if (!--remainingHashesToCheck)
+                        return false;
+                }
+            }
             break;
         case CSSSelector::DirectAdjacent:
         case CSSSelector::IndirectAdjacent:
@@ -158,15 +169,20 @@
                 break;
             }
             skipOverSubselectors = false;
-            collectDescendantSelectorIdentifierHashes(selector, hash);
+            if (unsigned hash = selectorIdentifierHash(selector)) {
+                if (!m_ancestorIdentifierFilter->mayContain(hash))
+                    return true;
+                if (!--remainingHashesToCheck)
+                    return false;
+            }
             break;
         }
-        if (hash == end)
-            return;
+
         relation = selector->relation();
         relationIsForShadowDistributed = selector->relationIsForShadowDistributed();
     }
-    *hash = 0;
+
+    return false;
 }
 
 }
diff --git a/Source/core/css/SelectorFilter.h b/Source/core/css/SelectorFilter.h
index 4025ca3..2e44252 100644
--- a/Source/core/css/SelectorFilter.h
+++ b/Source/core/css/SelectorFilter.h
@@ -48,9 +48,7 @@
     bool parentStackIsEmpty() const { return m_parentStack.isEmpty(); }
     bool parentStackIsConsistent(const ContainerNode* parentNode) const { return !m_parentStack.isEmpty() && m_parentStack.last().element == parentNode; }
 
-    template <unsigned maximumIdentifierCount>
-    inline bool fastRejectSelector(const unsigned* identifierHashes) const;
-    static void collectIdentifierHashes(const CSSSelector*, unsigned* identifierHashes, unsigned maximumIdentifierCount);
+    bool fastRejectSelector(const CSSSelector*) const;
 
 private:
     struct ParentStackFrame {
@@ -66,17 +64,6 @@
     OwnPtr<BloomFilter<bloomFilterKeyBits> > m_ancestorIdentifierFilter;
 };
 
-template <unsigned maximumIdentifierCount>
-inline bool SelectorFilter::fastRejectSelector(const unsigned* identifierHashes) const
-{
-    ASSERT(m_ancestorIdentifierFilter);
-    for (unsigned n = 0; n < maximumIdentifierCount && identifierHashes[n]; ++n) {
-        if (!m_ancestorIdentifierFilter->mayContain(identifierHashes[n]))
-            return true;
-    }
-    return false;
-}
-
 }
 
 #endif
diff --git a/Source/core/css/StyleInvalidationAnalysis.cpp b/Source/core/css/StyleInvalidationAnalysis.cpp
index b0ef035..47ce49a 100644
--- a/Source/core/css/StyleInvalidationAnalysis.cpp
+++ b/Source/core/css/StyleInvalidationAnalysis.cpp
@@ -119,7 +119,7 @@
     }
     if (styleSheetContents->hasSingleOwnerNode()) {
         Node* ownerNode = styleSheetContents->singleOwnerNode();
-        if (ownerNode && isHTMLStyleElement(ownerNode) && toHTMLStyleElement(ownerNode)->isRegisteredAsScoped()) {
+        if (ownerNode && ownerNode->hasTagName(HTMLNames::styleTag) && toHTMLStyleElement(ownerNode)->isRegisteredAsScoped()) {
             m_scopingNodes.append(determineScopingNodeForStyleScoped(toHTMLStyleElement(ownerNode), styleSheetContents));
             return;
         }
diff --git a/Source/core/css/StyleInvalidationAnalysis.h b/Source/core/css/StyleInvalidationAnalysis.h
index 5e2c4b9..18dad9f 100644
--- a/Source/core/css/StyleInvalidationAnalysis.h
+++ b/Source/core/css/StyleInvalidationAnalysis.h
@@ -26,10 +26,9 @@
 #ifndef StyleInvalidationAnalysis_h
 #define StyleInvalidationAnalysis_h
 
-#include <wtf/HashSet.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/Vector.h>
-#include <wtf/text/AtomicStringImpl.h>
+#include "wtf/HashSet.h"
+#include "wtf/Vector.h"
+#include "wtf/text/AtomicStringImpl.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/StylePropertySerializer.cpp b/Source/core/css/StylePropertySerializer.cpp
index c132da4..3e2135c 100644
--- a/Source/core/css/StylePropertySerializer.cpp
+++ b/Source/core/css/StylePropertySerializer.cpp
@@ -86,6 +86,10 @@
         case CSSPropertyBackgroundRepeatY:
             repeatYPropertyIndex = n;
             continue;
+        case CSSPropertyContent:
+            if (property.value()->isValueList())
+                value = toCSSValueList(property.value())->customCssText(AlwaysQuoteCSSString);
+            break;
         case CSSPropertyBorderTopWidth:
         case CSSPropertyBorderRightWidth:
         case CSSPropertyBorderBottomWidth:
@@ -170,14 +174,14 @@
         case CSSPropertyWebkitAnimationFillMode:
             shorthandPropertyID = CSSPropertyWebkitAnimation;
             break;
-        case CSSPropertyWebkitFlexDirection:
-        case CSSPropertyWebkitFlexWrap:
-            shorthandPropertyID = CSSPropertyWebkitFlexFlow;
+        case CSSPropertyFlexDirection:
+        case CSSPropertyFlexWrap:
+            shorthandPropertyID = CSSPropertyFlexFlow;
             break;
-        case CSSPropertyWebkitFlexBasis:
-        case CSSPropertyWebkitFlexGrow:
-        case CSSPropertyWebkitFlexShrink:
-            shorthandPropertyID = CSSPropertyWebkitFlex;
+        case CSSPropertyFlexBasis:
+        case CSSPropertyFlexGrow:
+        case CSSPropertyFlexShrink:
+            shorthandPropertyID = CSSPropertyFlex;
             break;
         case CSSPropertyWebkitMaskPositionX:
         case CSSPropertyWebkitMaskPositionY:
@@ -215,8 +219,10 @@
         }
 
         if (!value.isNull()) {
-            propertyID = shorthandPropertyID;
-            shorthandPropertyUsed.set(shortPropertyIndex);
+            if (shorthandPropertyID) {
+                propertyID = shorthandPropertyID;
+                shorthandPropertyUsed.set(shortPropertyIndex);
+            }
         } else
             value = property.value()->cssText();
 
@@ -336,10 +342,10 @@
         return getShorthandValue(webkitColumnRuleShorthand());
     case CSSPropertyWebkitColumns:
         return getShorthandValue(webkitColumnsShorthand());
-    case CSSPropertyWebkitFlex:
-        return getShorthandValue(webkitFlexShorthand());
-    case CSSPropertyWebkitFlexFlow:
-        return getShorthandValue(webkitFlexFlowShorthand());
+    case CSSPropertyFlex:
+        return getShorthandValue(flexShorthand());
+    case CSSPropertyFlexFlow:
+        return getShorthandValue(flexFlowShorthand());
     case CSSPropertyGridColumn:
         return getShorthandValue(gridColumnShorthand());
     case CSSPropertyGridRow:
diff --git a/Source/core/css/StylePropertySerializer.h b/Source/core/css/StylePropertySerializer.h
index e15d1a2..55d1027 100644
--- a/Source/core/css/StylePropertySerializer.h
+++ b/Source/core/css/StylePropertySerializer.h
@@ -23,11 +23,8 @@
 #ifndef StylePropertySerializer_h
 #define StylePropertySerializer_h
 
-#include "core/css/CSSValue.h"
 #include "core/css/CSSValueList.h"
 #include "core/css/StylePropertySet.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
 
 namespace WebCore {
 
diff --git a/Source/core/css/StylePropertySet.cpp b/Source/core/css/StylePropertySet.cpp
index 352e0ee..8146755 100644
--- a/Source/core/css/StylePropertySet.cpp
+++ b/Source/core/css/StylePropertySet.cpp
@@ -30,14 +30,12 @@
 #include "core/css/StylePropertyShorthand.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/page/RuntimeCSSEnabled.h"
-#include <wtf/BitArray.h>
-#include <wtf/MemoryInstrumentationVector.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/MemoryInstrumentationVector.h"
+#include "wtf/text/StringBuilder.h"
 
 #ifndef NDEBUG
+#include "wtf/text/CString.h"
 #include <stdio.h>
-#include <wtf/ASCIICType.h>
-#include <wtf/text/CString.h>
 #endif
 
 using namespace std;
@@ -535,7 +533,7 @@
     return cssomWrapper;
 }
 
-CSSStyleDeclaration* MutableStylePropertySet::ensureInlineCSSStyleDeclaration(StyledElement* parentElement)
+CSSStyleDeclaration* MutableStylePropertySet::ensureInlineCSSStyleDeclaration(Element* parentElement)
 {
     if (m_ownsCSSOMWrapper) {
         ASSERT(propertySetCSSOMWrapperMap().get(this)->parentElement() == parentElement);
@@ -594,7 +592,7 @@
         ASSERT(propertyValue()->isVariableValue());
         if (!propertyValue()->isVariableValue())
             return emptyString(); // Should not happen, but if it does, avoid a bad cast.
-        return "-webkit-var-" + static_cast<const CSSVariableValue*>(propertyValue())->name();
+        return "var-" + static_cast<const CSSVariableValue*>(propertyValue())->name();
     }
     return getPropertyNameString(id());
 }
diff --git a/Source/core/css/StylePropertySet.h b/Source/core/css/StylePropertySet.h
index 7d40b49..3fed430 100644
--- a/Source/core/css/StylePropertySet.h
+++ b/Source/core/css/StylePropertySet.h
@@ -33,11 +33,11 @@
 
 class CSSRule;
 class CSSStyleDeclaration;
+class Element;
 class ImmutableStylePropertySet;
 class KURL;
 class MutableStylePropertySet;
 class PropertySetCSSStyleDeclaration;
-class StyledElement;
 class StylePropertyShorthand;
 class StyleSheetContents;
 
@@ -211,7 +211,7 @@
     void parseDeclaration(const String& styleDeclaration, StyleSheetContents* contextStyleSheet);
 
     CSSStyleDeclaration* ensureCSSStyleDeclaration();
-    CSSStyleDeclaration* ensureInlineCSSStyleDeclaration(StyledElement* parentElement);
+    CSSStyleDeclaration* ensureInlineCSSStyleDeclaration(Element* parentElement);
 
     Vector<CSSProperty, 4> m_propertyVector;
 
diff --git a/Source/core/css/StylePropertyShorthand.cpp b/Source/core/css/StylePropertyShorthand.cpp
index 8d0de73..6e6512f 100644
--- a/Source/core/css/StylePropertyShorthand.cpp
+++ b/Source/core/css/StylePropertyShorthand.cpp
@@ -369,18 +369,18 @@
     return webkitColumnRuleLonghands;
 }
 
-const StylePropertyShorthand& webkitFlexFlowShorthand()
+const StylePropertyShorthand& flexFlowShorthand()
 {
-    static const CSSPropertyID flexFlowProperties[] = { CSSPropertyWebkitFlexDirection, CSSPropertyWebkitFlexWrap };
-    DEFINE_STATIC_LOCAL(StylePropertyShorthand, webkitFlexFlowLonghands, (CSSPropertyWebkitFlexFlow, flexFlowProperties, WTF_ARRAY_LENGTH(flexFlowProperties)));
-    return webkitFlexFlowLonghands;
+    static const CSSPropertyID flexFlowProperties[] = { CSSPropertyFlexDirection, CSSPropertyFlexWrap };
+    DEFINE_STATIC_LOCAL(StylePropertyShorthand, flexFlowLonghands, (CSSPropertyFlexFlow, flexFlowProperties, WTF_ARRAY_LENGTH(flexFlowProperties)));
+    return flexFlowLonghands;
 }
 
-const StylePropertyShorthand& webkitFlexShorthand()
+const StylePropertyShorthand& flexShorthand()
 {
-    static const CSSPropertyID flexProperties[] = { CSSPropertyWebkitFlexGrow, CSSPropertyWebkitFlexShrink, CSSPropertyWebkitFlexBasis };
-    DEFINE_STATIC_LOCAL(StylePropertyShorthand, webkitFlexLonghands, (CSSPropertyWebkitFlex, flexProperties, WTF_ARRAY_LENGTH(flexProperties)));
-    return webkitFlexLonghands;
+    static const CSSPropertyID flexProperties[] = { CSSPropertyFlexGrow, CSSPropertyFlexShrink, CSSPropertyFlexBasis };
+    DEFINE_STATIC_LOCAL(StylePropertyShorthand, flexLonghands, (CSSPropertyFlex, flexProperties, WTF_ARRAY_LENGTH(flexProperties)));
+    return flexLonghands;
 }
 
 const StylePropertyShorthand& webkitMarginCollapseShorthand()
@@ -393,8 +393,8 @@
 const StylePropertyShorthand& gridColumnShorthand()
 {
     static const CSSPropertyID gridColumnProperties[] = {
-        CSSPropertyGridStart,
-        CSSPropertyGridEnd
+        CSSPropertyGridColumnStart,
+        CSSPropertyGridColumnEnd
     };
     DEFINE_STATIC_LOCAL(StylePropertyShorthand, gridColumnLonghands, (CSSPropertyGridColumn, gridColumnProperties, WTF_ARRAY_LENGTH(gridColumnProperties)));
     return gridColumnLonghands;
@@ -403,8 +403,8 @@
 const StylePropertyShorthand& gridRowShorthand()
 {
     static const CSSPropertyID gridRowProperties[] = {
-        CSSPropertyGridBefore,
-        CSSPropertyGridAfter
+        CSSPropertyGridRowStart,
+        CSSPropertyGridRowEnd
     };
     DEFINE_STATIC_LOCAL(StylePropertyShorthand, gridRowLonghands, (CSSPropertyGridRow, gridRowProperties, WTF_ARRAY_LENGTH(gridRowProperties)));
     return gridRowLonghands;
@@ -413,10 +413,10 @@
 const StylePropertyShorthand& gridAreaShorthand()
 {
     static const CSSPropertyID gridAreaProperties[] = {
-        CSSPropertyGridStart,
-        CSSPropertyGridBefore,
-        CSSPropertyGridEnd,
-        CSSPropertyGridAfter
+        CSSPropertyGridColumnStart,
+        CSSPropertyGridRowStart,
+        CSSPropertyGridColumnEnd,
+        CSSPropertyGridRowEnd
     };
     DEFINE_STATIC_LOCAL(StylePropertyShorthand, gridAreaLonghands, (CSSPropertyGridArea, gridAreaProperties, WTF_ARRAY_LENGTH(gridAreaProperties)));
     return gridAreaLonghands;
@@ -587,10 +587,10 @@
         return webkitColumnsShorthand();
     case CSSPropertyWebkitColumnRule:
         return webkitColumnRuleShorthand();
-    case CSSPropertyWebkitFlex:
-        return webkitFlexShorthand();
-    case CSSPropertyWebkitFlexFlow:
-        return webkitFlexFlowShorthand();
+    case CSSPropertyFlex:
+        return flexShorthand();
+    case CSSPropertyFlexFlow:
+        return flexFlowShorthand();
     case CSSPropertyGridColumn:
         return gridColumnShorthand();
     case CSSPropertyGridRow:
@@ -853,27 +853,27 @@
         map.set(CSSPropertyWebkitColumnRuleColor, columnRule);
 
         Vector<StylePropertyShorthand, 1> flex;
-        flex.uncheckedAppend(webkitFlexShorthand());
-        map.set(CSSPropertyWebkitFlexGrow, flex);
-        map.set(CSSPropertyWebkitFlexShrink, flex);
-        map.set(CSSPropertyWebkitFlexBasis, flex);
+        flex.uncheckedAppend(flexShorthand());
+        map.set(CSSPropertyFlexGrow, flex);
+        map.set(CSSPropertyFlexShrink, flex);
+        map.set(CSSPropertyFlexBasis, flex);
 
         Vector<StylePropertyShorthand, 1> flexFlow;
-        flexFlow.uncheckedAppend(webkitFlexFlowShorthand());
-        map.set(CSSPropertyWebkitFlexDirection, flexFlow);
-        map.set(CSSPropertyWebkitFlexWrap, flexFlow);
+        flexFlow.uncheckedAppend(flexFlowShorthand());
+        map.set(CSSPropertyFlexDirection, flexFlow);
+        map.set(CSSPropertyFlexWrap, flexFlow);
 
         Vector<StylePropertyShorthand, 2> grid;
         grid.uncheckedAppend(gridAreaShorthand());
         grid.uncheckedAppend(gridColumnShorthand());
-        map.set(CSSPropertyGridStart, grid);
-        map.set(CSSPropertyGridEnd, grid);
+        map.set(CSSPropertyGridColumnStart, grid);
+        map.set(CSSPropertyGridColumnEnd, grid);
 
         Vector<StylePropertyShorthand, 2> gridAfter;
         gridAfter.uncheckedAppend(gridAreaShorthand());
         gridAfter.uncheckedAppend(gridRowShorthand());
-        map.set(CSSPropertyGridBefore, gridAfter);
-        map.set(CSSPropertyGridAfter, gridAfter);
+        map.set(CSSPropertyGridRowStart, gridAfter);
+        map.set(CSSPropertyGridRowEnd, gridAfter);
 
         Vector<StylePropertyShorthand, 1> marginCollapse;
         marginCollapse.uncheckedAppend(webkitMarginCollapseShorthand());
diff --git a/Source/core/css/StylePropertyShorthand.h b/Source/core/css/StylePropertyShorthand.h
index 6992e89..d3f3b3f 100644
--- a/Source/core/css/StylePropertyShorthand.h
+++ b/Source/core/css/StylePropertyShorthand.h
@@ -96,8 +96,8 @@
 const StylePropertyShorthand& webkitBorderStartShorthand();
 const StylePropertyShorthand& webkitColumnsShorthand();
 const StylePropertyShorthand& webkitColumnRuleShorthand();
-const StylePropertyShorthand& webkitFlexFlowShorthand();
-const StylePropertyShorthand& webkitFlexShorthand();
+const StylePropertyShorthand& flexFlowShorthand();
+const StylePropertyShorthand& flexShorthand();
 const StylePropertyShorthand& gridColumnShorthand();
 const StylePropertyShorthand& gridRowShorthand();
 const StylePropertyShorthand& gridAreaShorthand();
diff --git a/Source/core/css/StyleRule.cpp b/Source/core/css/StyleRule.cpp
index e547872..3b16271 100644
--- a/Source/core/css/StyleRule.cpp
+++ b/Source/core/css/StyleRule.cpp
@@ -23,24 +23,20 @@
 #include "core/css/StyleRule.h"
 
 #include "RuntimeEnabledFeatures.h"
-#include "core/css/CSSCharsetRule.h"
 #include "core/css/CSSFilterRule.h"
 #include "core/css/CSSFontFaceRule.h"
 #include "core/css/CSSHostRule.h"
 #include "core/css/CSSImportRule.h"
-#include "core/css/CSSKeyframeRule.h"
 #include "core/css/CSSKeyframesRule.h"
 #include "core/css/CSSMediaRule.h"
 #include "core/css/CSSPageRule.h"
 #include "core/css/CSSRegionRule.h"
 #include "core/css/CSSStyleRule.h"
 #include "core/css/CSSSupportsRule.h"
-#include "core/css/CSSUnknownRule.h"
 #include "core/css/CSSViewportRule.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleRuleImport.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include "wtf/MemoryInstrumentationVector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/StyleRuleImport.cpp b/Source/core/css/StyleRuleImport.cpp
index 8f77583..d3808d3 100644
--- a/Source/core/css/StyleRuleImport.cpp
+++ b/Source/core/css/StyleRuleImport.cpp
@@ -22,7 +22,6 @@
 #include "config.h"
 #include "core/css/StyleRuleImport.h"
 
-#include <wtf/StdLibExtras.h>
 #include "core/css/StyleSheetContents.h"
 #include "core/dom/Document.h"
 #include "core/loader/cache/CachedCSSStyleSheet.h"
diff --git a/Source/core/css/StyleSheetList.cpp b/Source/core/css/StyleSheetList.cpp
index 226206e..bd00038 100644
--- a/Source/core/css/StyleSheetList.cpp
+++ b/Source/core/css/StyleSheetList.cpp
@@ -74,9 +74,10 @@
     // ### Bad implementation because returns a single element (are IDs always unique?)
     // and doesn't look for name attribute.
     // But unicity of stylesheet ids is good practice anyway ;)
+    // FIXME: We should figure out if we should change this or fix the spec.
     Element* element = m_document->getElementById(name);
     if (element && element->hasTagName(styleTag))
-        return static_cast<HTMLStyleElement*>(element);
+        return toHTMLStyleElement(element);
     return 0;
 }
 
diff --git a/Source/core/css/html.css b/Source/core/css/html.css
index 5b97e32..057d693 100644
--- a/Source/core/css/html.css
+++ b/Source/core/css/html.css
@@ -447,8 +447,7 @@
     display: block;
     -webkit-flex: none;
     -webkit-user-modify: read-only !important;
-    -webkit-align-self: flex-start;
-    margin: auto 0;
+    -webkit-margin-start: 1px;
 }
 
 input[type="search"]::-webkit-search-decoration {
diff --git a/Source/core/css/resolver/ElementStyleResources.cpp b/Source/core/css/resolver/ElementStyleResources.cpp
new file mode 100644
index 0000000..6efe8e0
--- /dev/null
+++ b/Source/core/css/resolver/ElementStyleResources.cpp
@@ -0,0 +1,54 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include "config.h"
+#include "core/css/resolver/ElementStyleResources.h"
+
+#include "core/platform/graphics/filters/FilterOperation.h"
+
+namespace WebCore {
+
+ElementStyleResources::ElementStyleResources()
+    : m_hasPendingShaders(false)
+    , m_deviceScaleFactor(1)
+{
+}
+
+void ElementStyleResources::addPendingImageProperty(const CSSPropertyID& property, CSSValue* value)
+{
+    m_pendingImageProperties.set(property, value);
+}
+
+void ElementStyleResources::addPendingSVGDocument(FilterOperation* filterOperation, CSSSVGDocumentValue* cssSVGDocumentValue)
+{
+    m_pendingSVGDocuments.set(filterOperation, cssSVGDocumentValue);
+}
+
+void ElementStyleResources::clear()
+{
+    m_pendingImageProperties.clear();
+    m_pendingSVGDocuments.clear();
+    m_hasPendingShaders = false;
+    m_deviceScaleFactor = 1;
+}
+
+}
diff --git a/Source/core/css/resolver/ElementStyleResources.h b/Source/core/css/resolver/ElementStyleResources.h
new file mode 100644
index 0000000..94c1599
--- /dev/null
+++ b/Source/core/css/resolver/ElementStyleResources.h
@@ -0,0 +1,71 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef ElementStyleResources_h
+#define ElementStyleResources_h
+
+#include "CSSPropertyNames.h"
+#include "core/css/CSSSVGDocumentValue.h"
+#include "core/css/CSSValue.h"
+#include "wtf/HashMap.h"
+
+namespace WebCore {
+
+class FilterOperation;
+
+typedef HashMap<FilterOperation*, RefPtr<CSSSVGDocumentValue> > PendingSVGDocumentMap;
+typedef HashMap<CSSPropertyID, RefPtr<CSSValue> > PendingImagePropertyMap;
+
+// Holds information about resources, requested by stylesheets.
+// Lifetime: per-element style resolve.
+// FIXME: At least for the moment, the lifetime actually matches that of StyleResolverState,
+// but all data is cleared for each element resolve. We must investigate performance
+// implications of matching effective and intended lifetime.
+class ElementStyleResources {
+WTF_MAKE_NONCOPYABLE(ElementStyleResources);
+public:
+    ElementStyleResources();
+
+    const PendingImagePropertyMap& pendingImageProperties() const { return m_pendingImageProperties; }
+    const PendingSVGDocumentMap& pendingSVGDocuments() const { return m_pendingSVGDocuments; }
+
+    void setHasPendingShaders(bool hasPendingShaders) { m_hasPendingShaders = hasPendingShaders; }
+    bool hasPendingShaders() const { return m_hasPendingShaders; }
+
+    float deviceScaleFactor() const { return m_deviceScaleFactor; }
+    void setDeviceScaleFactor(float deviceScaleFactor) { m_deviceScaleFactor = deviceScaleFactor; }
+
+    void addPendingImageProperty(const CSSPropertyID&, CSSValue*);
+    void addPendingSVGDocument(FilterOperation*, CSSSVGDocumentValue*);
+
+    void clear();
+
+private:
+    PendingImagePropertyMap m_pendingImageProperties;
+    PendingSVGDocumentMap m_pendingSVGDocuments;
+    bool m_hasPendingShaders;
+    float m_deviceScaleFactor;
+};
+
+} // namespace WebCore
+
+#endif // ElementStyleResources_h
diff --git a/Source/core/css/resolver/FilterOperationResolver.cpp b/Source/core/css/resolver/FilterOperationResolver.cpp
index d2c8e45..bde228b 100644
--- a/Source/core/css/resolver/FilterOperationResolver.cpp
+++ b/Source/core/css/resolver/FilterOperationResolver.cpp
@@ -99,7 +99,7 @@
 {
     StyleShader* shader = value->cachedOrPendingShader();
     if (shader && shader->isPendingShader())
-        state.setHasPendingShaders(true);
+        state.elementStyleResources().setHasPendingShaders(true);
     return shader;
 }
 
@@ -415,7 +415,7 @@
             RefPtr<ReferenceFilterOperation> operation = ReferenceFilterOperation::create(svgDocumentValue->url(), url.fragmentIdentifier(), operationType);
             if (SVGURIReference::isExternalURIReference(svgDocumentValue->url(), state.document())) {
                 if (!svgDocumentValue->loadRequested())
-                    state.pendingSVGDocuments().set(operation.get(), svgDocumentValue);
+                    state.elementStyleResources().addPendingSVGDocument(operation.get(), svgDocumentValue);
                 else if (svgDocumentValue->cachedSVGDocument())
                     operation->setCachedSVGDocumentReference(adoptPtr(new CachedSVGDocumentReference(svgDocumentValue->cachedSVGDocument())));
             }
@@ -497,7 +497,7 @@
             int blur = item->blur ? item->blur->computeLength<int>(style, rootStyle, zoomFactor) : 0;
             Color color;
             if (item->color)
-                color = state.colorFromPrimitiveValue(item->color.get());
+                color = state.resolveColorFromPrimitiveValue(item->color.get());
 
             operations.operations().append(DropShadowFilterOperation::create(location, blur, color.isValid() ? color : Color::transparent, operationType));
             break;
diff --git a/Source/core/css/resolver/FilterOperationResolver.h b/Source/core/css/resolver/FilterOperationResolver.h
index 3009735..cd4d817 100644
--- a/Source/core/css/resolver/FilterOperationResolver.h
+++ b/Source/core/css/resolver/FilterOperationResolver.h
@@ -22,8 +22,6 @@
 #ifndef FilterOperationResolver_h
 #define FilterOperationResolver_h
 
-#include "CSSPropertyNames.h"
-#include "core/css/CSSValueList.h"
 #include "core/css/resolver/StyleResolverState.h"
 #include "core/platform/graphics/filters/FilterOperations.h"
 
diff --git a/Source/core/css/resolver/ScopedStyleResolver.cpp b/Source/core/css/resolver/ScopedStyleResolver.cpp
index ef99e87..35a4110 100644
--- a/Source/core/css/resolver/ScopedStyleResolver.cpp
+++ b/Source/core/css/resolver/ScopedStyleResolver.cpp
@@ -41,7 +41,6 @@
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLStyleElement.h"
 #include "wtf/MemoryInstrumentationHashMap.h"
-#include "wtf/MemoryInstrumentationHashSet.h"
 
 namespace WebCore {
 
@@ -84,23 +83,35 @@
     ASSERT(target);
     ASSERT(target->scopingNode());
 
+    const ContainerNode* scopingNode = target->scopingNode();
+
     // Since StyleResolver creates RuleSets according to styles' document
     // order, a parent of the given ScopedRuleData has been already
     // prepared.
-    const ContainerNode* e = target->scopingNode()->parentOrShadowHostNode();
-    for (; e; e = e->parentOrShadowHostNode()) {
-        if (ScopedStyleResolver* scopedResolver = scopedStyleResolverFor(e)) {
+    for (const ContainerNode* node = scopingNode->parentOrShadowHostNode(); node; node = node->parentOrShadowHostNode()) {
+        if (ScopedStyleResolver* scopedResolver = scopedStyleResolverFor(node)) {
             target->setParent(scopedResolver);
             break;
         }
-        if (e->isDocumentNode()) {
+        if (node->isDocumentNode()) {
             bool dummy;
-            ScopedStyleResolver* scopedResolver = addScopedStyleResolver(e, dummy);
+            ScopedStyleResolver* scopedResolver = addScopedStyleResolver(node, dummy);
             target->setParent(scopedResolver);
             setupScopedStylesTree(scopedResolver);
             break;
         }
     }
+
+    if (m_buildInDocumentOrder)
+        return;
+
+    // Reparent all nodes whose scoping node is contained by target's one.
+    for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it) {
+        if (it->value == target)
+            continue;
+        if (it->value->parent() == target->parent() && scopingNode->containsIncludingShadowDOM(it->key))
+            it->value->setParent(target);
+    }
 }
 
 void ScopedStyleTree::clear()
@@ -163,6 +174,31 @@
         it->value->collectFeaturesTo(features);
 }
 
+inline void ScopedStyleTree::reparentNodes(const ScopedStyleResolver* oldParent, ScopedStyleResolver* newParent)
+{
+    // FIXME: this takes O(N) (N = number of all scoping nodes).
+    for (HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> >::iterator it = m_authorStyles.begin(); it != m_authorStyles.end(); ++it) {
+        if (it->value->parent() == oldParent)
+            it->value->setParent(newParent);
+    }
+}
+
+void ScopedStyleTree::remove(const ContainerNode* scopingNode)
+{
+    if (!scopingNode || scopingNode->isDocumentNode())
+        return;
+
+    ScopedStyleResolver* resolverRemoved = scopedStyleResolverFor(scopingNode);
+    if (!resolverRemoved)
+        return;
+
+    reparentNodes(resolverRemoved, resolverRemoved->parent());
+    if (m_cache.scopedResolver == resolverRemoved)
+        m_cache.clear();
+
+    m_authorStyles.remove(scopingNode);
+}
+
 void ScopedStyleTree::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
 {
     MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::CSS);
@@ -177,10 +213,10 @@
     if (!document)
         return 0;
     Node* ownerNode = sheet->ownerNode();
-    if (!ownerNode || !ownerNode->isHTMLElement() || !ownerNode->hasTagName(HTMLNames::styleTag))
+    if (!ownerNode || !ownerNode->hasTagName(HTMLNames::styleTag))
         return 0;
 
-    HTMLStyleElement* styleElement = static_cast<HTMLStyleElement*>(ownerNode);
+    HTMLStyleElement* styleElement = toHTMLStyleElement(ownerNode);
     if (!styleElement->scoped())
         return styleElement->isInShadowTree() ? styleElement->containingShadowRoot() : 0;
 
@@ -242,8 +278,11 @@
 void ScopedStyleResolver::resetAuthorStyle()
 {
     m_authorStyle = RuleSet::create();
-    m_authorStyle->disableAutoShrinkToFit();
-    m_atHostRules.clear();
+}
+
+void ScopedStyleResolver::resetAtHostRules(const ShadowRoot* shadowRoot)
+{
+    m_atHostRules.remove(shadowRoot);
 }
 
 bool ScopedStyleResolver::checkRegionStyle(Element* regionElement)
diff --git a/Source/core/css/resolver/ScopedStyleResolver.h b/Source/core/css/resolver/ScopedStyleResolver.h
index 3c2582f..0ed95d7 100644
--- a/Source/core/css/resolver/ScopedStyleResolver.h
+++ b/Source/core/css/resolver/ScopedStyleResolver.h
@@ -27,27 +27,8 @@
 #ifndef ScopedStyleResolver_h
 #define ScopedStyleResolver_h
 
-#include "core/css/CSSKeyframeRule.h"
-#include "core/css/CSSKeyframesRule.h"
-#include "core/css/CSSRuleList.h"
-#include "core/css/CSSSVGDocumentValue.h"
-#include "core/css/CSSToStyleMap.h"
-#include "core/css/CSSValueList.h"
-#include "core/css/DocumentRuleSets.h"
-#include "core/css/InspectorCSSOMWrappers.h"
-#include "core/css/MediaQueryExp.h"
-#include "core/css/RuleFeature.h"
 #include "core/css/RuleSet.h"
-#include "core/css/SelectorChecker.h"
-#include "core/css/SelectorFilter.h"
 #include "core/css/SiblingTraversalStrategies.h"
-#include "core/css/resolver/ViewportStyleResolver.h"
-#include "core/platform/LinkHash.h"
-#include "core/platform/ScrollTypes.h"
-#include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
-#include "core/rendering/style/RenderStyle.h"
-#include "core/rendering/style/StyleInheritedData.h"
-#include "wtf/Assertions.h"
 #include "wtf/Forward.h"
 #include "wtf/HashMap.h"
 #include "wtf/OwnPtr.h"
@@ -71,13 +52,14 @@
 
     static const ContainerNode* scopingNodeFor(const CSSStyleSheet*);
 
-    // methods for building tree.
     const ContainerNode* scopingNode() const { return m_scopingNode; }
     const TreeScope* treeScope() const { return m_scopingNode->treeScope(); }
     void prepareEmptyRuleSet() { m_authorStyle = RuleSet::create(); }
     void setParent(ScopedStyleResolver* newParent) { m_parent = newParent; }
     ScopedStyleResolver* parent() { return m_parent; }
 
+    bool hasOnlyEmptyRuleSets() const { return !m_authorStyle->ruleCount() && m_atHostRules.isEmpty(); }
+
 public:
     bool checkRegionStyle(Element*);
 
@@ -85,10 +67,11 @@
     void matchAuthorRules(ElementRuleCollector&, bool includeEmptyRules, bool applyAuthorStyles);
     void matchPageRules(PageRuleCollector&);
     void addRulesFromSheet(StyleSheetContents*, const MediaQueryEvaluator&, StyleResolver*);
-    void postAddRulesFromSheet() { m_authorStyle->shrinkToFit(); }
     void addHostRule(StyleRuleHost*, bool hasDocumentSecurityOrigin, const ContainerNode* scopingNode);
     void collectFeaturesTo(RuleFeatureSet&);
     void resetAuthorStyle();
+    void resetAtHostRules(const ShadowRoot*);
+
     void reportMemoryUsage(MemoryObjectInfo*) const;
 
 private:
@@ -108,7 +91,7 @@
 class ScopedStyleTree {
     WTF_MAKE_NONCOPYABLE(ScopedStyleTree); WTF_MAKE_FAST_ALLOCATED;
 public:
-    ScopedStyleTree() : m_scopedResolverForDocument(0) { }
+    ScopedStyleTree() : m_scopedResolverForDocument(0), m_buildInDocumentOrder(true) { }
 
     ScopedStyleResolver* ensureScopedStyleResolver(const ContainerNode* scopingNode);
     ScopedStyleResolver* scopedStyleResolverFor(const ContainerNode* scopingNode);
@@ -122,10 +105,14 @@
     void resolveScopedStyles(const Element*, Vector<ScopedStyleResolver*, 8>&);
     ScopedStyleResolver* scopedResolverFor(const Element*);
 
+    void remove(const ContainerNode* scopingNode);
+
     void pushStyleCache(const ContainerNode* scopingNode, const ContainerNode* parent);
     void popStyleCache(const ContainerNode* scopingNode);
 
     void collectFeaturesTo(RuleFeatureSet& features);
+    void setBuildInDocumentOrder(bool enabled) { m_buildInDocumentOrder = enabled; }
+    bool buildInDocumentOrder() const { return m_buildInDocumentOrder; }
 
     void reportMemoryUsage(MemoryObjectInfo*) const;
 private:
@@ -135,9 +122,12 @@
     void resolveStyleCache(const ContainerNode* scopingNode);
     ScopedStyleResolver* enclosingScopedStyleResolverFor(const ContainerNode* scopingNode);
 
+    void reparentNodes(const ScopedStyleResolver* oldParent, ScopedStyleResolver* newParent);
+
 private:
     HashMap<const ContainerNode*, OwnPtr<ScopedStyleResolver> > m_authorStyles;
     ScopedStyleResolver* m_scopedResolverForDocument;
+    bool m_buildInDocumentOrder;
 
     struct ScopedStyleCache {
         ScopedStyleResolver* scopedResolver;
diff --git a/Source/core/css/resolver/StyleResolver.cpp b/Source/core/css/resolver/StyleResolver.cpp
index 87e23ed..d06cf9b 100644
--- a/Source/core/css/resolver/StyleResolver.cpp
+++ b/Source/core/css/resolver/StyleResolver.cpp
@@ -30,36 +30,27 @@
 #include "core/css/resolver/StyleResolver.h"
 
 #include "CSSPropertyNames.h"
-#include "FontFamilyNames.h"
 #include "HTMLNames.h"
-#include "MathMLNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "SVGNames.h"
-#include "UserAgentStyleSheets.h"
 #include "XMLNames.h"
 #include "core/animation/AnimatableValue.h"
 #include "core/animation/Animation.h"
-#include "core/css/CSSBorderImage.h"
 #include "core/css/CSSCalculationValue.h"
 #include "core/css/CSSCursorImageValue.h"
 #include "core/css/CSSDefaultStyleSheets.h"
-#include "core/css/CSSFontFaceRule.h"
 #include "core/css/CSSFontSelector.h"
 #include "core/css/CSSImageSetValue.h"
 #include "core/css/CSSKeyframeRule.h"
 #include "core/css/CSSKeyframesRule.h"
 #include "core/css/CSSLineBoxContainValue.h"
-#include "core/css/CSSPageRule.h"
 #include "core/css/CSSParser.h"
 #include "core/css/CSSPrimitiveValueMappings.h"
 #include "core/css/CSSReflectValue.h"
 #include "core/css/CSSSVGDocumentValue.h"
 #include "core/css/CSSSelector.h"
 #include "core/css/CSSSelectorList.h"
-#include "core/css/CSSShaderValue.h"
 #include "core/css/CSSStyleRule.h"
-#include "core/css/CSSSupportsRule.h"
-#include "core/css/CSSTimingFunctionValue.h"
 #include "core/css/CSSValueList.h"
 #include "core/css/CSSVariableValue.h"
 #include "core/css/Counter.h"
@@ -68,66 +59,39 @@
 #include "core/css/FontFeatureValue.h"
 #include "core/css/FontSize.h"
 #include "core/css/FontValue.h"
-#include "core/css/MediaList.h"
 #include "core/css/MediaQueryEvaluator.h"
 #include "core/css/PageRuleCollector.h"
 #include "core/css/Pair.h"
-#include "core/css/Rect.h"
 #include "core/css/RuleSet.h"
-#include "core/css/SelectorCheckerFastPath.h"
 #include "core/css/ShadowValue.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StylePropertyShorthand.h"
-#include "core/css/StyleRule.h"
-#include "core/css/StyleRuleImport.h"
 #include "core/css/StyleSheetContents.h"
-#include "core/css/StyleSheetList.h"
+#include "core/css/resolver/ElementStyleResources.h"
 #include "core/css/resolver/FilterOperationResolver.h"
 #include "core/css/resolver/StyleBuilder.h"
 #include "core/css/resolver/TransformBuilder.h"
 #include "core/css/resolver/ViewportStyleResolver.h"
-#include "core/dom/Attribute.h"
-#include "core/dom/ContextFeatures.h"
 #include "core/dom/DocumentStyleSheetCollection.h"
 #include "core/dom/FullscreenController.h"
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/NodeRenderingContext.h"
 #include "core/dom/Text.h"
-#include "core/dom/VisitedLinkState.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include "core/dom/shadow/ElementShadow.h"
-#include "core/dom/shadow/InsertionPoint.h"
 #include "core/dom/shadow/ShadowRoot.h"
-#include "core/editing/FrameSelection.h"
-#include "core/html/HTMLDocument.h"
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/HTMLOptionElement.h"
-#include "core/html/HTMLProgressElement.h"
-#include "core/html/HTMLStyleElement.h"
-#include "core/html/HTMLTextAreaElement.h"
 #include "core/html/track/WebVTTElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/cache/CachedDocument.h"
-#include "core/loader/cache/CachedImage.h"
 #include "core/loader/cache/CachedSVGDocumentReference.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "core/platform/CalculationValue.h"
 #include "core/platform/LinkHash.h"
-#include "core/platform/graphics/filters/custom/CustomFilterArrayParameter.h"
 #include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
-#include "core/platform/graphics/filters/custom/CustomFilterNumberParameter.h"
-#include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
-#include "core/platform/graphics/filters/custom/CustomFilterParameter.h"
-#include "core/platform/graphics/filters/custom/CustomFilterProgramInfo.h"
-#include "core/platform/graphics/filters/custom/CustomFilterTransformParameter.h"
 #include "core/platform/text/LocaleToScriptMapping.h"
-#include "core/rendering/RenderRegion.h"
-#include "core/rendering/RenderScrollbar.h"
-#include "core/rendering/RenderScrollbarTheme.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/style/ContentData.h"
@@ -139,21 +103,15 @@
 #include "core/rendering/style/ShadowData.h"
 #include "core/rendering/style/StyleCachedImage.h"
 #include "core/rendering/style/StyleCachedImageSet.h"
-#include "core/rendering/style/StyleCachedShader.h"
-#include "core/rendering/style/StyleCustomFilterProgram.h"
 #include "core/rendering/style/StyleCustomFilterProgramCache.h"
 #include "core/rendering/style/StyleGeneratedImage.h"
 #include "core/rendering/style/StylePendingImage.h"
 #include "core/rendering/style/StylePendingShader.h"
 #include "core/rendering/style/StyleShader.h"
-#include "core/svg/SVGDocument.h"
 #include "core/svg/SVGDocumentExtensions.h"
 #include "core/svg/SVGElement.h"
 #include "core/svg/SVGFontFaceElement.h"
-#include "core/svg/SVGURIReference.h"
-#include "weborigin/SecurityOrigin.h"
 #include "wtf/MemoryInstrumentationHashMap.h"
-#include "wtf/MemoryInstrumentationHashSet.h"
 #include "wtf/MemoryInstrumentationVector.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/Vector.h"
@@ -223,6 +181,7 @@
     , m_viewportStyleResolver(ViewportStyleResolver::create(document))
     , m_styleBuilder(DeprecatedStyleBuilder::sharedStyleBuilder())
     , m_styleMap(this)
+    , m_styleResourceLoader(document->cachedResourceLoader())
 {
     Element* root = document->documentElement();
 
@@ -260,6 +219,7 @@
     }
 #endif
 
+    // FIXME: Stylesheet candidate nodes are sorted in document order, but scoping nodes are not sorted.
     appendAuthorStyleSheets(0, styleSheetCollection->activeAuthorStyleSheets());
 }
 
@@ -267,7 +227,6 @@
 {
     // This handles sheets added to the end of the stylesheet list only. In other cases the style resolver
     // needs to be reconstructed. To handle insertions too the rule order numbers would need to be updated.
-    ScopedStyleResolver* lastUpdatedResolver = 0;
     unsigned size = styleSheets.size();
     for (unsigned i = firstNew; i < size; ++i) {
         CSSStyleSheet* cssSheet = styleSheets[i].get();
@@ -280,14 +239,8 @@
         ASSERT(resolver);
         resolver->addRulesFromSheet(sheet, *m_medium, this);
         m_inspectorCSSOMWrappers.collectFromStyleSheetIfNeeded(cssSheet);
-
-        if (lastUpdatedResolver && lastUpdatedResolver != resolver)
-            lastUpdatedResolver->postAddRulesFromSheet();
-        lastUpdatedResolver = resolver;
     }
 
-    if (lastUpdatedResolver)
-        lastUpdatedResolver->postAddRulesFromSheet();
     collectFeatures();
 
     if (document()->renderer() && document()->renderer()->style())
@@ -302,6 +255,41 @@
     m_styleTree.clear();
 }
 
+void StyleResolver::resetAuthorStyle(const ContainerNode* scopingNode)
+{
+    m_styleTree.clear();
+    ScopedStyleResolver* resolver = scopingNode ? m_styleTree.scopedStyleResolverFor(scopingNode) : m_styleTree.scopedStyleResolverForDocument();
+    if (!resolver)
+        return;
+
+    m_ruleSets.shadowDistributedRules().reset(scopingNode);
+
+    resolver->resetAuthorStyle();
+
+    if (!scopingNode || !resolver->hasOnlyEmptyRuleSets())
+        return;
+
+    m_styleTree.remove(scopingNode);
+}
+
+void StyleResolver::resetAtHostRules(const ContainerNode* scopingNode)
+{
+    ASSERT(scopingNode);
+    ASSERT(scopingNode->isShadowRoot());
+
+    const ShadowRoot* shadowRoot = toShadowRoot(scopingNode);
+    const ContainerNode* shadowHost = shadowRoot->shadowHost();
+    ScopedStyleResolver* resolver = m_styleTree.scopedStyleResolverFor(shadowHost);
+    if (!resolver)
+        return;
+
+    resolver->resetAtHostRules(shadowRoot);
+    if (!resolver->hasOnlyEmptyRuleSets())
+        return;
+
+    m_styleTree.remove(shadowHost);
+}
+
 static PassOwnPtr<RuleSet> makeRuleSet(const Vector<RuleFeature>& rules)
 {
     size_t size = rules.size();
@@ -310,7 +298,6 @@
     OwnPtr<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);
-    ruleSet->shrinkToFit();
     return ruleSet.release();
 }
 
@@ -561,17 +548,6 @@
         collector.matchedResult().isCacheable = false;
 }
 
-inline void StyleResolver::initElement(Element* e)
-{
-    if (m_state.element() != e) {
-        m_state.initElement(e);
-        if (e && e == e->document()->documentElement()) {
-            e->document()->setDirectionSetOnDocumentElement(false);
-            e->document()->setWritingModeSetOnDocumentElement(false);
-        }
-    }
-}
-
 static const unsigned cStyleSearchThreshold = 10;
 static const unsigned cStyleSearchLevelThreshold = 10;
 
@@ -590,18 +566,17 @@
         return 0;
     if (parent->hasScopedHTMLStyleChild())
         return 0;
-    StyledElement* p = static_cast<StyledElement*>(parent);
-    if (p->inlineStyle())
+    if (parent->inlineStyle())
         return 0;
-    if (p->isSVGElement() && toSVGElement(p)->animatedSMILStyleProperties())
+    if (parent->isSVGElement() && toSVGElement(parent)->animatedSMILStyleProperties())
         return 0;
-    if (p->hasID() && m_features.idsInRules.contains(p->idForStyleResolution().impl()))
+    if (parent->hasID() && m_features.idsInRules.contains(parent->idForStyleResolution().impl()))
         return 0;
 
-    RenderStyle* parentStyle = p->renderStyle();
+    RenderStyle* parentStyle = parent->renderStyle();
     unsigned subcount = 0;
-    Node* thisCousin = p;
-    Node* currentNode = p->previousSibling();
+    Node* thisCousin = parent;
+    Node* currentNode = parent->previousSibling();
 
     // Reserve the tries for this level. This effectively makes sure that the algorithm
     // will never go deeper than cStyleSearchLevelThreshold levels into recursion.
@@ -637,7 +612,7 @@
     return collector.hasAnyMatchingRules(ruleSet);
 }
 
-bool StyleResolver::canShareStyleWithControl(StyledElement* element) const
+bool StyleResolver::canShareStyleWithControl(Element* element) const
 {
     const StyleResolverState& state = m_state;
 
@@ -693,7 +668,7 @@
     return element->isHTMLElement() && toHTMLElement(element)->hasDirectionAuto();
 }
 
-bool StyleResolver::sharingCandidateHasIdenticalStyleAffectingAttributes(StyledElement* sharingCandidate) const
+bool StyleResolver::sharingCandidateHasIdenticalStyleAffectingAttributes(Element* sharingCandidate) const
 {
     const StyleResolverState& state = m_state;
     if (state.element()->elementData() == sharingCandidate->elementData())
@@ -729,7 +704,7 @@
     return true;
 }
 
-bool StyleResolver::canShareStyleWithElement(StyledElement* element) const
+bool StyleResolver::canShareStyleWithElement(Element* element) const
 {
     RenderStyle* style = element->renderStyle();
     const StyleResolverState& state = m_state;
@@ -816,17 +791,17 @@
     return true;
 }
 
-inline StyledElement* StyleResolver::findSiblingForStyleSharing(Node* node, unsigned& count) const
+inline Element* StyleResolver::findSiblingForStyleSharing(Node* node, unsigned& count) const
 {
     for (; node; node = node->previousSibling()) {
         if (!node->isStyledElement())
             continue;
-        if (canShareStyleWithElement(static_cast<StyledElement*>(node)))
+        if (canShareStyleWithElement(toElement(node)))
             break;
         if (count++ == cStyleSearchThreshold)
             return 0;
     }
-    return static_cast<StyledElement*>(node);
+    return toElement(node);
 }
 
 RenderStyle* StyleResolver::locateSharedStyle()
@@ -866,7 +841,7 @@
     // Check previous siblings and their cousins.
     unsigned count = 0;
     unsigned visitedNodeCount = 0;
-    StyledElement* shareElement = 0;
+    Element* shareElement = 0;
     Node* cousinList = state.styledElement()->previousSibling();
     while (cousinList) {
         shareElement = findSiblingForStyleSharing(cousinList, count);
@@ -1098,7 +1073,6 @@
     }
 
     StyleResolverState& state = m_state;
-    initElement(element);
     state.initForStyleResolve(document(), element, defaultParent, regionForStyling);
     if (sharingBehavior == AllowStyleSharing && !state.distributedToInsertionPoint()) {
         RenderStyle* sharedStyle = locateSharedStyle();
@@ -1199,7 +1173,7 @@
     updateFont();
 
     // Start loading resources referenced by this style.
-    loadPendingResources();
+    m_styleResourceLoader.loadPendingResources(m_state.style(), m_state.elementStyleResources());
 
     // Add all the animating properties to the keyframe.
     if (const StylePropertySet* styleDeclaration = keyframe->properties()) {
@@ -1238,7 +1212,6 @@
     const Vector<RefPtr<StyleKeyframe> >& keyframes = keyframesRule->keyframes();
     for (unsigned i = 0; i < keyframes.size(); ++i) {
         // Apply the declaration to the style. This is a simplified version of the logic in styleForElement
-        initElement(e);
         m_state.initForStyleResolve(document(), e);
 
         const StyleKeyframe* keyframe = keyframes[i].get();
@@ -1289,8 +1262,6 @@
 
     StyleResolverState& state = m_state;
 
-    initElement(e);
-
     state.initForStyleResolve(document(), e, parentStyle);
 
     if (m_state.parentStyle()) {
@@ -1325,7 +1296,7 @@
     adjustRenderStyle(state.style(), m_state.parentStyle(), 0);
 
     // Start loading resources referenced by this style.
-    loadPendingResources();
+    m_styleResourceLoader.loadPendingResources(m_state.style(), m_state.elementStyleResources());
 
     document()->didAccessStyleResolver();
 
@@ -1365,7 +1336,7 @@
     applyMatchedProperties<LowPriorityProperties>(result, false, 0, result.matchedProperties.size() - 1, inheritedOnly);
 
     // Start loading resources referenced by this style.
-    loadPendingResources();
+    m_styleResourceLoader.loadPendingResources(m_state.style(), m_state.elementStyleResources());
 
     document()->didAccessStyleResolver();
 
@@ -1713,14 +1684,14 @@
 void StyleResolver::adjustGridItemPosition(RenderStyle* style) const
 {
     // If opposing grid-placement properties both specify a grid span, they both compute to ‘auto’.
-    if (style->gridStart().isSpan() && style->gridEnd().isSpan()) {
-        style->setGridStart(GridPosition());
-        style->setGridEnd(GridPosition());
+    if (style->gridColumnStart().isSpan() && style->gridColumnEnd().isSpan()) {
+        style->setGridColumnStart(GridPosition());
+        style->setGridColumnEnd(GridPosition());
     }
 
-    if (style->gridBefore().isSpan() && style->gridAfter().isSpan()) {
-        style->setGridBefore(GridPosition());
-        style->setGridAfter(GridPosition());
+    if (style->gridRowStart().isSpan() && style->gridRowEnd().isSpan()) {
+        style->setGridRowStart(GridPosition());
+        style->setGridRowEnd(GridPosition());
     }
 }
 
@@ -1784,7 +1755,6 @@
     if (!e || !e->document()->haveStylesheetsLoaded())
         return 0;
 
-    initElement(e);
     m_state.initForStyleResolve(document(), e, 0);
 
     ElementRuleCollector collector(this, m_state);
@@ -2189,12 +2159,14 @@
     applyMatchedProperties<LowPriorityProperties>(matchResult, true, matchResult.ranges.firstUARule, matchResult.ranges.lastUARule, applyInheritedOnly);
 
     // Start loading resources referenced by this style.
-    loadPendingResources();
+    m_styleResourceLoader.loadPendingResources(m_state.style(), m_state.elementStyleResources());
 
     ASSERT(!state.fontDirty());
 
     if (cacheItem || !cacheHash)
         return;
+    if (!state.isMatchedPropertiesCacheable())
+        return;
     if (!isCacheableInMatchedPropertiesCache(state.element(), state.style(), state.parentStyle()))
         return;
     addToMatchedPropertiesCache(state.style(), state.parentStyle(), cacheHash, matchResult);
@@ -2202,7 +2174,6 @@
 
 void StyleResolver::applyPropertyToStyle(CSSPropertyID id, CSSValue* value, RenderStyle* style)
 {
-    initElement(0);
     m_state.initForStyleResolve(document(), 0, style);
     m_state.setStyle(style);
     applyPropertyToCurrentStyle(id, value);
@@ -2214,27 +2185,19 @@
         applyProperty(id, value);
 }
 
-// SVG handles zooming in a different way compared to CSS. The whole document is scaled instead
-// of each individual length value in the render style / tree. CSSPrimitiveValue::computeLength*()
-// multiplies each resolved length with the zoom multiplier - so for SVG we need to disable that.
-// Though all CSS values that can be applied to outermost <svg> elements (width/height/border/padding...)
-// need to respect the scaling. RenderBox (the parent class of RenderSVGRoot) grabs values like
-// width/height/border/padding/... from the RenderStyle -> for SVG these values would never scale,
-// if we'd pass a 1.0 zoom factor everyhwere. So we only pass a zoom factor of 1.0 for specific
-// properties that are NOT allowed to scale within a zoomed SVG document (letter/word-spacing/font-size).
 bool StyleResolver::useSVGZoomRules()
 {
-    return m_state.element() && m_state.element()->isSVGElement();
+    return m_state.useSVGZoomRules();
 }
 
 static bool createGridTrackBreadth(CSSPrimitiveValue* primitiveValue, const StyleResolverState& state, GridLength& workingLength)
 {
-    if (primitiveValue->getValueID() == CSSValueWebkitMinContent) {
+    if (primitiveValue->getValueID() == CSSValueMinContent) {
         workingLength = Length(MinContent);
         return true;
     }
 
-    if (primitiveValue->getValueID() == CSSValueWebkitMaxContent) {
+    if (primitiveValue->getValueID() == CSSValueMaxContent) {
         workingLength = Length(MaxContent);
         return true;
     }
@@ -2311,9 +2274,9 @@
         trackSizes.append(trackSize);
     }
 
-    if (trackSizes.isEmpty())
-        return false;
-
+    // The parser should have rejected any <track-list> without any <track-size> as
+    // this is not conformant to the syntax.
+    ASSERT(!trackSizes.isEmpty());
     return true;
 }
 
@@ -2491,7 +2454,7 @@
                 CSSValue* item = i.value();
                 if (item->isImageGeneratorValue()) {
                     if (item->isGradientValue())
-                        state.style()->setContent(StyleGeneratedImage::create(static_cast<CSSGradientValue*>(item)->gradientWithStylesResolved(this).get()), didSet);
+                        state.style()->setContent(StyleGeneratedImage::create(static_cast<CSSGradientValue*>(item)->gradientWithStylesResolved(m_state).get()), didSet);
                     else
                         state.style()->setContent(StyleGeneratedImage::create(static_cast<CSSImageGeneratorValue*>(item)), didSet);
                     didSet = true;
@@ -2624,7 +2587,7 @@
                 fontDescription.setUsePrinterFont(document()->printing());
 
                 // Handle the zoom factor.
-                fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(document(), state.style(), fontDescription.isAbsoluteSize(), fontDescription.specifiedSize(), useSVGZoomRules()));
+                fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(document(), state.style(), fontDescription.isAbsoluteSize(), fontDescription.specifiedSize(), m_state.useSVGZoomRules()));
                 setFontDescription(fontDescription);
             }
         } else if (value->isFontValue()) {
@@ -2676,8 +2639,8 @@
     case CSSPropertyWebkitBorderRadius:
     case CSSPropertyWebkitColumns:
     case CSSPropertyWebkitColumnRule:
-    case CSSPropertyWebkitFlex:
-    case CSSPropertyWebkitFlexFlow:
+    case CSSPropertyFlex:
+    case CSSPropertyFlexFlow:
     case CSSPropertyGridColumn:
     case CSSPropertyGridRow:
     case CSSPropertyGridArea:
@@ -2721,7 +2684,7 @@
             ShadowStyle shadowStyle = item->style && item->style->getValueID() == CSSValueInset ? Inset : Normal;
             Color color;
             if (item->color)
-                color = m_state.colorFromPrimitiveValue(item->color.get());
+                color = m_state.resolveColorFromPrimitiveValue(item->color.get());
             else if (state.style())
                 color = state.style()->color();
 
@@ -2838,7 +2801,7 @@
         if (!primitiveValue)
             break;
 
-        Color col = m_state.colorFromPrimitiveValue(primitiveValue);
+        Color col = m_state.resolveColorFromPrimitiveValue(primitiveValue);
         state.style()->setTapHighlightColor(col);
         return;
     }
@@ -2964,7 +2927,7 @@
     case CSSPropertyWebkitFilter: {
         HANDLE_INHERIT_AND_INITIAL(filter, Filter);
         FilterOperations operations;
-        if (FilterOperationResolver::createFilterOperations(value, state.style(), state.rootElementStyle(), operations, m_customFilterProgramCache.get(), m_state))
+        if (FilterOperationResolver::createFilterOperations(value, state.style(), state.rootElementStyle(), operations, m_styleResourceLoader.customFilterProgramCache(), m_state))
             state.style()->setFilter(operations);
         return;
     }
@@ -2984,14 +2947,14 @@
         state.style()->setGridAutoRows(trackSize);
         return;
     }
-    case CSSPropertyGridColumns: {
+    case CSSPropertyGridDefinitionColumns: {
         if (isInherit) {
-            m_state.style()->setGridColumns(m_state.parentStyle()->gridColumns());
+            m_state.style()->setGridDefinitionColumns(m_state.parentStyle()->gridDefinitionColumns());
             m_state.style()->setNamedGridColumnLines(m_state.parentStyle()->namedGridColumnLines());
             return;
         }
         if (isInitial) {
-            m_state.style()->setGridColumns(RenderStyle::initialGridColumns());
+            m_state.style()->setGridDefinitionColumns(RenderStyle::initialGridDefinitionColumns());
             m_state.style()->setNamedGridColumnLines(RenderStyle::initialNamedGridColumnLines());
             return;
         }
@@ -3000,18 +2963,18 @@
         NamedGridLinesMap namedGridLines;
         if (!createGridTrackList(value, trackSizes, namedGridLines, state))
             return;
-        state.style()->setGridColumns(trackSizes);
+        state.style()->setGridDefinitionColumns(trackSizes);
         state.style()->setNamedGridColumnLines(namedGridLines);
         return;
     }
-    case CSSPropertyGridRows: {
+    case CSSPropertyGridDefinitionRows: {
         if (isInherit) {
-            m_state.style()->setGridRows(m_state.parentStyle()->gridRows());
+            m_state.style()->setGridDefinitionRows(m_state.parentStyle()->gridDefinitionRows());
             m_state.style()->setNamedGridRowLines(m_state.parentStyle()->namedGridRowLines());
             return;
         }
         if (isInitial) {
-            m_state.style()->setGridRows(RenderStyle::initialGridRows());
+            m_state.style()->setGridDefinitionRows(RenderStyle::initialGridDefinitionRows());
             m_state.style()->setNamedGridRowLines(RenderStyle::initialNamedGridRowLines());
             return;
         }
@@ -3020,42 +2983,42 @@
         NamedGridLinesMap namedGridLines;
         if (!createGridTrackList(value, trackSizes, namedGridLines, state))
             return;
-        state.style()->setGridRows(trackSizes);
+        state.style()->setGridDefinitionRows(trackSizes);
         state.style()->setNamedGridRowLines(namedGridLines);
         return;
     }
 
-    case CSSPropertyGridStart: {
-        HANDLE_INHERIT_AND_INITIAL(gridStart, GridStart);
+    case CSSPropertyGridColumnStart: {
+        HANDLE_INHERIT_AND_INITIAL(gridColumnStart, GridColumnStart);
         GridPosition startPosition;
         if (!createGridPosition(value, startPosition))
             return;
-        state.style()->setGridStart(startPosition);
+        state.style()->setGridColumnStart(startPosition);
         return;
     }
-    case CSSPropertyGridEnd: {
-        HANDLE_INHERIT_AND_INITIAL(gridEnd, GridEnd);
+    case CSSPropertyGridColumnEnd: {
+        HANDLE_INHERIT_AND_INITIAL(gridColumnEnd, GridColumnEnd);
         GridPosition endPosition;
         if (!createGridPosition(value, endPosition))
             return;
-        state.style()->setGridEnd(endPosition);
+        state.style()->setGridColumnEnd(endPosition);
         return;
     }
 
-    case CSSPropertyGridBefore: {
-        HANDLE_INHERIT_AND_INITIAL(gridBefore, GridBefore);
+    case CSSPropertyGridRowStart: {
+        HANDLE_INHERIT_AND_INITIAL(gridRowStart, GridRowStart);
         GridPosition beforePosition;
         if (!createGridPosition(value, beforePosition))
             return;
-        state.style()->setGridBefore(beforePosition);
+        state.style()->setGridRowStart(beforePosition);
         return;
     }
-    case CSSPropertyGridAfter: {
-        HANDLE_INHERIT_AND_INITIAL(gridAfter, GridAfter);
+    case CSSPropertyGridRowEnd: {
+        HANDLE_INHERIT_AND_INITIAL(gridRowEnd, GridRowEnd);
         GridPosition afterPosition;
         if (!createGridPosition(value, afterPosition))
             return;
-        state.style()->setGridAfter(afterPosition);
+        state.style()->setGridRowEnd(afterPosition);
         return;
     }
 
@@ -3212,16 +3175,16 @@
     case CSSPropertyWebkitColumnRuleWidth:
     case CSSPropertyWebkitColumnSpan:
     case CSSPropertyWebkitColumnWidth:
-    case CSSPropertyWebkitAlignContent:
-    case CSSPropertyWebkitAlignItems:
-    case CSSPropertyWebkitAlignSelf:
-    case CSSPropertyWebkitFlexBasis:
-    case CSSPropertyWebkitFlexDirection:
-    case CSSPropertyWebkitFlexGrow:
-    case CSSPropertyWebkitFlexShrink:
-    case CSSPropertyWebkitFlexWrap:
-    case CSSPropertyWebkitJustifyContent:
-    case CSSPropertyWebkitOrder:
+    case CSSPropertyAlignContent:
+    case CSSPropertyAlignItems:
+    case CSSPropertyAlignSelf:
+    case CSSPropertyFlexBasis:
+    case CSSPropertyFlexDirection:
+    case CSSPropertyFlexGrow:
+    case CSSPropertyFlexShrink:
+    case CSSPropertyFlexWrap:
+    case CSSPropertyJustifyContent:
+    case CSSPropertyOrder:
     case CSSPropertyWebkitFlowFrom:
     case CSSPropertyWebkitFlowInto:
     case CSSPropertyWebkitFontKerning:
@@ -3325,7 +3288,7 @@
 
     if (value->isImageGeneratorValue()) {
         if (value->isGradientValue())
-            return generatedOrPendingFromValue(property, static_cast<CSSGradientValue*>(value)->gradientWithStylesResolved(this).get());
+            return generatedOrPendingFromValue(property, static_cast<CSSGradientValue*>(value)->gradientWithStylesResolved(m_state).get());
         return generatedOrPendingFromValue(property, static_cast<CSSImageGeneratorValue*>(value));
     }
 
@@ -3342,14 +3305,14 @@
 {
     RefPtr<StyleImage> image = value->cachedOrPendingImage();
     if (image && image->isPendingImage())
-        m_state.pendingImageProperties().set(property, value);
+        m_state.elementStyleResources().addPendingImageProperty(property, value);
     return image.release();
 }
 
 PassRefPtr<StyleImage> StyleResolver::generatedOrPendingFromValue(CSSPropertyID property, CSSImageGeneratorValue* value)
 {
     if (value->isPending()) {
-        m_state.pendingImageProperties().set(property, value);
+        m_state.elementStyleResources().addPendingImageProperty(property, value);
         return StylePendingImage::create(value);
     }
     return StyleGeneratedImage::create(value);
@@ -3357,17 +3320,17 @@
 
 PassRefPtr<StyleImage> StyleResolver::setOrPendingFromValue(CSSPropertyID property, CSSImageSetValue* value)
 {
-    RefPtr<StyleImage> image = value->cachedOrPendingImageSet(document());
+    RefPtr<StyleImage> image = value->cachedOrPendingImageSet(m_state.elementStyleResources().deviceScaleFactor());
     if (image && image->isPendingImage())
-        m_state.pendingImageProperties().set(property, value);
+        m_state.elementStyleResources().addPendingImageProperty(property, value);
     return image.release();
 }
 
 PassRefPtr<StyleImage> StyleResolver::cursorOrPendingFromValue(CSSPropertyID property, CSSCursorImageValue* value)
 {
-    RefPtr<StyleImage> image = value->cachedOrPendingImage(document());
+    RefPtr<StyleImage> image = value->cachedOrPendingImage(m_state.elementStyleResources().deviceScaleFactor());
     if (image && image->isPendingImage())
-        m_state.pendingImageProperties().set(property, value);
+        m_state.elementStyleResources().addPendingImageProperty(property, value);
     return image.release();
 }
 
@@ -3441,21 +3404,7 @@
 void StyleResolver::setFontSize(FontDescription& fontDescription, float size)
 {
     fontDescription.setSpecifiedSize(size);
-    fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(document(), m_state.style(), fontDescription.isAbsoluteSize(), size, useSVGZoomRules()));
-}
-
-bool StyleResolver::colorFromPrimitiveValueIsDerivedFromElement(CSSPrimitiveValue* value)
-{
-    int ident = value->getValueID();
-    switch (ident) {
-    case CSSValueWebkitText:
-    case CSSValueWebkitLink:
-    case CSSValueWebkitActivelink:
-    case CSSValueCurrentcolor:
-        return true;
-    default:
-        return false;
-    }
+    fontDescription.setComputedSize(getComputedSizeFromSpecifiedSize(document(), m_state.style(), fontDescription.isAbsoluteSize(), size, m_state.useSVGZoomRules()));
 }
 
 void StyleResolver::addViewportDependentMediaQueryResult(const MediaQueryExp* expr, bool result)
@@ -3473,203 +3422,6 @@
     return false;
 }
 
-void StyleResolver::loadPendingSVGDocuments()
-{
-    StyleResolverState& state = m_state;
-    if (!state.style()->hasFilter() || state.pendingSVGDocuments().isEmpty())
-        return;
-
-    CachedResourceLoader* cachedResourceLoader = state.document()->cachedResourceLoader();
-    Vector<RefPtr<FilterOperation> >& filterOperations = state.style()->mutableFilter().operations();
-    for (unsigned i = 0; i < filterOperations.size(); ++i) {
-        RefPtr<FilterOperation> filterOperation = filterOperations.at(i);
-        if (filterOperation->getOperationType() == FilterOperation::REFERENCE) {
-            ReferenceFilterOperation* referenceFilter = static_cast<ReferenceFilterOperation*>(filterOperation.get());
-
-            CSSSVGDocumentValue* value = state.pendingSVGDocuments().get(referenceFilter);
-            if (!value)
-                continue;
-            CachedDocument* cachedDocument = value->load(cachedResourceLoader);
-            if (!cachedDocument)
-                continue;
-
-            // Stash the CachedDocument on the reference filter.
-            referenceFilter->setCachedSVGDocumentReference(adoptPtr(new CachedSVGDocumentReference(cachedDocument)));
-        }
-    }
-    state.pendingSVGDocuments().clear();
-}
-
-void StyleResolver::loadPendingShaders()
-{
-    if (!m_state.style()->hasFilter() || !m_state.hasPendingShaders())
-        return;
-
-    CachedResourceLoader* cachedResourceLoader = m_state.document()->cachedResourceLoader();
-
-    Vector<RefPtr<FilterOperation> >& filterOperations = m_state.style()->mutableFilter().operations();
-    for (unsigned i = 0; i < filterOperations.size(); ++i) {
-        RefPtr<FilterOperation> filterOperation = filterOperations.at(i);
-        if (filterOperation->getOperationType() == FilterOperation::CUSTOM) {
-            CustomFilterOperation* customFilter = static_cast<CustomFilterOperation*>(filterOperation.get());
-            ASSERT(customFilter->program());
-            StyleCustomFilterProgram* program = static_cast<StyleCustomFilterProgram*>(customFilter->program());
-            // Note that the StylePendingShaders could be already resolved to StyleCachedShaders. That's because the rule was matched before.
-            // However, the StyleCustomFilterProgram that was initially created could have been removed from the cache in the meanwhile,
-            // meaning that we get a new StyleCustomFilterProgram here that is not yet in the cache, but already has loaded StyleShaders.
-            if (!program->hasPendingShaders() && program->inCache())
-                continue;
-            if (!m_customFilterProgramCache)
-                m_customFilterProgramCache = adoptPtr(new StyleCustomFilterProgramCache());
-            RefPtr<StyleCustomFilterProgram> styleProgram = m_customFilterProgramCache->lookup(program);
-            if (styleProgram.get())
-                customFilter->setProgram(styleProgram.release());
-            else {
-                if (program->vertexShader() && program->vertexShader()->isPendingShader()) {
-                    CSSShaderValue* shaderValue = static_cast<StylePendingShader*>(program->vertexShader())->cssShaderValue();
-                    program->setVertexShader(shaderValue->cachedShader(cachedResourceLoader));
-                }
-                if (program->fragmentShader() && program->fragmentShader()->isPendingShader()) {
-                    CSSShaderValue* shaderValue = static_cast<StylePendingShader*>(program->fragmentShader())->cssShaderValue();
-                    program->setFragmentShader(shaderValue->cachedShader(cachedResourceLoader));
-                }
-                m_customFilterProgramCache->add(program);
-            }
-        }
-    }
-    m_state.setHasPendingShaders(false);
-}
-
-PassRefPtr<StyleImage> StyleResolver::loadPendingImage(StylePendingImage* pendingImage)
-{
-    CachedResourceLoader* cachedResourceLoader = m_state.document()->cachedResourceLoader();
-
-    if (pendingImage->cssImageValue()) {
-        CSSImageValue* imageValue = pendingImage->cssImageValue();
-        return imageValue->cachedImage(cachedResourceLoader);
-    }
-
-    if (pendingImage->cssImageGeneratorValue()) {
-        CSSImageGeneratorValue* imageGeneratorValue = pendingImage->cssImageGeneratorValue();
-        imageGeneratorValue->loadSubimages(cachedResourceLoader);
-        return StyleGeneratedImage::create(imageGeneratorValue);
-    }
-
-    if (pendingImage->cssCursorImageValue()) {
-        CSSCursorImageValue* cursorImageValue = pendingImage->cssCursorImageValue();
-        return cursorImageValue->cachedImage(cachedResourceLoader);
-    }
-
-    if (pendingImage->cssImageSetValue()) {
-        CSSImageSetValue* imageSetValue = pendingImage->cssImageSetValue();
-        return imageSetValue->cachedImageSet(cachedResourceLoader);
-    }
-
-    return 0;
-}
-
-void StyleResolver::loadPendingImages()
-{
-    if (m_state.pendingImageProperties().isEmpty())
-        return;
-
-    PendingImagePropertyMap::const_iterator::Keys end = m_state.pendingImageProperties().end().keys();
-    for (PendingImagePropertyMap::const_iterator::Keys it = m_state.pendingImageProperties().begin().keys(); it != end; ++it) {
-        CSSPropertyID currentProperty = *it;
-
-        switch (currentProperty) {
-        case CSSPropertyBackgroundImage: {
-            for (FillLayer* backgroundLayer = m_state.style()->accessBackgroundLayers(); backgroundLayer; backgroundLayer = backgroundLayer->next()) {
-                if (backgroundLayer->image() && backgroundLayer->image()->isPendingImage())
-                    backgroundLayer->setImage(loadPendingImage(static_cast<StylePendingImage*>(backgroundLayer->image())));
-            }
-            break;
-        }
-        case CSSPropertyContent: {
-            for (ContentData* contentData = const_cast<ContentData*>(m_state.style()->contentData()); contentData; contentData = contentData->next()) {
-                if (contentData->isImage()) {
-                    StyleImage* image = static_cast<ImageContentData*>(contentData)->image();
-                    if (image->isPendingImage()) {
-                        RefPtr<StyleImage> loadedImage = loadPendingImage(static_cast<StylePendingImage*>(image));
-                        if (loadedImage)
-                            static_cast<ImageContentData*>(contentData)->setImage(loadedImage.release());
-                    }
-                }
-            }
-            break;
-        }
-        case CSSPropertyCursor: {
-            if (CursorList* cursorList = m_state.style()->cursors()) {
-                for (size_t i = 0; i < cursorList->size(); ++i) {
-                    CursorData& currentCursor = cursorList->at(i);
-                    if (StyleImage* image = currentCursor.image()) {
-                        if (image->isPendingImage())
-                            currentCursor.setImage(loadPendingImage(static_cast<StylePendingImage*>(image)));
-                    }
-                }
-            }
-            break;
-        }
-        case CSSPropertyListStyleImage: {
-            if (m_state.style()->listStyleImage() && m_state.style()->listStyleImage()->isPendingImage())
-                m_state.style()->setListStyleImage(loadPendingImage(static_cast<StylePendingImage*>(m_state.style()->listStyleImage())));
-            break;
-        }
-        case CSSPropertyBorderImageSource: {
-            if (m_state.style()->borderImageSource() && m_state.style()->borderImageSource()->isPendingImage())
-                m_state.style()->setBorderImageSource(loadPendingImage(static_cast<StylePendingImage*>(m_state.style()->borderImageSource())));
-            break;
-        }
-        case CSSPropertyWebkitBoxReflect: {
-            if (StyleReflection* reflection = m_state.style()->boxReflect()) {
-                const NinePieceImage& maskImage = reflection->mask();
-                if (maskImage.image() && maskImage.image()->isPendingImage()) {
-                    RefPtr<StyleImage> loadedImage = loadPendingImage(static_cast<StylePendingImage*>(maskImage.image()));
-                    reflection->setMask(NinePieceImage(loadedImage.release(), maskImage.imageSlices(), maskImage.fill(), maskImage.borderSlices(), maskImage.outset(), maskImage.horizontalRule(), maskImage.verticalRule()));
-                }
-            }
-            break;
-        }
-        case CSSPropertyWebkitMaskBoxImageSource: {
-            if (m_state.style()->maskBoxImageSource() && m_state.style()->maskBoxImageSource()->isPendingImage())
-                m_state.style()->setMaskBoxImageSource(loadPendingImage(static_cast<StylePendingImage*>(m_state.style()->maskBoxImageSource())));
-            break;
-        }
-        case CSSPropertyWebkitMaskImage: {
-            for (FillLayer* maskLayer = m_state.style()->accessMaskLayers(); maskLayer; maskLayer = maskLayer->next()) {
-                if (maskLayer->image() && maskLayer->image()->isPendingImage())
-                    maskLayer->setImage(loadPendingImage(static_cast<StylePendingImage*>(maskLayer->image())));
-            }
-            break;
-        }
-        case CSSPropertyWebkitShapeInside:
-            if (m_state.style()->shapeInside() && m_state.style()->shapeInside()->image() && m_state.style()->shapeInside()->image()->isPendingImage())
-                m_state.style()->shapeInside()->setImage(loadPendingImage(static_cast<StylePendingImage*>(m_state.style()->shapeInside()->image())));
-            break;
-        case CSSPropertyWebkitShapeOutside:
-            if (m_state.style()->shapeOutside() && m_state.style()->shapeOutside()->image() && m_state.style()->shapeOutside()->image()->isPendingImage())
-                m_state.style()->shapeOutside()->setImage(loadPendingImage(static_cast<StylePendingImage*>(m_state.style()->shapeOutside()->image())));
-            break;
-        default:
-            ASSERT_NOT_REACHED();
-        }
-    }
-
-    m_state.pendingImageProperties().clear();
-}
-
-void StyleResolver::loadPendingResources()
-{
-    // Start loading images referenced by this style.
-    loadPendingImages();
-
-    // Start loading the shaders referenced by this style.
-    loadPendingShaders();
-
-    // Start loading the SVG Documents referenced by this style.
-    loadPendingSVGDocuments();
-}
-
 inline StyleResolver::MatchedProperties::MatchedProperties()
     : possiblyPaddedMember(0)
 {
diff --git a/Source/core/css/resolver/StyleResolver.h b/Source/core/css/resolver/StyleResolver.h
index a8013e7..ff1a28b 100644
--- a/Source/core/css/resolver/StyleResolver.h
+++ b/Source/core/css/resolver/StyleResolver.h
@@ -24,9 +24,7 @@
 
 #include "RuntimeEnabledFeatures.h"
 #include "core/css/CSSRuleList.h"
-#include "core/css/CSSSVGDocumentValue.h"
 #include "core/css/CSSToStyleMap.h"
-#include "core/css/CSSValueList.h"
 #include "core/css/DocumentRuleSets.h"
 #include "core/css/InspectorCSSOMWrappers.h"
 #include "core/css/MediaQueryExp.h"
@@ -38,17 +36,13 @@
 #include "core/css/SiblingTraversalStrategies.h"
 #include "core/css/resolver/ScopedStyleResolver.h"
 #include "core/css/resolver/StyleResolverState.h"
+#include "core/css/resolver/StyleResourceLoader.h"
 #include "core/css/resolver/ViewportStyleResolver.h"
-#include "core/platform/LinkHash.h"
-#include "core/platform/ScrollTypes.h"
-#include "core/platform/graphics/filters/custom/CustomFilterConstants.h"
 #include "core/rendering/style/RenderStyle.h"
 #include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
 #include "wtf/RefPtr.h"
 #include "wtf/Vector.h"
-#include "wtf/text/AtomicStringHash.h"
-#include "wtf/text/StringHash.h"
 
 namespace WebCore {
 
@@ -79,7 +73,6 @@
 class RuleData;
 class RuleSet;
 class Settings;
-class StyleCustomFilterProgramCache;
 class StyleImage;
 class StyleKeyframe;
 class StylePendingImage;
@@ -92,7 +85,6 @@
 class StyleShader;
 class StyleSheet;
 class StyleSheetList;
-class StyledElement;
 
 class MediaQueryResult {
     WTF_MAKE_NONCOPYABLE(MediaQueryResult); WTF_MAKE_FAST_ALLOCATED;
@@ -128,12 +120,19 @@
     MatchRequest(RuleSet* ruleSet, bool includeEmptyRules = false, const ContainerNode* scope = 0)
         : ruleSet(ruleSet)
         , includeEmptyRules(includeEmptyRules)
-        , scope(scope) { }
+        , scope(scope)
+    {
+        // Now that we're about to read from the RuleSet, we're done adding more
+        // rules to the set and we should make sure it's compacted.
+        ruleSet->compactRulesIfNeeded();
+    }
+
     const RuleSet* ruleSet;
     const bool includeEmptyRules;
     const ContainerNode* scope;
 };
 
+
 // This class selects a RenderStyle for a given element based on a collection of stylesheets.
 class StyleResolver {
     WTF_MAKE_NONCOPYABLE(StyleResolver); WTF_MAKE_FAST_ALLOCATED;
@@ -160,9 +159,9 @@
 
     static PassRefPtr<RenderStyle> styleForDocument(Document*, CSSFontSelector* = 0);
 
-    Color colorFromPrimitiveValue(CSSPrimitiveValue* value, bool forVisitedLink = false) const
+    Color resolveColorFromPrimitiveValue(CSSPrimitiveValue* value, bool forVisitedLink = false)
     {
-        return m_state.colorFromPrimitiveValue(value, forVisitedLink);
+        return m_state.resolveColorFromPrimitiveValue(value, forVisitedLink);
     }
     RenderStyle* style() const { return m_state.style(); }
     RenderStyle* parentStyle() const { return m_state.parentStyle(); }
@@ -174,24 +173,29 @@
     // FIXME: It could be better to call m_ruleSets.appendAuthorStyleSheets() directly after we factor StyleRsolver further.
     // https://bugs.webkit.org/show_bug.cgi?id=108890
     void appendAuthorStyleSheets(unsigned firstNew, const Vector<RefPtr<CSSStyleSheet> >&);
+    // FIXME: resetAuthorStyle() will be removed when rulesets are reset in a per-scoping node manner.
     void resetAuthorStyle();
+    void resetAuthorStyle(const ContainerNode*);
+    void resetAtHostRules(const ContainerNode*);
 
     DocumentRuleSets& ruleSets() { return m_ruleSets; }
     const DocumentRuleSets& ruleSets() const { return m_ruleSets; }
     SelectorFilter& selectorFilter() { return m_selectorFilter; }
 
+    void setBuildScopedStyleTreeInDocumentOrder(bool enabled) { m_styleTree.setBuildInDocumentOrder(enabled); }
+    bool buildScopedStyleTreeInDocumentOrder() const { return m_styleTree.buildInDocumentOrder(); }
+
     ScopedStyleResolver* ensureScopedStyleResolver(const ContainerNode* scope)
     {
         return m_styleTree.ensureScopedStyleResolver(scope ? scope : document());
     }
 
 private:
-    void initElement(Element*);
     RenderStyle* locateSharedStyle();
     bool styleSharingCandidateMatchesRuleSet(RuleSet*);
     Node* locateCousinList(Element* parent, unsigned& visitedNodeCount) const;
-    StyledElement* findSiblingForStyleSharing(Node*, unsigned& count) const;
-    bool canShareStyleWithElement(StyledElement*) const;
+    Element* findSiblingForStyleSharing(Node*, unsigned& count) const;
+    bool canShareStyleWithElement(Element*) const;
 
     PassRefPtr<RenderStyle> styleForKeyframe(const RenderStyle*, const StyleKeyframe*, KeyframeValue&);
 
@@ -220,8 +224,6 @@
 public:
     bool useSVGZoomRules();
 
-    static bool colorFromPrimitiveValueIsDerivedFromElement(CSSPrimitiveValue*);
-
     bool hasSelectorForId(const AtomicString&) const;
     bool hasSelectorForClass(const AtomicString&) const;
     bool hasSelectorForAttribute(const AtomicString&) const;
@@ -243,11 +245,6 @@
 
     void invalidateMatchedPropertiesCache();
 
-    void loadPendingShaders();
-    void loadPendingSVGDocuments();
-
-    void loadPendingResources();
-
     struct RuleRange {
         RuleRange(int& firstRuleIndex, int& lastRuleIndex): firstRuleIndex(firstRuleIndex), lastRuleIndex(lastRuleIndex) { }
         int& firstRuleIndex;
@@ -375,15 +372,12 @@
     void cacheBorderAndBackground();
 
 private:
-    bool canShareStyleWithControl(StyledElement*) const;
+    bool canShareStyleWithControl(Element*) const;
 
     void applyProperty(CSSPropertyID, CSSValue*);
 
     void applySVGProperty(CSSPropertyID, CSSValue*);
 
-    PassRefPtr<StyleImage> loadPendingImage(StylePendingImage*);
-    void loadPendingImages();
-
     struct MatchedPropertiesCacheItem {
         void reportMemoryUsage(MemoryObjectInfo*) const;
         Vector<MatchedProperties> matchedProperties;
@@ -399,7 +393,7 @@
     void sweepMatchedPropertiesCache(Timer<StyleResolver>*);
 
     bool classNamesAffectedByRules(const SpaceSplitString&) const;
-    bool sharingCandidateHasIdenticalStyleAffectingAttributes(StyledElement*) const;
+    bool sharingCandidateHasIdenticalStyleAffectingAttributes(Element*) const;
 
     unsigned m_matchedPropertiesCacheAdditionsSinceLastSweep;
 
@@ -432,8 +426,7 @@
     InspectorCSSOMWrappers m_inspectorCSSOMWrappers;
 
     StyleResolverState m_state;
-
-    OwnPtr<StyleCustomFilterProgramCache> m_customFilterProgramCache;
+    StyleResourceLoader m_styleResourceLoader;
 
     friend class DeprecatedStyleBuilder;
     friend bool operator==(const MatchedProperties&, const MatchedProperties&);
diff --git a/Source/core/css/resolver/StyleResolverState.cpp b/Source/core/css/resolver/StyleResolverState.cpp
index ecdf471..a355f8e 100644
--- a/Source/core/css/resolver/StyleResolverState.cpp
+++ b/Source/core/css/resolver/StyleResolverState.cpp
@@ -22,12 +22,12 @@
 #include "config.h"
 #include "core/css/resolver/StyleResolverState.h"
 
-#include "core/css/CSSPrimitiveValueMappings.h"
+#include "core/dom/Element.h"
 #include "core/dom/Node.h"
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/NodeRenderingContext.h"
-#include "core/dom/StyledElement.h"
 #include "core/dom/VisitedLinkState.h"
+#include "core/page/Page.h"
 #include "core/rendering/RenderTheme.h"
 
 namespace WebCore {
@@ -49,20 +49,29 @@
     m_parentStyle = 0;
     m_parentNode = 0;
     m_regionForStyling = 0;
-    m_pendingImageProperties.clear();
-    m_hasPendingShaders = false;
-    m_pendingSVGDocuments.clear();
+    m_elementStyleResources.clear();
 }
 
-void StyleResolverState::initElement(Element* e)
+void StyleResolverState::initElement(Element* element)
 {
-    m_element = e;
-    m_styledElement = e && e->isStyledElement() ? static_cast<StyledElement*>(e) : 0;
-    m_elementLinkState = e ? e->document()->visitedLinkState()->determineLinkState(e) : NotInsideLink;
+    if (m_element == element)
+        return;
+
+    m_element = element;
+    m_styledElement = element && element->isStyledElement() ? element : 0;
+    m_elementLinkState = element ? element->document()->visitedLinkState()->determineLinkState(element) : NotInsideLink;
+
+    if (!element || element != element->document()->documentElement())
+        return;
+
+    element->document()->setDirectionSetOnDocumentElement(false);
+    element->document()->setWritingModeSetOnDocumentElement(false);
 }
 
 void StyleResolverState::initForStyleResolve(Document* document, Element* e, RenderStyle* parentStyle, RenderRegion* regionForStyling)
 {
+    initElement(e);
+
     m_regionForStyling = regionForStyling;
 
     if (e) {
@@ -83,8 +92,11 @@
     m_rootElementStyle = docElement && e != docElement ? docElement->renderStyle() : docStyle;
 
     m_style = 0;
-    m_pendingImageProperties.clear();
+    m_elementStyleResources.clear();
     m_fontDirty = false;
+
+    if (Page* page = document->page())
+        m_elementStyleResources.setDeviceScaleFactor(page->deviceScaleFactor());
 }
 
 
@@ -125,7 +137,7 @@
     return RenderTheme::defaultTheme()->systemColor(cssValueId);
 }
 
-Color StyleResolverState::colorFromPrimitiveValue(CSSPrimitiveValue* value, bool forVisitedLink) const
+Color StyleResolverState::resolveColorFromPrimitiveValue(CSSPrimitiveValue* value, bool forVisitedLink)
 {
     if (value->isRGBColor())
         return Color(value->getRGBA32Value());
@@ -143,11 +155,11 @@
     case CSSValueWebkitFocusRingColor:
         return RenderTheme::focusRingColor();
     case CSSValueCurrentcolor:
+        m_isMatchedPropertiesCacheable = false;
         return style()->color();
     default:
         return colorForCSSValue(valueID);
     }
 }
 
-
 } // namespace WebCore
diff --git a/Source/core/css/resolver/StyleResolverState.h b/Source/core/css/resolver/StyleResolverState.h
index 4084290..c181b57 100644
--- a/Source/core/css/resolver/StyleResolverState.h
+++ b/Source/core/css/resolver/StyleResolverState.h
@@ -25,10 +25,9 @@
 #include "CSSPropertyNames.h"
 
 #include "core/css/CSSSVGDocumentValue.h"
-#include "core/css/CSSValueList.h"
+#include "core/css/resolver/ElementStyleResources.h"
 #include "core/dom/Element.h"
 #include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/filters/FilterOperations.h"
 #include "core/rendering/style/BorderData.h"
 #include "core/rendering/style/FillLayer.h"
 #include "core/rendering/style/RenderStyle.h"
@@ -40,10 +39,6 @@
 class FillLayer;
 class FontDescription;
 class RenderRegion;
-class StyledElement;
-
-typedef HashMap<CSSPropertyID, RefPtr<CSSValue> > PendingImagePropertyMap;
-typedef HashMap<FilterOperation*, RefPtr<CSSSVGDocumentValue> > PendingSVGDocumentMap;
 
 class StyleResolverState {
 WTF_MAKE_NONCOPYABLE(StyleResolverState);
@@ -60,22 +55,22 @@
     , m_elementAffectedByClassRules(false)
     , m_applyPropertyToRegularStyle(true)
     , m_applyPropertyToVisitedLinkStyle(false)
-    , m_hasPendingShaders(false)
+    , m_isMatchedPropertiesCacheable(true)
     , m_lineHeightValue(0)
     , m_fontDirty(false)
     , m_hasUAAppearance(false)
     , m_backgroundData(BackgroundFillLayer) { }
 
-    public:
-    void initElement(Element*);
+public:
     void initForStyleResolve(Document*, Element*, RenderStyle* parentStyle = 0, RenderRegion* regionForStyling = 0);
     void clear();
 
-    Color colorFromPrimitiveValue(CSSPrimitiveValue*, bool forVisitedLink = false) const;
+    // This method might change an internal state, i.e. m_isMatchedPropertiesCachable.
+    Color resolveColorFromPrimitiveValue(CSSPrimitiveValue*, bool forVisitedLink = false);
 
     Document* document() const { return m_element->document(); }
     Element* element() const { return m_element; }
-    StyledElement* styledElement() const { return m_styledElement; }
+    Element* styledElement() const { return m_styledElement; }
     void setStyle(PassRefPtr<RenderStyle> style) { m_style = style; }
     RenderStyle* style() const { return m_style.get(); }
     PassRefPtr<RenderStyle> takeStyle() { return m_style.release(); }
@@ -95,10 +90,7 @@
     void setApplyPropertyToVisitedLinkStyle(bool isApply) { m_applyPropertyToVisitedLinkStyle = isApply; }
     bool applyPropertyToRegularStyle() const { return m_applyPropertyToRegularStyle; }
     bool applyPropertyToVisitedLinkStyle() const { return m_applyPropertyToVisitedLinkStyle; }
-    PendingImagePropertyMap& pendingImageProperties() { return m_pendingImageProperties; }
-    PendingSVGDocumentMap& pendingSVGDocuments() { return m_pendingSVGDocuments; }
-    void setHasPendingShaders(bool hasPendingShaders) { m_hasPendingShaders = hasPendingShaders; }
-    bool hasPendingShaders() const { return m_hasPendingShaders; }
+    bool isMatchedPropertiesCacheable() const { return m_isMatchedPropertiesCacheable; }
 
     void setLineHeightValue(CSSValue* value) { m_lineHeightValue = value; }
     CSSValue* lineHeightValue() { return m_lineHeightValue; }
@@ -110,6 +102,7 @@
     BorderData borderData() const { return m_borderData; }
     FillLayer backgroundData() const { return m_backgroundData; }
     Color backgroundColor() const { return m_backgroundColor; }
+    ElementStyleResources& elementStyleResources() { return m_elementStyleResources; }
 
     const FontDescription& fontDescription() { return m_style->fontDescription(); }
     const FontDescription& parentFontDescription() { return m_parentStyle->fontDescription(); }
@@ -119,12 +112,22 @@
     void setWritingMode(WritingMode writingMode) { m_fontDirty |= m_style->setWritingMode(writingMode); }
     void setTextOrientation(TextOrientation textOrientation) { m_fontDirty |= m_style->setTextOrientation(textOrientation); }
 
+    // SVG handles zooming in a different way compared to CSS. The whole document is scaled instead
+    // of each individual length value in the render style / tree. CSSPrimitiveValue::computeLength*()
+    // multiplies each resolved length with the zoom multiplier - so for SVG we need to disable that.
+    // Though all CSS values that can be applied to outermost <svg> elements (width/height/border/padding...)
+    // need to respect the scaling. RenderBox (the parent class of RenderSVGRoot) grabs values like
+    // width/height/border/padding/... from the RenderStyle -> for SVG these values would never scale,
+    // if we'd pass a 1.0 zoom factor everyhwere. So we only pass a zoom factor of 1.0 for specific
+    // properties that are NOT allowed to scale within a zoomed SVG document (letter/word-spacing/font-size).
     bool useSVGZoomRules() const { return m_element && m_element->isSVGElement(); }
 
 private:
+    void initElement(Element*);
+
     Element* m_element;
     RefPtr<RenderStyle> m_style;
-    StyledElement* m_styledElement;
+    Element* m_styledElement;
     ContainerNode* m_parentNode;
     RefPtr<RenderStyle> m_parentStyle;
     RenderStyle* m_rootElementStyle;
@@ -140,10 +143,8 @@
 
     bool m_applyPropertyToRegularStyle;
     bool m_applyPropertyToVisitedLinkStyle;
+    bool m_isMatchedPropertiesCacheable;
 
-    PendingImagePropertyMap m_pendingImageProperties;
-    bool m_hasPendingShaders;
-    PendingSVGDocumentMap m_pendingSVGDocuments;
     CSSValue* m_lineHeightValue;
     bool m_fontDirty;
 
@@ -151,6 +152,7 @@
     BorderData m_borderData;
     FillLayer m_backgroundData;
     Color m_backgroundColor;
+    ElementStyleResources m_elementStyleResources;
 };
 
 } // namespace WebCore
diff --git a/Source/core/css/resolver/StyleResourceLoader.cpp b/Source/core/css/resolver/StyleResourceLoader.cpp
new file mode 100644
index 0000000..dabbbbc
--- /dev/null
+++ b/Source/core/css/resolver/StyleResourceLoader.cpp
@@ -0,0 +1,259 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#include "config.h"
+#include "core/css/resolver/StyleResourceLoader.h"
+
+#include "CSSPropertyNames.h"
+#include "core/css/CSSCursorImageValue.h"
+#include "core/css/CSSImageValue.h"
+#include "core/css/CSSSVGDocumentValue.h"
+#include "core/css/CSSShaderValue.h"
+#include "core/css/resolver/ElementStyleResources.h"
+#include "core/loader/cache/CachedResourceLoader.h"
+#include "core/platform/graphics/filters/custom/CustomFilterOperation.h"
+#include "core/rendering/style/ContentData.h"
+#include "core/rendering/style/CursorList.h"
+#include "core/rendering/style/FillLayer.h"
+#include "core/rendering/style/RenderStyle.h"
+#include "core/rendering/style/StyleCachedImage.h"
+#include "core/rendering/style/StyleCachedImageSet.h"
+#include "core/rendering/style/StyleCachedShader.h"
+#include "core/rendering/style/StyleCustomFilterProgram.h"
+#include "core/rendering/style/StyleCustomFilterProgramCache.h"
+#include "core/rendering/style/StyleGeneratedImage.h"
+#include "core/rendering/style/StylePendingImage.h"
+#include "core/rendering/style/StylePendingShader.h"
+
+namespace WebCore {
+
+StyleResourceLoader::StyleResourceLoader(CachedResourceLoader* cachedResourceLoader)
+    : m_cachedResourceLoader(cachedResourceLoader)
+    , m_customFilterProgramCache(StyleCustomFilterProgramCache::create())
+{
+}
+
+void StyleResourceLoader::loadPendingSVGDocuments(RenderStyle* renderStyle, const ElementStyleResources& elementStyleResources)
+{
+    if (!renderStyle->hasFilter() || elementStyleResources.pendingSVGDocuments().isEmpty())
+        return;
+
+    Vector<RefPtr<FilterOperation> >& filterOperations = renderStyle->mutableFilter().operations();
+    for (unsigned i = 0; i < filterOperations.size(); ++i) {
+        RefPtr<FilterOperation> filterOperation = filterOperations.at(i);
+        if (filterOperation->getOperationType() == FilterOperation::REFERENCE) {
+            ReferenceFilterOperation* referenceFilter = static_cast<ReferenceFilterOperation*>(filterOperation.get());
+
+            CSSSVGDocumentValue* value = elementStyleResources.pendingSVGDocuments().get(referenceFilter);
+            if (!value)
+                continue;
+            CachedDocument* cachedDocument = value->load(m_cachedResourceLoader);
+            if (!cachedDocument)
+                continue;
+
+            // Stash the CachedDocument on the reference filter.
+            referenceFilter->setCachedSVGDocumentReference(adoptPtr(new CachedSVGDocumentReference(cachedDocument)));
+        }
+    }
+}
+
+PassRefPtr<StyleImage> StyleResourceLoader::loadPendingImage(StylePendingImage* pendingImage, float deviceScaleFactor)
+{
+    if (pendingImage->cssImageValue()) {
+        CSSImageValue* imageValue = pendingImage->cssImageValue();
+        return imageValue->cachedImage(m_cachedResourceLoader);
+    }
+
+    if (pendingImage->cssImageGeneratorValue()) {
+        CSSImageGeneratorValue* imageGeneratorValue = pendingImage->cssImageGeneratorValue();
+        imageGeneratorValue->loadSubimages(m_cachedResourceLoader);
+        return StyleGeneratedImage::create(imageGeneratorValue);
+    }
+
+    if (pendingImage->cssCursorImageValue()) {
+        CSSCursorImageValue* cursorImageValue = pendingImage->cssCursorImageValue();
+        return cursorImageValue->cachedImage(m_cachedResourceLoader, deviceScaleFactor);
+    }
+
+    if (pendingImage->cssImageSetValue()) {
+        CSSImageSetValue* imageSetValue = pendingImage->cssImageSetValue();
+        return imageSetValue->cachedImageSet(m_cachedResourceLoader, deviceScaleFactor);
+    }
+
+    return 0;
+}
+
+void StyleResourceLoader::loadPendingShapeImage(RenderStyle* renderStyle, ShapeValue* shapeValue)
+{
+    if (!shapeValue)
+        return;
+
+    StyleImage* image = shapeValue->image();
+    if (!image || !image->isPendingImage())
+        return;
+
+    StylePendingImage* pendingImage = static_cast<StylePendingImage*>(image);
+    CSSImageValue* cssImageValue =  pendingImage->cssImageValue();
+
+    ResourceLoaderOptions options = CachedResourceLoader::defaultCachedResourceOptions();
+    options.requestOriginPolicy = RestrictToSameOrigin;
+
+    shapeValue->setImage(cssImageValue->cachedImage(m_cachedResourceLoader, options));
+}
+
+void StyleResourceLoader::loadPendingImages(RenderStyle* style, const ElementStyleResources& elementStyleResources)
+{
+    if (elementStyleResources.pendingImageProperties().isEmpty())
+        return;
+
+    PendingImagePropertyMap::const_iterator::Keys end = elementStyleResources.pendingImageProperties().end().keys();
+    for (PendingImagePropertyMap::const_iterator::Keys it = elementStyleResources.pendingImageProperties().begin().keys(); it != end; ++it) {
+        CSSPropertyID currentProperty = *it;
+
+        switch (currentProperty) {
+        case CSSPropertyBackgroundImage: {
+            for (FillLayer* backgroundLayer = style->accessBackgroundLayers(); backgroundLayer; backgroundLayer = backgroundLayer->next()) {
+                if (backgroundLayer->image() && backgroundLayer->image()->isPendingImage())
+                    backgroundLayer->setImage(loadPendingImage(static_cast<StylePendingImage*>(backgroundLayer->image()), elementStyleResources.deviceScaleFactor()));
+            }
+            break;
+        }
+        case CSSPropertyContent: {
+            for (ContentData* contentData = const_cast<ContentData*>(style->contentData()); contentData; contentData = contentData->next()) {
+                if (contentData->isImage()) {
+                    StyleImage* image = static_cast<ImageContentData*>(contentData)->image();
+                    if (image->isPendingImage()) {
+                        RefPtr<StyleImage> loadedImage = loadPendingImage(static_cast<StylePendingImage*>(image), elementStyleResources.deviceScaleFactor());
+                        if (loadedImage)
+                            static_cast<ImageContentData*>(contentData)->setImage(loadedImage.release());
+                    }
+                }
+            }
+            break;
+        }
+        case CSSPropertyCursor: {
+            if (CursorList* cursorList = style->cursors()) {
+                for (size_t i = 0; i < cursorList->size(); ++i) {
+                    CursorData& currentCursor = cursorList->at(i);
+                    if (StyleImage* image = currentCursor.image()) {
+                        if (image->isPendingImage())
+                            currentCursor.setImage(loadPendingImage(static_cast<StylePendingImage*>(image), elementStyleResources.deviceScaleFactor()));
+                    }
+                }
+            }
+            break;
+        }
+        case CSSPropertyListStyleImage: {
+            if (style->listStyleImage() && style->listStyleImage()->isPendingImage())
+                style->setListStyleImage(loadPendingImage(static_cast<StylePendingImage*>(style->listStyleImage()), elementStyleResources.deviceScaleFactor()));
+            break;
+        }
+        case CSSPropertyBorderImageSource: {
+            if (style->borderImageSource() && style->borderImageSource()->isPendingImage())
+                style->setBorderImageSource(loadPendingImage(static_cast<StylePendingImage*>(style->borderImageSource()), elementStyleResources.deviceScaleFactor()));
+            break;
+        }
+        case CSSPropertyWebkitBoxReflect: {
+            if (StyleReflection* reflection = style->boxReflect()) {
+                const NinePieceImage& maskImage = reflection->mask();
+                if (maskImage.image() && maskImage.image()->isPendingImage()) {
+                    RefPtr<StyleImage> loadedImage = loadPendingImage(static_cast<StylePendingImage*>(maskImage.image()), elementStyleResources.deviceScaleFactor());
+                    reflection->setMask(NinePieceImage(loadedImage.release(), maskImage.imageSlices(), maskImage.fill(), maskImage.borderSlices(), maskImage.outset(), maskImage.horizontalRule(), maskImage.verticalRule()));
+                }
+            }
+            break;
+        }
+        case CSSPropertyWebkitMaskBoxImageSource: {
+            if (style->maskBoxImageSource() && style->maskBoxImageSource()->isPendingImage())
+                style->setMaskBoxImageSource(loadPendingImage(static_cast<StylePendingImage*>(style->maskBoxImageSource()), elementStyleResources.deviceScaleFactor()));
+            break;
+        }
+        case CSSPropertyWebkitMaskImage: {
+            for (FillLayer* maskLayer = style->accessMaskLayers(); maskLayer; maskLayer = maskLayer->next()) {
+                if (maskLayer->image() && maskLayer->image()->isPendingImage())
+                    maskLayer->setImage(loadPendingImage(static_cast<StylePendingImage*>(maskLayer->image()), elementStyleResources.deviceScaleFactor()));
+            }
+            break;
+        }
+        case CSSPropertyWebkitShapeInside:
+            loadPendingShapeImage(style, style->shapeInside());
+            break;
+        case CSSPropertyWebkitShapeOutside:
+            loadPendingShapeImage(style, style->shapeOutside());
+            break;
+        default:
+            ASSERT_NOT_REACHED();
+        }
+    }
+}
+
+void StyleResourceLoader::loadPendingShaders(RenderStyle* style, const ElementStyleResources& elementStyleResources)
+{
+    if (!style->hasFilter() || !elementStyleResources.hasPendingShaders())
+        return;
+
+    Vector<RefPtr<FilterOperation> >& filterOperations = style->mutableFilter().operations();
+    for (unsigned i = 0; i < filterOperations.size(); ++i) {
+        RefPtr<FilterOperation> filterOperation = filterOperations.at(i);
+        if (filterOperation->getOperationType() == FilterOperation::CUSTOM) {
+            CustomFilterOperation* customFilter = static_cast<CustomFilterOperation*>(filterOperation.get());
+            ASSERT(customFilter->program());
+            StyleCustomFilterProgram* program = static_cast<StyleCustomFilterProgram*>(customFilter->program());
+            // Note that the StylePendingShaders could be already resolved to StyleCachedShaders. That's because the rule was matched before.
+            // However, the StyleCustomFilterProgram that was initially created could have been removed from the cache in the meanwhile,
+            // meaning that we get a new StyleCustomFilterProgram here that is not yet in the cache, but already has loaded StyleShaders.
+            if (!program->hasPendingShaders() && program->inCache())
+                continue;
+            RefPtr<StyleCustomFilterProgram> styleProgram = m_customFilterProgramCache->lookup(program);
+            if (styleProgram.get()) {
+                customFilter->setProgram(styleProgram.release());
+            } else {
+                if (program->vertexShader() && program->vertexShader()->isPendingShader()) {
+                    CSSShaderValue* shaderValue = static_cast<StylePendingShader*>(program->vertexShader())->cssShaderValue();
+                    program->setVertexShader(shaderValue->cachedShader(m_cachedResourceLoader));
+                }
+                if (program->fragmentShader() && program->fragmentShader()->isPendingShader()) {
+                    CSSShaderValue* shaderValue = static_cast<StylePendingShader*>(program->fragmentShader())->cssShaderValue();
+                    program->setFragmentShader(shaderValue->cachedShader(m_cachedResourceLoader));
+                }
+                m_customFilterProgramCache->add(program);
+            }
+        }
+    }
+}
+
+void StyleResourceLoader::loadPendingResources(RenderStyle* renderStyle, ElementStyleResources& elementStyleResources)
+{
+    // Start loading images referenced by this style.
+    loadPendingImages(renderStyle, elementStyleResources);
+
+    // Start loading the shaders referenced by this style.
+    loadPendingShaders(renderStyle, elementStyleResources);
+
+    // Start loading the SVG Documents referenced by this style.
+    loadPendingSVGDocuments(renderStyle, elementStyleResources);
+
+    // FIXME: Investigate if this clearing is necessary.
+    elementStyleResources.clear();
+}
+
+}
diff --git a/Source/core/css/resolver/StyleResourceLoader.h b/Source/core/css/resolver/StyleResourceLoader.h
new file mode 100644
index 0000000..0bf75d0
--- /dev/null
+++ b/Source/core/css/resolver/StyleResourceLoader.h
@@ -0,0 +1,65 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 Apple Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef StyleResourceLoader_h
+#define StyleResourceLoader_h
+
+#include "wtf/OwnPtr.h"
+#include "wtf/PassRefPtr.h"
+
+namespace WebCore {
+
+class ElementStyleResources;
+class CachedResourceLoader;
+class RenderStyle;
+class ShapeValue;
+class StyleImage;
+class StylePendingImage;
+class StyleCustomFilterProgramCache;
+
+// Manages loading of resources, requested by the stylesheets.
+// Expects the same lifetime as StyleResolver, because:
+// 1) it expects CachedResourceLoader to never change, and
+// 2) it also holds the StyleCustomFilterProgramCache.
+class StyleResourceLoader {
+WTF_MAKE_NONCOPYABLE(StyleResourceLoader);
+public:
+    explicit StyleResourceLoader(CachedResourceLoader*);
+
+    void loadPendingResources(RenderStyle*, ElementStyleResources&);
+    StyleCustomFilterProgramCache* customFilterProgramCache() const { return m_customFilterProgramCache.get(); }
+
+private:
+    void loadPendingSVGDocuments(RenderStyle*, const ElementStyleResources&);
+    void loadPendingShaders(RenderStyle*, const ElementStyleResources&);
+
+    PassRefPtr<StyleImage> loadPendingImage(StylePendingImage*, float deviceScaleFactor);
+    void loadPendingImages(RenderStyle*, const ElementStyleResources&);
+    void loadPendingShapeImage(RenderStyle*, ShapeValue*);
+
+    OwnPtr<StyleCustomFilterProgramCache> m_customFilterProgramCache;
+    CachedResourceLoader* m_cachedResourceLoader;
+};
+
+} // namespace WebCore
+
+#endif // StyleResourceLoader_h
diff --git a/Source/core/css/resolver/ViewportStyleResolver.cpp b/Source/core/css/resolver/ViewportStyleResolver.cpp
index 7d2fce1..cc22bcf 100644
--- a/Source/core/css/resolver/ViewportStyleResolver.cpp
+++ b/Source/core/css/resolver/ViewportStyleResolver.cpp
@@ -36,8 +36,6 @@
 #include "core/dom/Document.h"
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/ViewportArguments.h"
-#include "core/page/Page.h"
-#include "core/rendering/RenderView.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/resolver/ViewportStyleResolver.h b/Source/core/css/resolver/ViewportStyleResolver.h
index 6699561..a523bc5 100644
--- a/Source/core/css/resolver/ViewportStyleResolver.h
+++ b/Source/core/css/resolver/ViewportStyleResolver.h
@@ -31,7 +31,6 @@
 #define ViewportStyleResolver_h
 
 #include "CSSPropertyNames.h"
-#include "core/platform/graphics/FloatSize.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
 
diff --git a/Source/core/css/themeWin.css b/Source/core/css/themeWin.css
index 1bb96fa..b7a6f0b 100644
--- a/Source/core/css/themeWin.css
+++ b/Source/core/css/themeWin.css
@@ -120,6 +120,10 @@
     font: inherit !important;
 }
 
+select:disabled option:checked, option:disabled:checked {
+    color: #d2d2d2
+}
+
 textarea {
   font-family: monospace;
 }
diff --git a/Source/core/dom/ActiveDOMObject.cpp b/Source/core/dom/ActiveDOMObject.cpp
index a3270fc..c2008aa 100644
--- a/Source/core/dom/ActiveDOMObject.cpp
+++ b/Source/core/dom/ActiveDOMObject.cpp
@@ -33,7 +33,7 @@
 namespace WebCore {
 
 ActiveDOMObject::ActiveDOMObject(ScriptExecutionContext* scriptExecutionContext)
-    : ContextDestructionObserver(scriptExecutionContext)
+    : ContextLifecycleObserver(scriptExecutionContext, ActiveDOMObjectType)
     , m_pendingActivityCount(0)
 #if !ASSERT_DISABLED
     , m_suspendIfNeededCalled(false)
@@ -43,26 +43,22 @@
         return;
 
     ASSERT(m_scriptExecutionContext->isContextThread());
-    m_scriptExecutionContext->didCreateActiveDOMObject(this);
 }
 
 ActiveDOMObject::~ActiveDOMObject()
 {
+    // ActiveDOMObject may be inherited by a sub-class whose life-cycle
+    // exceeds that of the associated ScriptExecutionContext. In those cases,
+    // m_scriptExecutionContext would/should have been nullified by
+    // ContextLifecycleObserver::contextDestroyed() (which we implement /
+    // inherit). Hence, we should ensure that this is not 0 before use it
+    // here.
     if (!m_scriptExecutionContext)
         return;
 
     ASSERT(m_suspendIfNeededCalled);
-
-    // ActiveDOMObject may be inherited by a sub-class whose life-cycle
-    // exceeds that of the associated ScriptExecutionContext. In those cases,
-    // m_scriptExecutionContext would/should have been nullified by
-    // ContextDestructionObserver::contextDestroyed() (which we implement /
-    // inherit). Hence, we should ensure that this is not 0 before use it
-    // here.
-    if (m_scriptExecutionContext) {
-        ASSERT(m_scriptExecutionContext->isContextThread());
-        m_scriptExecutionContext->willDestroyActiveDOMObject(this);
-    }
+    ASSERT(m_scriptExecutionContext->isContextThread());
+    observeContext(0, ActiveDOMObjectType);
 }
 
 void ActiveDOMObject::suspendIfNeeded()
diff --git a/Source/core/dom/ActiveDOMObject.h b/Source/core/dom/ActiveDOMObject.h
index d37017e..bfb47db 100644
--- a/Source/core/dom/ActiveDOMObject.h
+++ b/Source/core/dom/ActiveDOMObject.h
@@ -27,13 +27,13 @@
 #ifndef ActiveDOMObject_h
 #define ActiveDOMObject_h
 
-#include "core/dom/ContextDestructionObserver.h"
+#include "core/dom/ContextLifecycleObserver.h"
 #include <wtf/Assertions.h>
 #include <wtf/Forward.h>
 
 namespace WebCore {
 
-class ActiveDOMObject : public ContextDestructionObserver {
+class ActiveDOMObject : public ContextLifecycleObserver {
 public:
     ActiveDOMObject(ScriptExecutionContext*);
 
diff --git a/Source/core/dom/Attr.cpp b/Source/core/dom/Attr.cpp
index 7aaf56c..2d56cb2 100644
--- a/Source/core/dom/Attr.cpp
+++ b/Source/core/dom/Attr.cpp
@@ -24,13 +24,12 @@
 #include "core/dom/Attr.h"
 
 #include "XMLNSNames.h"
-#include "core/css/StylePropertySet.h"
+#include "core/dom/Element.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/ScopedEventQueue.h"
-#include "core/dom/StyledElement.h"
 #include "core/dom/Text.h"
-#include <wtf/text/AtomicString.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/text/AtomicString.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/Attr.h b/Source/core/dom/Attr.h
index 9bff433..5f6004e 100644
--- a/Source/core/dom/Attr.h
+++ b/Source/core/dom/Attr.h
@@ -57,8 +57,6 @@
 
     bool isId() const;
 
-    CSSStyleDeclaration* style();
-
     void setSpecified(bool specified) { m_specified = specified; }
 
     void attachToElement(Element*);
@@ -100,6 +98,18 @@
     bool m_specified : 1;
 };
 
+inline Attr* toAttr(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isAttributeNode());
+    return static_cast<Attr*>(node);
+}
+
+inline const Attr* toAttr(const Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isAttributeNode());
+    return static_cast<const Attr*>(node);
+}
+
 } // namespace WebCore
 
 #endif // Attr_h
diff --git a/Source/core/dom/CharacterData.cpp b/Source/core/dom/CharacterData.cpp
index 9fda297..e57d138 100644
--- a/Source/core/dom/CharacterData.cpp
+++ b/Source/core/dom/CharacterData.cpp
@@ -28,14 +28,11 @@
 #include "core/dom/MutationEvent.h"
 #include "core/dom/MutationObserverInterestGroup.h"
 #include "core/dom/MutationRecord.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/dom/Text.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/editing/FrameSelection.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/platform/text/TextBreakIterator.h"
-#include "core/rendering/RenderText.h"
-#include "core/rendering/style/StyleInheritedData.h"
 
 using namespace std;
 
diff --git a/Source/core/dom/CharacterData.idl b/Source/core/dom/CharacterData.idl
index 9d8ee85..2e3262c 100644
--- a/Source/core/dom/CharacterData.idl
+++ b/Source/core/dom/CharacterData.idl
@@ -36,10 +36,7 @@
      [RaisesException] void replaceData([IsIndex,Default=Undefined] optional unsigned long offset, 
                                     [IsIndex,Default=Undefined] optional unsigned long length,
                                     [Default=Undefined] optional DOMString data);
-
-    // ChildNode interface API
-    readonly attribute Element previousElementSibling;
-    readonly attribute Element nextElementSibling;
-    [RaisesException] void remove();
 };
 
+CharacterData implements ChildNode;
+
diff --git a/Source/core/dom/ChildListMutationScope.h b/Source/core/dom/ChildListMutationScope.h
index b5060e1..78c63c3 100644
--- a/Source/core/dom/ChildListMutationScope.h
+++ b/Source/core/dom/ChildListMutationScope.h
@@ -34,10 +34,9 @@
 #include "core/dom/Document.h"
 #include "core/dom/MutationObserver.h"
 #include "core/dom/Node.h"
-#include <wtf/HashMap.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/RefCounted.h>
+#include "wtf/Noncopyable.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/RegisteredEventListener.cpp b/Source/core/dom/ChildNode.idl
similarity index 65%
copy from Source/core/dom/RegisteredEventListener.cpp
copy to Source/core/dom/ChildNode.idl
index 6153b5c..b37f05f 100644
--- a/Source/core/dom/RegisteredEventListener.cpp
+++ b/Source/core/dom/ChildNode.idl
@@ -1,8 +1,8 @@
 /*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2006, 2007, 2009 Apple Inc. All rights reserved.
+ * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
+ * 
  *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
@@ -20,11 +20,10 @@
  * Boston, MA 02110-1301, USA.
  */
 
-#include "config.h"
-#include "core/dom/RegisteredEventListener.h"
+[NoInterfaceObject]
+interface ChildNode {
+    [PerWorldBindings] readonly attribute Element previousElementSibling;
+    [PerWorldBindings] readonly attribute Element nextElementSibling;
+    [RaisesException] void remove();
+};
 
-#include "core/dom/EventListener.h"
-
-namespace WebCore {
-
-} // namespace WebCore
diff --git a/Source/core/dom/Clipboard.h b/Source/core/dom/Clipboard.h
index ef51bf3..1593a5c 100644
--- a/Source/core/dom/Clipboard.h
+++ b/Source/core/dom/Clipboard.h
@@ -31,13 +31,17 @@
 #include "core/page/DragActions.h"
 #include "core/platform/DragImage.h"
 #include "core/platform/graphics/IntPoint.h"
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
+class CachedImage;
 class DataTransferItemList;
 class DragData;
+class DragImage;
 class FileList;
 class Frame;
+class Range;
 
 // State available during IE's events for drag and drop and copy/paste
 class Clipboard : public RefCounted<Clipboard>, public ScriptWrappable {
@@ -76,7 +80,7 @@
     Node* dragImageElement() const { return m_dragImageElement.get(); }
     virtual void setDragImageElement(Node*, const IntPoint&) = 0;
 
-    virtual DragImageRef createDragImage(IntPoint& dragLocation) const = 0;
+    virtual PassOwnPtr<DragImage> createDragImage(IntPoint& dragLocation) const = 0;
     virtual void declareAndWriteDragImage(Element*, const KURL&, const String& title, Frame*) = 0;
     virtual void writeURL(const KURL&, const String&, Frame*) = 0;
     virtual void writeRange(Range*, Frame*) = 0;
diff --git a/Source/core/dom/ContainerNode.cpp b/Source/core/dom/ContainerNode.cpp
index 33bf98d..1f9b351 100644
--- a/Source/core/dom/ContainerNode.cpp
+++ b/Source/core/dom/ContainerNode.cpp
@@ -33,13 +33,11 @@
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/html/HTMLCollection.h"
-#include "core/page/Page.h"
 #include "core/rendering/InlineTextBox.h"
 #include "core/rendering/RenderText.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderWidget.h"
-#include <wtf/CurrentTime.h>
-#include <wtf/Vector.h>
+#include "wtf/Vector.h"
 
 using namespace std;
 
@@ -558,9 +556,6 @@
     // The container node can be removed from event handlers.
     RefPtr<ContainerNode> protect(this);
 
-    // exclude this node when looking for removed focusedNode since only children will be removed
-    document()->removeFocusedNodeOfSubtree(this, true);
-
     if (FullscreenController* fullscreen = FullscreenController::fromIfExists(document()))
         fullscreen->removeFullScreenElementOfSubtree(this, true);
 
@@ -568,6 +563,12 @@
     // and remove... e.g. stop loading frames, fire unload events.
     willRemoveChildren(protect.get());
 
+    // Exclude this node when looking for removed focusedNode since only
+    // children will be removed.
+    // This must be later than willRemvoeChildren, which might change focus
+    // state of a child.
+    document()->removeFocusedNodeOfSubtree(this, true);
+
     NodeVector removedChildren;
     {
         WidgetHierarchyUpdatesSuspensionScope suspendWidgetHierarchyUpdates;
@@ -713,13 +714,13 @@
 
 void ContainerNode::attach(const AttachContext& context)
 {
-    attachChildren();
+    attachChildren(context);
     Node::attach(context);
 }
 
 void ContainerNode::detach(const AttachContext& context)
 {
-    detachChildren();
+    detachChildren(context);
     clearChildNeedsStyleRecalc();
     Node::detach(context);
 }
diff --git a/Source/core/dom/ContainerNode.h b/Source/core/dom/ContainerNode.h
index e25b308..28dea40 100644
--- a/Source/core/dom/ContainerNode.h
+++ b/Source/core/dom/ContainerNode.h
@@ -127,11 +127,6 @@
     // node that is of the type CDATA_SECTION_NODE, TEXT_NODE or COMMENT_NODE has changed its value.
     virtual void childrenChanged(bool createdByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
 
-    void attachChildren();
-    void attachChildrenLazily();
-    void detachChildren();
-    void detachChildrenIfNeeded();
-
     void disconnectDescendantFrames();
 
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const { return true; }
@@ -158,6 +153,9 @@
     void removeBetween(Node* previousChild, Node* nextChild, Node* oldChild);
     void insertBeforeCommon(Node* nextChild, Node* oldChild);
 
+    void attachChildren(const AttachContext& = AttachContext());
+    void detachChildren(const AttachContext& = AttachContext());
+
     static void dispatchPostAttachCallbacks();
 
     void suspendPostAttachCallbacks();
@@ -196,34 +194,25 @@
 {
 }
 
-inline void ContainerNode::attachChildren()
+inline void ContainerNode::attachChildren(const AttachContext& context)
 {
+    AttachContext childrenContext(context);
+    childrenContext.resolvedStyle = 0;
+
     for (Node* child = firstChild(); child; child = child->nextSibling()) {
         ASSERT(!child->attached() || childAttachedAllowedWhenAttachingChildren(this));
         if (!child->attached())
-            child->attach();
+            child->attach(childrenContext);
     }
 }
 
-inline void ContainerNode::attachChildrenLazily()
+inline void ContainerNode::detachChildren(const AttachContext& context)
 {
-    for (Node* child = firstChild(); child; child = child->nextSibling())
-        if (!child->attached())
-            child->lazyAttach();
-}
+    AttachContext childrenContext(context);
+    childrenContext.resolvedStyle = 0;
 
-inline void ContainerNode::detachChildrenIfNeeded()
-{
-    for (Node* child = firstChild(); child; child = child->nextSibling()) {
-        if (child->attached())
-            child->detach();
-    }
-}
-
-inline void ContainerNode::detachChildren()
-{
     for (Node* child = firstChild(); child; child = child->nextSibling())
-        child->detach();
+        child->detach(childrenContext);
 }
 
 inline unsigned Node::childNodeCount() const
diff --git a/Source/core/dom/ContainerNodeAlgorithms.h b/Source/core/dom/ContainerNodeAlgorithms.h
index 5e09a6b..f02eb7f 100644
--- a/Source/core/dom/ContainerNodeAlgorithms.h
+++ b/Source/core/dom/ContainerNodeAlgorithms.h
@@ -26,8 +26,7 @@
 #include "core/dom/NodeTraversal.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/page/Frame.h"
-#include <wtf/Assertions.h>
+#include "wtf/Assertions.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/ContextLifecycleNotifier.cpp b/Source/core/dom/ContextLifecycleNotifier.cpp
new file mode 100644
index 0000000..1c1b72f
--- /dev/null
+++ b/Source/core/dom/ContextLifecycleNotifier.cpp
@@ -0,0 +1,143 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2013 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+
+#include "config.h"
+#include "core/dom/ContextLifecycleNotifier.h"
+
+#include "core/dom/WebCoreMemoryInstrumentation.h"
+#include "wtf/TemporaryChange.h"
+
+namespace WebCore {
+
+ContextLifecycleNotifier::ContextLifecycleNotifier(ScriptExecutionContext* context)
+    : m_context(context)
+    , m_iterating(IteratingNone)
+    , m_inDestructor(false)
+{
+}
+
+ContextLifecycleNotifier::~ContextLifecycleNotifier()
+{
+    m_inDestructor = true;
+    for (ContextObserverSet::iterator iter = m_contextObservers.begin(); iter != m_contextObservers.end(); iter = m_contextObservers.begin()) {
+        ContextLifecycleObserver* observer = *iter;
+        m_contextObservers.remove(observer);
+        ASSERT(observer->scriptExecutionContext() == m_context);
+        observer->contextDestroyed();
+    }
+}
+
+void ContextLifecycleNotifier::addObserver(ContextLifecycleObserver* observer, ContextLifecycleObserver::Type as)
+{
+    RELEASE_ASSERT(!m_inDestructor);
+    RELEASE_ASSERT(m_iterating != IteratingOverContextObservers);
+    m_contextObservers.add(observer);
+    if (as == ContextLifecycleObserver::ActiveDOMObjectType) {
+        RELEASE_ASSERT(m_iterating != IteratingOverActiveDOMObjects);
+        m_activeDOMObjects.add(static_cast<ActiveDOMObject*>(observer));
+    }
+}
+
+void ContextLifecycleNotifier::removeObserver(ContextLifecycleObserver* observer, ContextLifecycleObserver::Type as)
+{
+    RELEASE_ASSERT(!m_inDestructor);
+    RELEASE_ASSERT(m_iterating != IteratingOverContextObservers);
+    m_contextObservers.remove(observer);
+    if (as == ContextLifecycleObserver::ActiveDOMObjectType) {
+        RELEASE_ASSERT(m_iterating != IteratingOverActiveDOMObjects);
+        m_activeDOMObjects.remove(static_cast<ActiveDOMObject*>(observer));
+    }
+}
+
+void ContextLifecycleNotifier::notifyResumingActiveDOMObjects()
+{
+    TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverActiveDOMObjects);
+    ActiveDOMObjectSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
+    for (ActiveDOMObjectSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
+        ASSERT((*iter)->scriptExecutionContext() == m_context);
+        ASSERT((*iter)->suspendIfNeededCalled());
+        (*iter)->resume();
+    }
+}
+
+void ContextLifecycleNotifier::notifySuspendingActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
+{
+    TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverActiveDOMObjects);
+    ActiveDOMObjectSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
+    for (ActiveDOMObjectSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
+        ASSERT((*iter)->scriptExecutionContext() == m_context);
+        ASSERT((*iter)->suspendIfNeededCalled());
+        (*iter)->suspend(why);
+    }
+}
+
+void ContextLifecycleNotifier::notifyStoppingActiveDOMObjects()
+{
+    TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverActiveDOMObjects);
+    ActiveDOMObjectSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
+    for (ActiveDOMObjectSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
+        ASSERT((*iter)->scriptExecutionContext() == m_context);
+        ASSERT((*iter)->suspendIfNeededCalled());
+        (*iter)->stop();
+    }
+}
+
+bool ContextLifecycleNotifier::canSuspendActiveDOMObjects()
+{
+    TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverActiveDOMObjects);
+    ActiveDOMObjectSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
+    for (ActiveDOMObjectSet::const_iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
+        ASSERT((*iter)->scriptExecutionContext() == m_context);
+        ASSERT((*iter)->suspendIfNeededCalled());
+        if (!(*iter)->canSuspend())
+            return false;
+    }
+
+    return true;
+}
+
+bool ContextLifecycleNotifier::hasPendingActivity() const
+{
+    ActiveDOMObjectSet::const_iterator activeObjectsEnd = activeDOMObjects().end();
+    for (ActiveDOMObjectSet::const_iterator iter = activeDOMObjects().begin(); iter != activeObjectsEnd; ++iter) {
+        if ((*iter)->hasPendingActivity())
+            return true;
+    }
+
+    return false;
+}
+
+void ContextLifecycleNotifier::reportMemoryUsage(WTF::MemoryObjectInfo* memoryObjectInfo) const
+{
+    MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM);
+    ActiveDOMObjectSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
+    for (ActiveDOMObjectSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter)
+        info.addMember(*iter, "activeDOMObject", WTF::RetainingPointer);
+}
+
+} // namespace WebCore
+
diff --git a/Source/core/dom/ContextLifecycleNotifier.h b/Source/core/dom/ContextLifecycleNotifier.h
new file mode 100644
index 0000000..4929ade
--- /dev/null
+++ b/Source/core/dom/ContextLifecycleNotifier.h
@@ -0,0 +1,95 @@
+/*
+ * Copyright (C) 2008 Apple Inc. All Rights Reserved.
+ * Copyright (C) 2013 Google Inc. All Rights Reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ */
+#ifndef ContextLifecycleNotifier_h
+#define ContextLifecycleNotifier_h
+
+#include "core/dom/ActiveDOMObject.h"
+#include "wtf/HashSet.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace WTF {
+class MemoryObjectInfo;
+}
+
+namespace WebCore {
+
+class ActiveDOMObject;
+class ContextLifecycleObserver;
+class ScriptExecutionContext;
+
+class ContextLifecycleNotifier {
+public:
+    static PassOwnPtr<ContextLifecycleNotifier> create(ScriptExecutionContext*);
+
+    virtual ~ContextLifecycleNotifier();
+
+    typedef HashSet<ContextLifecycleObserver*> ContextObserverSet;
+    typedef HashSet<ActiveDOMObject*> ActiveDOMObjectSet;
+
+    const ActiveDOMObjectSet& activeDOMObjects() const { return m_activeDOMObjects; }
+
+    virtual void addObserver(ContextLifecycleObserver*, ContextLifecycleObserver::Type as);
+    virtual void removeObserver(ContextLifecycleObserver*, ContextLifecycleObserver::Type as);
+
+    void notifyResumingActiveDOMObjects();
+    void notifySuspendingActiveDOMObjects(ActiveDOMObject::ReasonForSuspension);
+    void notifyStoppingActiveDOMObjects();
+
+    bool contains(ActiveDOMObject* object) const { return m_activeDOMObjects.contains(object); }
+    bool canSuspendActiveDOMObjects();
+    bool hasPendingActivity() const;
+
+    void reportMemoryUsage(WTF::MemoryObjectInfo*) const;
+
+protected:
+    explicit ContextLifecycleNotifier(ScriptExecutionContext*);
+
+    enum IterationType {
+        IteratingNone,
+        IteratingOverActiveDOMObjects,
+        IteratingOverContextObservers,
+        IteratingOverDocumentObservers
+    };
+
+    IterationType m_iterating;
+
+private:
+    ScriptExecutionContext* m_context;
+    ContextObserverSet m_contextObservers;
+    ActiveDOMObjectSet m_activeDOMObjects;
+    bool m_inDestructor;
+};
+
+inline PassOwnPtr<ContextLifecycleNotifier> ContextLifecycleNotifier::create(ScriptExecutionContext* context)
+{
+    return adoptPtr(new ContextLifecycleNotifier(context));
+}
+
+} // namespace WebCore
+
+#endif // ContextLifecycleNotifier_h
+
diff --git a/Source/core/dom/ContextDestructionObserver.cpp b/Source/core/dom/ContextLifecycleObserver.cpp
similarity index 74%
rename from Source/core/dom/ContextDestructionObserver.cpp
rename to Source/core/dom/ContextLifecycleObserver.cpp
index 6750d80..656f54e 100644
--- a/Source/core/dom/ContextDestructionObserver.cpp
+++ b/Source/core/dom/ContextLifecycleObserver.cpp
@@ -20,44 +20,45 @@
  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  */
 
 #include "config.h"
-#include "core/dom/ContextDestructionObserver.h"
+#include "core/dom/ContextLifecycleObserver.h"
 
 #include "core/dom/ScriptExecutionContext.h"
 
 namespace WebCore {
 
-ContextDestructionObserver::ContextDestructionObserver(ScriptExecutionContext* scriptExecutionContext)
+ContextLifecycleObserver::ContextLifecycleObserver(ScriptExecutionContext* scriptExecutionContext, Type type)
     : m_scriptExecutionContext(0)
 {
-    observeContext(scriptExecutionContext);
+    observeContext(scriptExecutionContext, type);
 }
 
-ContextDestructionObserver::~ContextDestructionObserver()
+ContextLifecycleObserver::~ContextLifecycleObserver()
 {
-    observeContext(0);
+    if (m_scriptExecutionContext)
+        observeContext(0, GenericType);
 }
 
-void ContextDestructionObserver::observeContext(ScriptExecutionContext* scriptExecutionContext)
+void ContextLifecycleObserver::observeContext(ScriptExecutionContext* scriptExecutionContext, Type as)
 {
     if (m_scriptExecutionContext) {
         ASSERT(m_scriptExecutionContext->isContextThread());
-        m_scriptExecutionContext->willDestroyDestructionObserver(this);
+        m_scriptExecutionContext->wasUnobservedBy(this, as);
     }
 
     m_scriptExecutionContext = scriptExecutionContext;
 
     if (m_scriptExecutionContext) {
         ASSERT(m_scriptExecutionContext->isContextThread());
-        m_scriptExecutionContext->didCreateDestructionObserver(this);
+        m_scriptExecutionContext->wasObservedBy(this, as);
     }
 }
 
-void ContextDestructionObserver::contextDestroyed()
+void ContextLifecycleObserver::contextDestroyed()
 {
     m_scriptExecutionContext = 0;
 }
diff --git a/Source/core/dom/ContextDestructionObserver.h b/Source/core/dom/ContextLifecycleObserver.h
similarity index 78%
rename from Source/core/dom/ContextDestructionObserver.h
rename to Source/core/dom/ContextLifecycleObserver.h
index ca956ab..574455e 100644
--- a/Source/core/dom/ContextDestructionObserver.h
+++ b/Source/core/dom/ContextLifecycleObserver.h
@@ -20,31 +20,37 @@
  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  *
  */
 
-#ifndef ContextDestructionObserver_h
-#define ContextDestructionObserver_h
+#ifndef ContextLifecycleObserver_h
+#define ContextLifecycleObserver_h
 
 namespace WebCore {
 
 class ScriptExecutionContext;
 
-class ContextDestructionObserver {
+class ContextLifecycleObserver {
 public:
-    explicit ContextDestructionObserver(ScriptExecutionContext*);
+    enum Type {
+        ActiveDOMObjectType,
+        DocumentLifecycleObserverType,
+        GenericType
+    };
+
+    explicit ContextLifecycleObserver(ScriptExecutionContext*, Type = GenericType);
     virtual void contextDestroyed();
 
     ScriptExecutionContext* scriptExecutionContext() const { return m_scriptExecutionContext; }
 
 protected:
-    virtual ~ContextDestructionObserver();
-    void observeContext(ScriptExecutionContext*);
+    virtual ~ContextLifecycleObserver();
+    void observeContext(ScriptExecutionContext*, Type);
 
     ScriptExecutionContext* m_scriptExecutionContext;
 };
 
 } // namespace WebCore
 
-#endif // ContextDestructionObserver_h
+#endif // ContextLifecycleObserver_h
diff --git a/Source/core/css/CSSStyleDeclaration.cpp b/Source/core/dom/CustomElementCallback.h
similarity index 74%
copy from Source/core/css/CSSStyleDeclaration.cpp
copy to Source/core/dom/CustomElementCallback.h
index 538e17e..d71e35a 100644
--- a/Source/core/css/CSSStyleDeclaration.cpp
+++ b/Source/core/dom/CustomElementCallback.h
@@ -28,19 +28,34 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/css/CSSStyleDeclaration.h"
+#ifndef CustomElementCallback_h
+#define CustomElementCallback_h
 
-#include "core/css/CSSParser.h"
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/css/CSSStyleSheet.h"
-#include "core/css/CSSValue.h"
-#include "core/dom/Document.h"
-#include "core/dom/DocumentStyleSheetCollection.h"
-#include "core/dom/EventTarget.h"
-#include "core/html/HTMLStyleElement.h"
-#include "core/page/RuntimeCSSEnabled.h"
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
-} // namespace WebCore
+class Element;
+
+class CustomElementCallback : public RefCounted<CustomElementCallback> {
+public:
+    virtual ~CustomElementCallback() { }
+
+    bool hasReady() const { return m_which == Ready; }
+    virtual void ready(Element*) = 0;
+
+protected:
+    enum CallbackType {
+        None,
+        Ready
+    };
+
+    CustomElementCallback(CallbackType which) : m_which(which) { }
+
+private:
+    CallbackType m_which;
+};
+
+}
+
+#endif // CustomElementCallback_h
diff --git a/Source/core/dom/CustomElementCallbackDispatcher.cpp b/Source/core/dom/CustomElementCallbackDispatcher.cpp
new file mode 100644
index 0000000..667c6c2
--- /dev/null
+++ b/Source/core/dom/CustomElementCallbackDispatcher.cpp
@@ -0,0 +1,74 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer
+ *    in the documentation and/or other materials provided with the
+ *    distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ *    may be used to endorse or promote products derived from this
+ *    software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "CustomElementCallbackDispatcher.h"
+
+#include "CustomElementCallback.h"
+
+namespace WebCore {
+
+CustomElementCallbackDispatcher& CustomElementCallbackDispatcher::instance()
+{
+    DEFINE_STATIC_LOCAL(CustomElementCallbackDispatcher, instance, ());
+    return instance;
+}
+
+CustomElementCallbackDispatcher::ReadyInvocation::ReadyInvocation(PassRefPtr<CustomElementCallback> callback, PassRefPtr<Element> element)
+    : m_callback(callback)
+    , m_element(element)
+{
+}
+
+bool CustomElementCallbackDispatcher::dispatch()
+{
+    if (m_invocations.isEmpty())
+        return false;
+
+    do  {
+        Vector<ReadyInvocation> invocations;
+        m_invocations.swap(invocations);
+
+        for (Vector<ReadyInvocation>::iterator it = invocations.begin(); it != invocations.end(); ++it)
+            it->invoke();
+    } while (!m_invocations.isEmpty());
+
+    return true;
+}
+
+void CustomElementCallbackDispatcher::enqueueReadyCallback(CustomElementCallback* callback, Element* element)
+{
+    if (!callback->hasReady())
+        return;
+
+    m_invocations.append(ReadyInvocation(callback, element));
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/CustomElementCallbackDispatcher.h b/Source/core/dom/CustomElementCallbackDispatcher.h
new file mode 100644
index 0000000..46a4f76
--- /dev/null
+++ b/Source/core/dom/CustomElementCallbackDispatcher.h
@@ -0,0 +1,86 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer
+ *    in the documentation and/or other materials provided with the
+ *    distribution.
+ * 3. Neither the name of Google Inc. nor the names of its contributors
+ *    may be used to endorse or promote products derived from this
+ *    software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef CustomElementCallbackDispatcher_h
+#define CustomElementCallbackDispatcher_h
+
+#include "core/dom/CustomElementCallback.h"
+#include "core/dom/Element.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+
+namespace WebCore {
+
+class CustomElementCallbackDispatcher {
+    WTF_MAKE_NONCOPYABLE(CustomElementCallbackDispatcher);
+public:
+    static CustomElementCallbackDispatcher& instance();
+
+    class CallbackDeliveryScope {
+    public:
+        CallbackDeliveryScope() { }
+        ~CallbackDeliveryScope()
+        {
+            CustomElementCallbackDispatcher& dispatcher = CustomElementCallbackDispatcher::instance();
+            if (dispatcher.hasQueuedCallbacks())
+                dispatcher.dispatch();
+        }
+    };
+
+    void enqueueReadyCallback(CustomElementCallback*, Element*);
+
+    // Returns true if more work may have to be performed at the
+    // checkpoint by this or other workers (for example, this work
+    // invoked author scripts)
+    bool dispatch();
+
+private:
+    explicit CustomElementCallbackDispatcher() { }
+
+    bool hasQueuedCallbacks() { return !m_invocations.isEmpty(); }
+
+    class ReadyInvocation {
+    public:
+        ReadyInvocation(PassRefPtr<CustomElementCallback>, PassRefPtr<Element>);
+        virtual ~ReadyInvocation() { }
+        void invoke() { m_callback->ready(m_element.get()); }
+
+    private:
+        RefPtr<CustomElementCallback> m_callback;
+        RefPtr<Element> m_element;
+    };
+
+    Vector<ReadyInvocation> m_invocations;
+};
+
+}
+
+#endif // CustomElementCallbackDispatcher_h
diff --git a/Source/core/dom/CustomElementDefinition.cpp b/Source/core/dom/CustomElementDefinition.cpp
index 70666dc..827383b 100644
--- a/Source/core/dom/CustomElementDefinition.cpp
+++ b/Source/core/dom/CustomElementDefinition.cpp
@@ -32,20 +32,17 @@
 
 #include "core/dom/CustomElementDefinition.h"
 
-#include "SVGNames.h"
-#include "bindings/v8/CustomElementHelpers.h"
-#include <wtf/Assertions.h>
-
 namespace WebCore {
 
-PassRefPtr<CustomElementDefinition> CustomElementDefinition::create(const AtomicString& type, const AtomicString& name, const AtomicString& namespaceURI)
+PassRefPtr<CustomElementDefinition> CustomElementDefinition::create(const AtomicString& type, const AtomicString& name, const AtomicString& namespaceURI, PassRefPtr<CustomElementCallback> callback)
 {
-    return adoptRef(new CustomElementDefinition(type, name, namespaceURI));
+    return adoptRef(new CustomElementDefinition(type, name, namespaceURI, callback));
 }
 
-CustomElementDefinition::CustomElementDefinition(const AtomicString& type, const AtomicString& name, const AtomicString& namespaceURI)
+CustomElementDefinition::CustomElementDefinition(const AtomicString& type, const AtomicString& name, const AtomicString& namespaceURI, PassRefPtr<CustomElementCallback> callback)
     : m_type(type)
     , m_tag(QualifiedName(nullAtom, name, namespaceURI))
+    , m_callback(callback)
 {
 }
 
diff --git a/Source/core/dom/CustomElementDefinition.h b/Source/core/dom/CustomElementDefinition.h
index ac5fe2d..a3a7134 100644
--- a/Source/core/dom/CustomElementDefinition.h
+++ b/Source/core/dom/CustomElementDefinition.h
@@ -31,7 +31,7 @@
 #ifndef CustomElementDefinition_h
 #define CustomElementDefinition_h
 
-#include "bindings/v8/ScriptValue.h"
+#include "core/dom/CustomElementCallback.h"
 #include "core/dom/QualifiedName.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
@@ -39,11 +39,9 @@
 
 namespace WebCore {
 
-class ScriptState;
-
 class CustomElementDefinition : public RefCounted<CustomElementDefinition> {
 public:
-    static PassRefPtr<CustomElementDefinition> create(const AtomicString& type, const AtomicString& name, const AtomicString& namespaceURI);
+    static PassRefPtr<CustomElementDefinition> create(const AtomicString& type, const AtomicString& name, const AtomicString& namespaceURI, PassRefPtr<CustomElementCallback>);
 
     virtual ~CustomElementDefinition() {}
 
@@ -72,11 +70,14 @@
     CustomElementKind kind() const { return isTypeExtension() ? TypeExtension : CustomTag; }
     bool isTypeExtension() const { return type() != name(); }
 
+    CustomElementCallback* callback() const { return m_callback.get(); }
+
 private:
-    CustomElementDefinition(const AtomicString& type, const AtomicString& name, const AtomicString& namespaceURI);
+    CustomElementDefinition(const AtomicString& type, const AtomicString& name, const AtomicString& namespaceURI, PassRefPtr<CustomElementCallback>);
 
     AtomicString m_type;
     QualifiedName m_tag;
+    RefPtr<CustomElementCallback> m_callback;
 };
 
 }
diff --git a/Source/core/dom/CustomElementRegistry.cpp b/Source/core/dom/CustomElementRegistry.cpp
index 3bad3ba..3eeb0df 100644
--- a/Source/core/dom/CustomElementRegistry.cpp
+++ b/Source/core/dom/CustomElementRegistry.cpp
@@ -29,14 +29,12 @@
  */
 
 #include "config.h"
-
 #include "core/dom/CustomElementRegistry.h"
 
 #include "HTMLNames.h"
 #include "SVGNames.h"
-#include "bindings/v8/CustomElementHelpers.h"
-#include "bindings/v8/Dictionary.h"
-#include "bindings/v8/ScriptValue.h"
+#include "bindings/v8/CustomElementConstructorBuilder.h"
+#include "core/dom/CustomElementCallbackDispatcher.h"
 #include "core/dom/CustomElementDefinition.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
@@ -45,15 +43,6 @@
 
 namespace WebCore {
 
-CustomElementInvocation::CustomElementInvocation(PassRefPtr<Element> element)
-    : m_element(element)
-{
-}
-
-CustomElementInvocation::~CustomElementInvocation()
-{
-}
-
 void setTypeExtension(Element* element, const AtomicString& typeExtension)
 {
     ASSERT(element);
@@ -62,15 +51,10 @@
 }
 
 CustomElementRegistry::CustomElementRegistry(Document* document)
-    : ContextDestructionObserver(document)
+    : ContextLifecycleObserver(document)
 {
 }
 
-CustomElementRegistry::~CustomElementRegistry()
-{
-    deactivate();
-}
-
 static inline bool nameIncludesHyphen(const AtomicString& name)
 {
     size_t hyphenPosition = name.find('-');
@@ -99,79 +83,66 @@
     return Document::isValidName(name.string());
 }
 
-ScriptValue CustomElementRegistry::registerElement(ScriptState* state, const AtomicString& userSuppliedName, const Dictionary& options, ExceptionCode& ec)
+void CustomElementRegistry::registerElement(CustomElementConstructorBuilder* constructorBuilder, const AtomicString& userSuppliedName, ExceptionCode& ec)
 {
     RefPtr<CustomElementRegistry> protect(this);
 
-    if (!CustomElementHelpers::isFeatureAllowed(state))
-        return ScriptValue();
+    if (!constructorBuilder->isFeatureAllowed())
+        return;
 
-    AtomicString name = userSuppliedName.lower();
-    if (!isValidName(name)) {
+    AtomicString type = userSuppliedName.lower();
+    if (!isValidName(type)) {
         ec = INVALID_CHARACTER_ERR;
-        return ScriptValue();
+        return;
     }
 
-    ScriptValue prototypeValue;
-    if (!options.get("prototype", prototypeValue)) {
-        // FIXME: Implement the default value handling.
-        // Currently default value of the "prototype" parameter, which
-        // is HTMLSpanElement.prototype, has an ambiguity about its
-        // behavior. The spec should be fixed before WebKit implements
-        // it. https://www.w3.org/Bugs/Public/show_bug.cgi?id=20801
+    if (!constructorBuilder->validateOptions()) {
         ec = INVALID_STATE_ERR;
-        return ScriptValue();
+        return;
     }
 
-    AtomicString namespaceURI;
-    if (!CustomElementHelpers::isValidPrototypeParameter(prototypeValue, state, namespaceURI)) {
-        ec = INVALID_STATE_ERR;
-        return ScriptValue();
-    }
-
-    if (namespaceURI.isNull()) {
+    QualifiedName tagName = nullQName();
+    if (!constructorBuilder->findTagName(type, tagName)) {
         ec = NAMESPACE_ERR;
-        return ScriptValue();
+        return;
     }
+    ASSERT(tagName.namespaceURI() == HTMLNames::xhtmlNamespaceURI || tagName.namespaceURI() == SVGNames::svgNamespaceURI);
 
-    AtomicString type = name;
     if (m_definitions.contains(type)) {
         ec = INVALID_STATE_ERR;
-        return ScriptValue();
+        return;
     }
 
-    const QualifiedName* prototypeTagName = CustomElementHelpers::findLocalName(prototypeValue);
-    if (prototypeTagName)
-        name = prototypeTagName->localName();
+    RefPtr<CustomElementCallback> lifecycleCallbacks = constructorBuilder->createCallback(document());
 
-    // A script execution could happen in isValidPrototypeParameter(), which kills the document.
+    // Consulting the constructor builder could execute script and
+    // kill the document.
     if (!document()) {
         ec = INVALID_STATE_ERR;
-        return ScriptValue();
+        return;
     }
 
-    ASSERT(name == type || QualifiedName(nullAtom, name, namespaceURI) == *CustomElementHelpers::findLocalName(prototypeValue));
-    ASSERT(namespaceURI == HTMLNames::xhtmlNamespaceURI || namespaceURI == SVGNames::svgNamespaceURI);
+    RefPtr<CustomElementDefinition> definition = CustomElementDefinition::create(type, tagName.localName(), tagName.namespaceURI(), lifecycleCallbacks);
 
-    RefPtr<CustomElementDefinition> definition = CustomElementDefinition::create(type, name, namespaceURI);
-    ScriptValue constructor = CustomElementHelpers::createConstructor(state, prototypeValue, document(), definition->namespaceURI(), definition->name(), definition->isTypeExtension() ? definition->type() : nullAtom);
-    if (constructor.hasNoValue()) {
-        ec = INVALID_STATE_ERR;
-        return ScriptValue();
+    if (!constructorBuilder->createConstructor(document(), definition.get())) {
+        ec = NOT_SUPPORTED_ERR;
+        return;
     }
-    ASSERT(constructor.isFunction());
 
     m_definitions.add(definition->type(), definition);
 
     // Upgrade elements that were waiting for this definition.
     CustomElementUpgradeCandidateMap::ElementSet upgradeCandidates = m_candidates.takeUpgradeCandidatesFor(definition.get());
-    CustomElementHelpers::didRegisterDefinition(definition.get(), document(), upgradeCandidates, prototypeValue);
-    for (CustomElementUpgradeCandidateMap::ElementSet::iterator it = upgradeCandidates.begin(); it != upgradeCandidates.end(); ++it) {
-        (*it)->setNeedsStyleRecalc(); // :unresolved has changed
-        activate(CustomElementInvocation(*it));
+    if (!constructorBuilder->didRegisterDefinition(definition.get(), upgradeCandidates)) {
+        ec = NOT_SUPPORTED_ERR;
+        return;
     }
 
-    return constructor;
+    for (CustomElementUpgradeCandidateMap::ElementSet::iterator it = upgradeCandidates.begin(); it != upgradeCandidates.end(); ++it) {
+        (*it)->setNeedsStyleRecalc(); // :unresolved has changed
+
+        CustomElementCallbackDispatcher::instance().enqueueReadyCallback(lifecycleCallbacks.get(), *it);
+    }
 }
 
 bool CustomElementRegistry::isUnresolved(Element* element) const
@@ -238,7 +209,7 @@
         // custom tag element will be unresolved in perpetuity.
         didCreateUnresolvedElement(CustomElementDefinition::CustomTag, tagName.localName(), element.get());
     } else {
-        didCreateCustomTagElement(element.get());
+        didCreateCustomTagElement(definition.get(), element.get());
     }
 
     return element.release();
@@ -255,13 +226,13 @@
         // extension element will be unresolved in perpetuity.
         didCreateUnresolvedElement(CustomElementDefinition::TypeExtension, type, element);
     } else {
-        activate(CustomElementInvocation(element));
+        CustomElementCallbackDispatcher::instance().enqueueReadyCallback(definition->callback(), element);
     }
 }
 
-void CustomElementRegistry::didCreateCustomTagElement(Element* element)
+void CustomElementRegistry::didCreateCustomTagElement(CustomElementDefinition* definition, Element* element)
 {
-    activate(CustomElementInvocation(element));
+    CustomElementCallbackDispatcher::instance().enqueueReadyCallback(definition->callback(), element);
 }
 
 void CustomElementRegistry::didCreateUnresolvedElement(CustomElementDefinition::CustomElementKind kind, const AtomicString& type, Element* element)
@@ -275,49 +246,9 @@
     m_candidates.remove(element);
 }
 
-void CustomElementRegistry::activate(const CustomElementInvocation& invocation)
-{
-    bool wasInactive = m_invocations.isEmpty();
-    m_invocations.append(invocation);
-    if (wasInactive)
-        activeCustomElementRegistries().add(this);
-}
-
-void CustomElementRegistry::deactivate()
-{
-    ASSERT(m_invocations.isEmpty());
-    if (activeCustomElementRegistries().contains(this))
-        activeCustomElementRegistries().remove(this);
-}
-
 inline Document* CustomElementRegistry::document() const
 {
     return toDocument(m_scriptExecutionContext);
 }
 
-void CustomElementRegistry::deliverLifecycleCallbacks()
-{
-    ASSERT(!m_invocations.isEmpty());
-
-    if (!m_invocations.isEmpty()) {
-        Vector<CustomElementInvocation> invocations;
-        m_invocations.swap(invocations);
-        CustomElementHelpers::invokeReadyCallbacksIfNeeded(m_scriptExecutionContext, invocations);
-    }
-
-    ASSERT(m_invocations.isEmpty());
-    deactivate();
-}
-
-void CustomElementRegistry::deliverAllLifecycleCallbacks()
-{
-    while (!activeCustomElementRegistries().isEmpty()) {
-        Vector<RefPtr<CustomElementRegistry> > registries;
-        copyToVector(activeCustomElementRegistries(), registries);
-        activeCustomElementRegistries().clear();
-        for (size_t i = 0; i < registries.size(); ++i)
-            registries[i]->deliverLifecycleCallbacks();
-    }
-}
-
 }
diff --git a/Source/core/dom/CustomElementRegistry.h b/Source/core/dom/CustomElementRegistry.h
index 532f623..525618a 100644
--- a/Source/core/dom/CustomElementRegistry.h
+++ b/Source/core/dom/CustomElementRegistry.h
@@ -31,58 +31,35 @@
 #ifndef CustomElementRegistry_h
 #define CustomElementRegistry_h
 
-#include "bindings/v8/ScriptValue.h"
-#include "core/dom/ContextDestructionObserver.h"
+#include "core/dom/ContextLifecycleObserver.h"
 #include "core/dom/CustomElementUpgradeCandidateMap.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/QualifiedName.h"
-#include "wtf/HashSet.h"
-#include "wtf/ListHashSet.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
-#include "wtf/Vector.h"
 #include "wtf/text/AtomicString.h"
 #include "wtf/text/AtomicStringHash.h"
 
 namespace WebCore {
 
+class CustomElementConstructorBuilder;
 class CustomElementDefinition;
-class Dictionary;
 class Document;
 class Element;
-class ScriptState;
-
-class CustomElementInvocation {
-public:
-    explicit CustomElementInvocation(PassRefPtr<Element>);
-    ~CustomElementInvocation();
-
-    Element* element() const { return m_element.get(); }
-
-private:
-    RefPtr<Element> m_element;
-};
 
 void setTypeExtension(Element*, const AtomicString& typeExtension);
 
-class CustomElementRegistry : public RefCounted<CustomElementRegistry>, public ContextDestructionObserver {
+class CustomElementRegistry : public RefCounted<CustomElementRegistry>, public ContextLifecycleObserver {
     WTF_MAKE_NONCOPYABLE(CustomElementRegistry); WTF_MAKE_FAST_ALLOCATED;
 public:
-    class CallbackDeliveryScope {
-    public:
-        CallbackDeliveryScope() { }
-        ~CallbackDeliveryScope() { CustomElementRegistry::deliverAllLifecycleCallbacksIfNeeded(); }
-    };
-
     explicit CustomElementRegistry(Document*);
-    ~CustomElementRegistry();
+    virtual ~CustomElementRegistry() { }
 
-    ScriptValue registerElement(ScriptState*, const AtomicString& name, const Dictionary& options, ExceptionCode&);
+    void registerElement(CustomElementConstructorBuilder*, const AtomicString& name, ExceptionCode&);
 
     bool isUnresolved(Element*) const;
     PassRefPtr<CustomElementDefinition> findFor(Element*) const;
-    PassRefPtr<CustomElementDefinition> findAndCheckNamespace(const AtomicString& type, const AtomicString& namespaceURI) const;
 
     PassRefPtr<Element> createCustomTagElement(const QualifiedName& localName);
 
@@ -93,43 +70,19 @@
 
     static bool isCustomTagName(const AtomicString& name) { return isValidName(name); }
 
-    static void deliverAllLifecycleCallbacks();
-    static void deliverAllLifecycleCallbacksIfNeeded();
-
 private:
     typedef HashMap<AtomicString, RefPtr<CustomElementDefinition> > DefinitionMap;
-    typedef ListHashSet<CustomElementRegistry*> InstanceSet;
-
     static bool isValidName(const AtomicString&);
 
-    static InstanceSet& activeCustomElementRegistries();
-    void activate(const CustomElementInvocation&);
-    void deactivate();
-    void deliverLifecycleCallbacks();
+    PassRefPtr<CustomElementDefinition> findAndCheckNamespace(const AtomicString& type, const AtomicString& namespaceURI) const;
 
-    void didCreateCustomTagElement(Element*);
+    void didCreateCustomTagElement(CustomElementDefinition*, Element*);
     void didCreateUnresolvedElement(CustomElementDefinition::CustomElementKind, const AtomicString& type, Element*);
 
     DefinitionMap m_definitions;
     CustomElementUpgradeCandidateMap m_candidates;
-
-    Vector<CustomElementInvocation> m_invocations;
 };
 
-inline void CustomElementRegistry::deliverAllLifecycleCallbacksIfNeeded()
-{
-    if (!activeCustomElementRegistries().isEmpty())
-        deliverAllLifecycleCallbacks();
-    ASSERT(activeCustomElementRegistries().isEmpty());
-}
-
-inline CustomElementRegistry::InstanceSet& CustomElementRegistry::activeCustomElementRegistries()
-{
-    DEFINE_STATIC_LOCAL(InstanceSet, activeInstances, ());
-    return activeInstances;
-}
-
-
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/dom/DOMCoreException.cpp b/Source/core/dom/DOMCoreException.cpp
deleted file mode 100644
index 10488d5..0000000
--- a/Source/core/dom/DOMCoreException.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/DOMCoreException.h"
-
-#include "DOMException.h"
-
-namespace WebCore {
-
-static struct CoreException {
-    const char* const name;
-    const char* const description;
-} coreExceptions[] = {
-    { "IndexSizeError", "Index or size was negative, or greater than the allowed value." },
-    { 0, 0 }, // DOMStringSizeError
-    { "HierarchyRequestError", "A Node was inserted somewhere it doesn't belong." },
-    { "WrongDocumentError", "A Node was used in a different document than the one that created it (that doesn't support it)." },
-    { "InvalidCharacterError", "An invalid or illegal character was specified, such as in an XML name." },
-    { 0, 0 }, // NoDataAllowedError
-    { "NoModificationAllowedError", "An attempt was made to modify an object where modifications are not allowed." },
-    { "NotFoundError", "An attempt was made to reference a Node in a context where it does not exist." },
-    { "NotSupportedError", "The implementation did not support the requested type of object or operation." },
-    { "InUseAttributeError", "An attempt was made to add an attribute that is already in use elsewhere." },
-    { "InvalidStateError", "An attempt was made to use an object that is not, or is no longer, usable." },
-    { "SyntaxError", "An invalid or illegal string was specified." },
-    { "InvalidModificationError", "An attempt was made to modify the type of the underlying object." },
-    { "NamespaceError", "An attempt was made to create or change an object in a way which is incorrect with regard to namespaces." },
-    { "InvalidAccessError", "A parameter or an operation was not supported by the underlying object." },
-    { 0, 0 }, // ValidationError
-    { "TypeMismatchError", "The type of an object was incompatible with the expected type of the parameter associated to the object." },
-    { "SecurityError", "An attempt was made to break through the security policy of the user agent." },
-    // FIXME: Couldn't find a description in the HTML/DOM specifications for NETWORK_ERR, ABORT_ERR, URL_MISMATCH_ERR, and QUOTA_EXCEEDED_ERR
-    { "NetworkError", "A network error occurred." },
-    { "AbortError", "The user aborted a request." },
-    { "URLMismatchError", "A worker global scope represented an absolute URL that is not equal to the resulting absolute URL." },
-    { "QuotaExceededError", "An attempt was made to add something to storage that exceeded the quota." },
-    { "TimeoutError", "A timeout occurred." },
-    { "InvalidNodeTypeError", "The supplied node is invalid or has an invalid ancestor for this operation." },
-    { "DataCloneError", "An object could not be cloned." }
-};
-
-bool DOMCoreException::initializeDescription(ExceptionCode ec, ExceptionCodeDescription* description)
-{
-    description->typeName = "DOM";
-    description->code = ec;
-    description->type = DOMCoreExceptionType;
-
-    size_t tableSize = WTF_ARRAY_LENGTH(coreExceptions);
-    size_t tableIndex = ec - INDEX_SIZE_ERR;
-
-    description->name = tableIndex < tableSize ? coreExceptions[tableIndex].name : 0;
-    description->description = tableIndex < tableSize ? coreExceptions[tableIndex].description : 0;
-
-    return true;
-}
-
-} // namespace WebCore
diff --git a/Source/core/dom/DOMCoreException.h b/Source/core/dom/DOMCoreException.h
deleted file mode 100644
index 1a98c6e..0000000
--- a/Source/core/dom/DOMCoreException.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef DOMCoreException_h
-#define DOMCoreException_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/ExceptionBase.h"
-
-namespace WebCore {
-
-class DOMCoreException : public ExceptionBase, public ScriptWrappable {
-public:
-    static PassRefPtr<DOMCoreException> create(const ExceptionCodeDescription& description)
-    {
-        return adoptRef(new DOMCoreException(description));
-    }
-
-    static bool initializeDescription(ExceptionCode, ExceptionCodeDescription*);
-
-private:
-    explicit DOMCoreException(const ExceptionCodeDescription& description)
-        : ExceptionBase(description)
-    {
-        ScriptWrappable::init(this);
-    }
-};
-
-} // namespace WebCore
-
-#endif // DOMCoreException_h
diff --git a/Source/core/dom/DOMError.h b/Source/core/dom/DOMError.h
index b74b7f0..74d4d17 100644
--- a/Source/core/dom/DOMError.h
+++ b/Source/core/dom/DOMError.h
@@ -27,6 +27,8 @@
 #define DOMError_h
 
 #include "bindings/v8/ScriptWrappable.h"
+#include "core/dom/DOMException.h"
+#include "core/dom/ExceptionCode.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
@@ -44,6 +46,16 @@
         return adoptRef(new DOMError(name, message));
     }
 
+    static PassRefPtr<DOMError> create(ExceptionCode ec)
+    {
+        return adoptRef(new DOMError(DOMException::getErrorName(ec), DOMException::getErrorMessage(ec)));
+    }
+
+    static PassRefPtr<DOMError> create(ExceptionCode ec, const String& message)
+    {
+        return adoptRef(new DOMError(DOMException::getErrorName(ec), message));
+    }
+
     const String& name() const { return m_name; }
     const String& message() const { return m_message; }
 
diff --git a/Source/core/dom/DOMException.cpp b/Source/core/dom/DOMException.cpp
new file mode 100644
index 0000000..ff41cd3
--- /dev/null
+++ b/Source/core/dom/DOMException.cpp
@@ -0,0 +1,168 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1.  Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer.
+ * 2.  Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution.
+ * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
+ *     its contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY GOOGLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/dom/DOMException.h"
+
+#include "ExceptionCode.h"
+
+namespace WebCore {
+
+static struct CoreException {
+    const char* const name;
+    const char* const message;
+    const int code;
+} coreExceptions[] = {
+    { "IndexSizeError", "Index or size was negative, or greater than the allowed value.", 1 },
+    { "HierarchyRequestError", "A Node was inserted somewhere it doesn't belong.", 3 },
+    { "WrongDocumentError", "A Node was used in a different document than the one that created it (that doesn't support it).", 4 },
+    { "InvalidCharacterError", "An invalid or illegal character was specified, such as in an XML name.", 5 },
+    { "NoModificationAllowedError", "An attempt was made to modify an object where modifications are not allowed.", 7 },
+    { "NotFoundError", "An attempt was made to reference a Node in a context where it does not exist.", 8 },
+    { "NotSupportedError", "The implementation did not support the requested type of object or operation.", 9 },
+    { "InUseAttributeError", "An attempt was made to add an attribute that is already in use elsewhere.", 10 },
+    { "InvalidStateError", "An attempt was made to use an object that is not, or is no longer, usable.", 11 },
+    { "SyntaxError", "An invalid or illegal string was specified.", 12 },
+    { "InvalidModificationError", "An attempt was made to modify the type of the underlying object.", 13 },
+    { "NamespaceError", "An attempt was made to create or change an object in a way which is incorrect with regard to namespaces.", 14 },
+    { "InvalidAccessError", "A parameter or an operation was not supported by the underlying object.", 15 },
+    { "TypeMismatchError", "The type of an object was incompatible with the expected type of the parameter associated to the object.", 17 },
+    { "SecurityError", "An attempt was made to break through the security policy of the user agent.", 18 },
+    { "NetworkError", "A network error occurred.", 19 },
+    { "AbortError", "The user aborted a request.", 20 },
+    { "URLMismatchError", "A worker global scope represented an absolute URL that is not equal to the resulting absolute URL.", 21 },
+    { "QuotaExceededError", "An attempt was made to add something to storage that exceeded the quota.", 22 },
+    { "TimeoutError", "A timeout occurred.", 23 },
+    { "InvalidNodeTypeError", "The supplied node is invalid or has an invalid ancestor for this operation.", 24 },
+    { "DataCloneError", "An object could not be cloned.", 25 },
+
+    // These are IDB-specific errors.
+    // FIXME: NotFoundError is duplicated to have a more specific error message.
+    // https://code.google.com/p/chromium/issues/detail?id=252233
+    { "NotFoundError", "An operation failed because the requested database object could not be found.", 8 },
+
+    // More IDB-specific errors.
+    { "UnknownError", "An unknown error occurred within Indexed Database.", 0 },
+    { "ConstraintError", "A mutation operation in the transaction failed because a constraint was not satisfied.", 0 },
+    { "DataError", "The data provided does not meet requirements.", 0 },
+    { "TransactionInactiveError", "A request was placed against a transaction which is either currently not active, or which is finished.", 0 },
+    { "ReadOnlyError", "A write operation was attempted in a read-only transaction.", 0 },
+    { "VersionError", "An attempt was made to open a database using a lower version than the existing version.", 0 },
+
+    // File system
+    { "NotFoundError", "A requested file or directory could not be found at the time an operation was processed.", 8 },
+    { "SecurityError", "It was determined that certain files are unsafe for access within a Web application, or that too many calls are being made on file resources.", 18 },
+    { "AbortError", "An ongoing operation was aborted, typically with a call to abort().", 20 },
+    { "NotReadableError", "The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired.", 0 },
+    { "EncodingError", "A URI supplied to the API was malformed, or the resulting Data URL has exceeded the URL length limitations for Data URLs.", 0 },
+    { "NoModificationAllowedError", "An attempt was made to write to a file or directory which could not be modified due to the state of the underlying filesystem.", 7 },
+    { "InvalidStateError", "An operation that depends on state cached in an interface object was made but the state had changed since it was read from disk.", 11 },
+    { "SyntaxError", "An invalid or unsupported argument was given, like an invalid line ending specifier.", 12 },
+    { "InvalidModificationError", "The modification request was illegal.", 13 },
+    { "QuotaExceededError", "The operation failed because it would cause the application to exceed its storage quota.", 22 },
+    { "TypeMismatchError", "The path supplied exists, but was not an entry of requested type.", 17 },
+    { "PathExistsError", "An attempt was made to create a file or directory where an element already exists.", 0 },
+
+    // SQL
+    { "UnknownError", "The operation failed for reasons unrelated to the database.", 0 },
+    { "DatabaseError", "The operation failed for some reason related to the database.", 0 },
+    { "VersionError", "The actual database version did not match the expected version.", 0 },
+    { "TooLargeError", "Data returned from the database is too large.", 0 },
+    { "QuotaExceededError", "Quota was exceeded.", 22 },
+    { "SyntaxError", "Invalid or unauthorized statement; or the number of arguments did not match the number of ? placeholders.", 12 },
+    { "ConstraintError", "A constraint was violated.", 0 },
+    { "TimeoutError", "A transaction lock could not be acquired in a reasonable time.", 23 },
+};
+
+static const CoreException* getErrorEntry(ExceptionCode ec)
+{
+    size_t tableSize = WTF_ARRAY_LENGTH(coreExceptions);
+    size_t tableIndex = ec - INDEX_SIZE_ERR;
+
+    return tableIndex < tableSize ? &coreExceptions[tableIndex] : 0;
+}
+
+DOMException::DOMException(ExceptionCode ec)
+{
+    const CoreException* entry = getErrorEntry(ec);
+    ASSERT(entry);
+    if (!entry) {
+        m_code = 0;
+        m_name = "UnknownError";
+        m_message = "Unknown Error";
+    } else {
+        m_code = entry->code;
+        if (entry->name)
+            m_name = entry->name;
+        else
+            m_name = "Error";
+        m_message = entry->message;
+    }
+
+    ScriptWrappable::init(this);
+}
+
+PassRefPtr<DOMException> DOMException::create(ExceptionCode ec)
+{
+    return adoptRef(new DOMException(ec));
+}
+
+String DOMException::toString() const
+{
+    return name() + ": " + message();
+}
+
+String DOMException::getErrorName(ExceptionCode ec)
+{
+    const CoreException* entry = getErrorEntry(ec);
+    ASSERT(entry);
+    if (!entry)
+        return "UnknownError";
+
+    return entry->name;
+}
+
+String DOMException::getErrorMessage(ExceptionCode ec)
+{
+    const CoreException* entry = getErrorEntry(ec);
+    ASSERT(entry);
+    if (!entry)
+        return "Unknown error.";
+
+    return entry->message;
+}
+
+unsigned short DOMException::getLegacyErrorCode(ExceptionCode ec)
+{
+    const CoreException* entry = getErrorEntry(ec);
+    ASSERT(entry);
+
+    return (entry && entry->code) ? entry->code : 0;
+}
+
+} // namespace WebCore
diff --git a/Source/core/dom/ExceptionBase.h b/Source/core/dom/DOMException.h
similarity index 72%
rename from Source/core/dom/ExceptionBase.h
rename to Source/core/dom/DOMException.h
index d500f1e..88fbebb 100644
--- a/Source/core/dom/ExceptionBase.h
+++ b/Source/core/dom/DOMException.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
+ * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -26,35 +26,39 @@
  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ExceptionBase_h
-#define ExceptionBase_h
+#ifndef DOMException_h
+#define DOMException_h
 
-#include "core/dom/ExceptionCode.h"
-#include <wtf/RefCounted.h>
-#include <wtf/text/WTFString.h>
+#include "bindings/v8/ScriptWrappable.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
-struct ExceptionCodeDescription;
+typedef int ExceptionCode;
 
-class ExceptionBase : public RefCounted<ExceptionBase> {
+class DOMException : public RefCounted<DOMException>, public ScriptWrappable {
 public:
+    static PassRefPtr<DOMException> create(ExceptionCode);
+
     unsigned short code() const { return m_code; }
     String name() const { return m_name; }
-    String message() const { return description(); }
-    String description() const { return m_description; }
+    String message() const { return m_message; }
 
     String toString() const;
 
-protected:
-    explicit ExceptionBase(const ExceptionCodeDescription&);
+    static String getErrorName(ExceptionCode);
+    static String getErrorMessage(ExceptionCode);
+    static unsigned short getLegacyErrorCode(ExceptionCode);
 
 private:
+    explicit DOMException(ExceptionCode);
+
     unsigned short m_code;
     String m_name;
-    String m_description;
+    String m_message;
 };
 
 } // namespace WebCore
 
-#endif // ExceptionBase_h
+#endif // DOMException_h
diff --git a/Source/core/dom/DOMException.idl b/Source/core/dom/DOMException.idl
index d4e9520..68d04bf 100644
--- a/Source/core/dom/DOMException.idl
+++ b/Source/core/dom/DOMException.idl
@@ -27,8 +27,7 @@
  */
 
 [
-    DoNotCheckConstants,
-    ImplementedAs=DOMCoreException
+    DoNotCheckConstants
 ] exception DOMException {
 
     readonly attribute unsigned short   code;
diff --git a/Source/core/dom/DOMExceptions.in b/Source/core/dom/DOMExceptions.in
deleted file mode 100644
index 433d0ba..0000000
--- a/Source/core/dom/DOMExceptions.in
+++ /dev/null
@@ -1,7 +0,0 @@
-namespace=DOMException
-
-core/dom/DOMException implementedAs=DOMCoreException
-core/fileapi/FileException
-core/svg/SVGException
-core/xml/XPathException
-modules/webdatabase/SQLException
diff --git a/Source/core/dom/DOMImplementation.cpp b/Source/core/dom/DOMImplementation.cpp
index 87ed5dc..d9e8989 100644
--- a/Source/core/dom/DOMImplementation.cpp
+++ b/Source/core/dom/DOMImplementation.cpp
@@ -26,7 +26,6 @@
 #include "core/dom/DOMImplementation.h"
 
 #include "HTMLNames.h"
-#include "RuntimeEnabledFeatures.h"
 #include "SVGNames.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/MediaList.h"
diff --git a/Source/core/dom/DOMImplementation.h b/Source/core/dom/DOMImplementation.h
index fe2c31d..14dcdf7 100644
--- a/Source/core/dom/DOMImplementation.h
+++ b/Source/core/dom/DOMImplementation.h
@@ -25,10 +25,8 @@
 #define DOMImplementation_h
 
 #include "core/dom/Document.h"
-#include "core/platform/graphics/MediaPlayer.h"
-#include <wtf/Forward.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
+#include "wtf/Forward.h"
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/DatasetDOMStringMap.cpp b/Source/core/dom/DatasetDOMStringMap.cpp
index c16bdf5..d1db9f1 100644
--- a/Source/core/dom/DatasetDOMStringMap.cpp
+++ b/Source/core/dom/DatasetDOMStringMap.cpp
@@ -39,10 +39,9 @@
     if (!name.startsWith("data-"))
         return false;
 
-    const UChar* characters = name.characters();
     unsigned length = name.length();
     for (unsigned i = 5; i < length; ++i) {
-        if (isASCIIUpper(characters[i]))
+        if (isASCIIUpper(name[i]))
             return false;
     }
 
@@ -53,15 +52,14 @@
 {
     StringBuilder stringBuilder;
 
-    const UChar* characters = name.characters();
     unsigned length = name.length();
     for (unsigned i = 5; i < length; ++i) {
-        UChar character = characters[i];
+        UChar character = name[i];
         if (character != '-')
             stringBuilder.append(character);
         else {
-            if ((i + 1 < length) && isASCIILower(characters[i + 1])) {
-                stringBuilder.append(toASCIIUpper(characters[i + 1]));
+            if ((i + 1 < length) && isASCIILower(name[i + 1])) {
+                stringBuilder.append(toASCIIUpper(name[i + 1]));
                 ++i;
             } else
                 stringBuilder.append(character);
@@ -76,8 +74,6 @@
     if (!attributeName.startsWith("data-"))
         return false;
 
-    const UChar* property = propertyName.characters();
-    const UChar* attribute = attributeName.characters();
     unsigned propertyLength = propertyName.length();
     unsigned attributeLength = attributeName.length();
    
@@ -85,10 +81,10 @@
     unsigned p = 0;
     bool wordBoundary = false;
     while (a < attributeLength && p < propertyLength) {
-        if (attribute[a] == '-' && a + 1 < attributeLength && attribute[a + 1] != '-')
+        if (attributeName[a] == '-' && a + 1 < attributeLength && attributeName[a + 1] != '-')
             wordBoundary = true;
         else {
-            if ((wordBoundary ? toASCIIUpper(attribute[a]) : attribute[a]) != property[p])
+            if ((wordBoundary ? toASCIIUpper(attributeName[a]) : attributeName[a]) != propertyName[p])
                 return false;
             p++;
             wordBoundary = false;
@@ -101,10 +97,9 @@
 
 static bool isValidPropertyName(const String& name)
 {
-    const UChar* characters = name.characters();
     unsigned length = name.length();
     for (unsigned i = 0; i < length; ++i) {
-        if (characters[i] == '-' && (i + 1 < length) && isASCIILower(characters[i + 1]))
+        if (name[i] == '-' && (i + 1 < length) && isASCIILower(name[i + 1]))
             return false;
     }
     return true;
@@ -115,10 +110,9 @@
     StringBuilder builder;
     builder.append("data-");
 
-    const UChar* characters = name.characters();
     unsigned length = name.length();
     for (unsigned i = 0; i < length; ++i) {
-        UChar character = characters[i];
+        UChar character = name[i];
         if (isASCIIUpper(character)) {
             builder.append('-');
             builder.append(toASCIILower(character));
diff --git a/Source/core/dom/DecodedDataDocumentParser.cpp b/Source/core/dom/DecodedDataDocumentParser.cpp
index da89429..2f76a28 100644
--- a/Source/core/dom/DecodedDataDocumentParser.cpp
+++ b/Source/core/dom/DecodedDataDocumentParser.cpp
@@ -26,7 +26,7 @@
 #include "config.h"
 #include "core/dom/DecodedDataDocumentParser.h"
 
-#include "core/loader/DocumentWriter.h"
+#include "core/dom/Document.h"
 #include "core/loader/TextResourceDecoder.h"
 
 namespace WebCore {
@@ -36,27 +36,36 @@
 {
 }
 
-void DecodedDataDocumentParser::appendBytes(DocumentWriter* writer, const char* data, size_t length)
+size_t DecodedDataDocumentParser::appendBytes(const char* data, size_t length)
 {
     if (!length)
-        return;
+        return 0;
 
-    String decoded = writer->createDecoderIfNeeded()->decode(data, length);
+    String decoded = document()->decoder()->decode(data, length);
     if (decoded.isEmpty())
-        return;
+        return 0;
 
-    writer->reportDataReceived();
+    size_t consumedChars = decoded.length();
     append(decoded.releaseImpl());
+
+    return consumedChars;
 }
 
-void DecodedDataDocumentParser::flush(DocumentWriter* writer)
+size_t DecodedDataDocumentParser::flush()
 {
-    String remainingData = writer->createDecoderIfNeeded()->flush();
+    // null decoder indicates there is no data received.
+    // We have nothing to do in that case.
+    TextResourceDecoder* decoder = document()->decoder();
+    if (!decoder)
+        return 0;
+    String remainingData = decoder->flush();
     if (remainingData.isEmpty())
-        return;
+        return 0;
 
-    writer->reportDataReceived();
+    size_t consumedChars = remainingData.length();
     append(remainingData.releaseImpl());
+
+    return consumedChars;
 }
 
 };
diff --git a/Source/core/dom/DecodedDataDocumentParser.h b/Source/core/dom/DecodedDataDocumentParser.h
index 4e61a93..ea13ff6 100644
--- a/Source/core/dom/DecodedDataDocumentParser.h
+++ b/Source/core/dom/DecodedDataDocumentParser.h
@@ -44,8 +44,9 @@
     virtual void append(PassRefPtr<StringImpl>) = 0;
 
     // appendBytes and flush are used by DocumentWriter (the loader).
-    virtual void appendBytes(DocumentWriter*, const char* bytes, size_t length);
-    virtual void flush(DocumentWriter*);
+    virtual size_t appendBytes(const char* bytes, size_t length) OVERRIDE;
+    virtual size_t flush() OVERRIDE;
+    virtual bool needsDecoder() const OVERRIDE { return true; }
 };
 
 }
diff --git a/Source/core/dom/DeviceOrientationController.cpp b/Source/core/dom/DeviceOrientationController.cpp
index bc9df50..460e1fb 100644
--- a/Source/core/dom/DeviceOrientationController.cpp
+++ b/Source/core/dom/DeviceOrientationController.cpp
@@ -28,7 +28,6 @@
 #include "core/dom/DeviceOrientationController.h"
 
 #include "core/dom/DeviceOrientationClient.h"
-#include "core/dom/DeviceOrientationData.h"
 #include "core/dom/DeviceOrientationEvent.h"
 #include "core/inspector/InspectorInstrumentation.h"
 
diff --git a/Source/core/dom/DeviceOrientationController.h b/Source/core/dom/DeviceOrientationController.h
index 922a54d..3173d39 100644
--- a/Source/core/dom/DeviceOrientationController.h
+++ b/Source/core/dom/DeviceOrientationController.h
@@ -28,7 +28,6 @@
 #define DeviceOrientationController_h
 
 #include "core/page/DeviceController.h"
-#include <wtf/HashCountedSet.h>
 
 namespace WebCore {
 
diff --git a/Source/core/dom/Document.cpp b/Source/core/dom/Document.cpp
index 6f0e65b..b296bc1 100644
--- a/Source/core/dom/Document.cpp
+++ b/Source/core/dom/Document.cpp
@@ -28,7 +28,6 @@
 #include "config.h"
 #include "core/dom/Document.h"
 
-#include "CSSValueKeywords.h"
 #include "HTMLElementFactory.h"
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
@@ -36,23 +35,20 @@
 #include "SVGNames.h"
 #include "XMLNSNames.h"
 #include "XMLNames.h"
+#include "bindings/v8/CustomElementConstructorBuilder.h"
 #include "bindings/v8/Dictionary.h"
 #include "bindings/v8/ScriptController.h"
-#include "bindings/v8/ScriptEventListener.h"
 #include "core/accessibility/AXObjectCache.h"
 #include "core/animation/DocumentTimeline.h"
-#include "core/css/CSSParser.h"
 #include "core/css/CSSStyleDeclaration.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/css/FontLoader.h"
-#include "core/css/MediaQueryList.h"
 #include "core/css/MediaQueryMatcher.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleSheetContents.h"
 #include "core/css/StyleSheetList.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Attr.h"
-#include "core/dom/Attribute.h"
 #include "core/dom/CDATASection.h"
 #include "core/dom/Comment.h"
 #include "core/dom/ContextFeatures.h"
@@ -74,7 +70,6 @@
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/ExceptionCodePlaceholder.h"
 #include "core/dom/HashChangeEvent.h"
-#include "core/dom/NameNodeList.h"
 #include "core/dom/NamedFlowCollection.h"
 #include "core/dom/NodeFilter.h"
 #include "core/dom/NodeIterator.h"
@@ -86,10 +81,8 @@
 #include "core/dom/PopStateEvent.h"
 #include "core/dom/ProcessingInstruction.h"
 #include "core/dom/QualifiedName.h"
-#include "core/dom/RegisteredEventListener.h"
 #include "core/dom/RequestAnimationFrameCallback.h"
 #include "core/dom/ScopedEventQueue.h"
-#include "core/dom/ScriptElement.h"
 #include "core/dom/ScriptRunner.h"
 #include "core/dom/ScriptedAnimationController.h"
 #include "core/dom/SelectorQuery.h"
@@ -103,11 +96,9 @@
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
-#include "core/editing/htmlediting.h"
 #include "core/html/FormController.h"
 #include "core/html/HTMLAllCollection.h"
 #include "core/html/HTMLAnchorElement.h"
-#include "core/html/HTMLBodyElement.h"
 #include "core/html/HTMLCanvasElement.h"
 #include "core/html/HTMLCollection.h"
 #include "core/html/HTMLDocument.h"
@@ -116,7 +107,6 @@
 #include "core/html/HTMLIFrameElement.h"
 #include "core/html/HTMLImportsController.h"
 #include "core/html/HTMLLinkElement.h"
-#include "core/html/HTMLMapElement.h"
 #include "core/html/HTMLNameCollection.h"
 #include "core/html/HTMLScriptElement.h"
 #include "core/html/HTMLStyleElement.h"
@@ -131,21 +121,16 @@
 #include "core/loader/CookieJar.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/FrameLoaderClient.h"
 #include "core/loader/ImageLoader.h"
 #include "core/loader/Prerenderer.h"
-#include "core/loader/ResourceLoader.h"
 #include "core/loader/TextResourceDecoder.h"
-#include "core/loader/cache/CachedCSSStyleSheet.h"
 #include "core/loader/cache/CachedResourceLoader.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "core/page/DOMSecurityPolicy.h"
-#include "core/page/DOMSelection.h"
 #include "core/page/DOMWindow.h"
 #include "core/page/EventHandler.h"
-#include "core/page/FocusController.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameTree.h"
 #include "core/page/FrameView.h"
@@ -153,48 +138,36 @@
 #include "core/page/MouseEventWithHitTestResults.h"
 #include "core/page/Page.h"
 #include "core/page/PageConsole.h"
-#include "core/page/PageGroup.h"
 #include "core/page/PointerLockController.h"
 #include "core/page/Settings.h"
-#include "core/page/UserContentURLPattern.h"
 #include "core/page/ValidationMessageClient.h"
 #include "core/page/animation/AnimationController.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/platform/DateComponents.h"
 #include "core/platform/HistogramSupport.h"
 #include "core/platform/Language.h"
-#include "core/platform/Logging.h"
-#include "core/platform/PlatformKeyboardEvent.h"
 #include "core/platform/Timer.h"
 #include "core/platform/chromium/TraceEvent.h"
 #include "core/platform/network/HTTPParsers.h"
 #include "core/platform/text/PlatformLocale.h"
 #include "core/platform/text/SegmentedString.h"
-#include "core/rendering/FlowThreadController.h"
 #include "core/rendering/HitTestRequest.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderArena.h"
-#include "core/rendering/RenderLayerCompositor.h"
-#include "core/rendering/RenderNamedFlowThread.h"
-#include "core/rendering/RenderTextControl.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/RenderWidget.h"
 #include "core/rendering/TextAutosizer.h"
 #include "core/svg/SVGDocumentExtensions.h"
-#include "core/svg/SVGSVGElement.h"
 #include "core/svg/SVGStyleElement.h"
 #include "core/workers/SharedWorkerRepository.h"
-#include "core/xml/XMLHttpRequest.h"
 #include "core/xml/XPathEvaluator.h"
 #include "core/xml/XPathExpression.h"
 #include "core/xml/XPathNSResolver.h"
 #include "core/xml/XPathResult.h"
 #include "core/xml/XSLTProcessor.h"
 #include "core/xml/parser/XMLDocumentParser.h"
-#include "modules/geolocation/GeolocationController.h"
 #include "weborigin/SchemeRegistry.h"
 #include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/HashFunctions.h"
 #include "wtf/MainThread.h"
@@ -435,7 +408,6 @@
     , m_closeAfterStyleRecalc(false)
     , m_gotoAnchorNeededAfterStylesheetsLoad(false)
     , m_pendingStyleRecalcShouldForce(false)
-    , m_frameElementsShouldIgnoreScrolling(false)
     , m_containsValidityStyleRules(false)
     , m_updateFocusAppearanceRestoresSelection(false)
     , m_ignoreDestructiveWriteCount(0)
@@ -643,8 +615,7 @@
         m_scriptedAnimationController->clearDocumentPointer();
     m_scriptedAnimationController.clear();
 
-    if (m_lifecycleNotifier)
-        m_lifecycleNotifier->notifyDocumentWasDisposed();
+    lifecycleNotifier()->notifyDocumentWasDisposed();
 }
 
 Element* Document::getElementById(const AtomicString& id) const
@@ -842,7 +813,9 @@
         return ScriptValue();
     }
 
-    return ensureCustomElementRegistry()->registerElement(state, name, options, ec);
+    CustomElementConstructorBuilder constructorBuilder(state, &options);
+    ensureCustomElementRegistry()->registerElement(&constructorBuilder, name, ec);
+    return constructorBuilder.bindingsReturnValue();
 }
 
 CustomElementRegistry* Document::ensureCustomElementRegistry()
@@ -854,11 +827,10 @@
     return m_registry.get();
 }
 
-HTMLImportsController* Document::ensureImports()
+void Document::setImports(PassRefPtr<HTMLImportsController> imports)
 {
-    if (!m_imports)
-        m_imports = HTMLImportsController::create(this);
-    return m_imports.get();
+    ASSERT(!m_imports);
+    m_imports = imports;
 }
 
 void Document::didLoadAllImports()
@@ -962,7 +934,7 @@
         return newElement.release();
     }
     case ATTRIBUTE_NODE:
-        return Attr::create(this, QualifiedName(nullAtom, static_cast<Attr*>(importedNode)->name(), nullAtom), static_cast<Attr*>(importedNode)->value());
+        return Attr::create(this, QualifiedName(nullAtom, toAttr(importedNode)->name(), nullAtom), toAttr(importedNode)->value());
     case DOCUMENT_FRAGMENT_NODE: {
         if (importedNode->isShadowRoot()) {
             // ShadowRoot nodes should not be explicitly importable.
@@ -1016,7 +988,7 @@
         ec = NOT_SUPPORTED_ERR;
         return 0;
     case ATTRIBUTE_NODE: {
-        Attr* attr = static_cast<Attr*>(source.get());
+        Attr* attr = toAttr(source.get());
         if (attr->ownerElement())
             attr->ownerElement()->removeAttributeNode(attr, ec);
         attr->setSpecified(true);
@@ -1680,6 +1652,7 @@
         return; // Guard against re-entrancy. -dwh
 
     TRACE_EVENT0("webkit", "Document::recalcStyle");
+    TraceEvent::SamplingState0Scope("Blink\0Blink-RecalcStyle");
 
     // FIXME: We should update style on our ancestor chain before proceeding (especially for seamless),
     // however doing so currently causes several tests to crash, as Frame::setDocument calls Document::attach
@@ -1689,7 +1662,7 @@
     // hits a null-dereference due to security code always assuming the document has a SecurityOrigin.
 
     if (m_styleSheetCollection->needsUpdateActiveStylesheetsOnStyleRecalc())
-        m_styleSheetCollection->updateActiveStyleSheets(DocumentStyleSheetCollection::FullUpdate);
+        m_styleSheetCollection->updateActiveStyleSheets(FullStyleUpdate);
 
     InspectorInstrumentationCookie cookie = InspectorInstrumentation::willRecalculateStyle(this);
 
@@ -1760,6 +1733,12 @@
     }
 
     InspectorInstrumentation::didRecalculateStyle(cookie);
+
+    // As a result of the style recalculation, the currently hovered element might have been
+    // detached (for example, by setting display:none in the :hover style), schedule another mouseMove event
+    // to check if any other elements ended up under the mouse pointer due to re-layout.
+    if (hoverNode() && !hoverNode()->renderer() && frame())
+        frame()->eventHandler()->dispatchFakeMouseMoveEventSoon();
 }
 
 void Document::updateStyleIfNeeded()
@@ -1774,6 +1753,18 @@
     recalcStyle(NoChange);
 }
 
+void Document::updateStyleForNodeIfNeeded(Node* node)
+{
+    if (!hasPendingForcedStyleRecalc() && !childNeedsStyleRecalc() && !needsStyleRecalc())
+        return;
+
+    bool needsStyleRecalc = hasPendingForcedStyleRecalc();
+    for (Node* n = node; n && !needsStyleRecalc; n = n->parentNode())
+        needsStyleRecalc = n->needsStyleRecalc();
+    if (needsStyleRecalc)
+        updateStyleIfNeeded();
+}
+
 void Document::updateLayout()
 {
     ASSERT(isMainThread());
@@ -2002,8 +1993,7 @@
     if (m_mediaQueryMatcher)
         m_mediaQueryMatcher->documentDestroyed();
 
-    if (m_lifecycleNotifier)
-        m_lifecycleNotifier->notifyDocumentWasDetached();
+    lifecycleNotifier()->notifyDocumentWasDetached();
 }
 
 void Document::prepareForDestruction()
@@ -2162,11 +2152,12 @@
     explicitClose();
 }
 
-void Document::implicitOpen()
+PassRefPtr<DocumentParser> Document::implicitOpen()
 {
     cancelParsing();
 
     removeChildren();
+    ASSERT(!m_focusedNode);
 
     setCompatibilityMode(NoQuirksMode);
 
@@ -2179,6 +2170,8 @@
     m_parser = createParser();
     setParsing(true);
     setReadyState(Loading);
+
+    return m_parser;
 }
 
 HTMLElement* Document::body() const
@@ -2295,12 +2288,14 @@
     if (f)
         f->animation()->resumeAnimationsForDocument(this);
 
-    ImageLoader::dispatchPendingBeforeLoadEvents();
-    ImageLoader::dispatchPendingLoadEvents();
-    ImageLoader::dispatchPendingErrorEvents();
+    if (f && f->script()->canExecuteScripts(NotAboutToExecuteScript)) {
+        ImageLoader::dispatchPendingBeforeLoadEvents();
+        ImageLoader::dispatchPendingLoadEvents();
+        ImageLoader::dispatchPendingErrorEvents();
 
-    HTMLLinkElement::dispatchPendingLoadEvents();
-    HTMLStyleElement::dispatchPendingLoadEvents();
+        HTMLLinkElement::dispatchPendingLoadEvents();
+        HTMLStyleElement::dispatchPendingLoadEvents();
+    }
 
     // To align the HTML load event and the SVGLoad event for the outermost <svg> element, fire it from
     // here, instead of doing it from SVGElement::finishedParsingChildren (if externalResourcesRequired="false",
@@ -2688,7 +2683,7 @@
 {
     m_needsNotifyRemoveAllPendingStylesheet = false;
 
-    styleResolverChanged(RecalcStyleIfNeeded);
+    styleResolverChanged(RecalcStyleImmediately, AnalyzedStyleUpdate);
     executeScriptsWaitingForResourcesIfNeeded();
 
     if (m_gotoAnchorNeededAfterStylesheetsLoad && view())
@@ -3052,7 +3047,7 @@
         m_mediaQueryMatcher->styleResolverChanged();
 }
 
-void Document::styleResolverChanged(StyleResolverUpdateFlag updateFlag)
+void Document::styleResolverChanged(StyleResolverUpdateType updateType, StyleResolverUpdateMode updateMode)
 {
     // Don't bother updating, since we haven't loaded all our style info yet
     // and haven't calculated the style selector for the first time.
@@ -3067,12 +3062,9 @@
         printf("Beginning update of style selector at time %d.\n", elapsedTime());
 #endif
 
-    DocumentStyleSheetCollection::UpdateFlag styleSheetUpdate = (updateFlag == RecalcStyleIfNeeded)
-        ? DocumentStyleSheetCollection::OptimizedUpdate
-        : DocumentStyleSheetCollection::FullUpdate;
-    bool stylesheetChangeRequiresStyleRecalc = m_styleSheetCollection->updateActiveStyleSheets(styleSheetUpdate);
+    bool needsRecalc = m_styleSheetCollection->updateActiveStyleSheets(updateMode);
 
-    if (updateFlag == DeferRecalcStyle) {
+    if (updateType >= DeferRecalcStyle) {
         scheduleForcedStyleRecalc();
         return;
     }
@@ -3083,7 +3075,7 @@
             renderView()->repaintViewAndCompositedLayers();
     }
 
-    if (!stylesheetChangeRequiresStyleRecalc)
+    if (!needsRecalc)
         return;
 
     // This recalcStyle initiates a new recalc cycle. We need to bracket it to
@@ -3138,11 +3130,6 @@
     m_activeElement = newActiveElement;
 }
 
-void Document::focusedNodeRemoved()
-{
-    setFocusedNode(0);
-}
-
 void Document::removeFocusedNodeOfSubtree(Node* node, bool amongChildrenOnly)
 {
     if (!m_focusedNode)
@@ -3159,7 +3146,7 @@
         nodeInSubtree = (focusedNode == node) || focusedNode->isDescendantOf(node);
 
     if (nodeInSubtree)
-        document()->focusedNodeRemoved();
+        setFocusedNode(0);
 }
 
 void Document::hoveredNodeDetached(Node* node)
@@ -3344,6 +3331,8 @@
 
 SetFocusedNodeDone:
     updateStyleIfNeeded();
+    if (Frame* frame = this->frame())
+        frame->selection()->didChangeFocus();
     return !focusChangeBlocked;
 }
 
@@ -3826,7 +3815,7 @@
     bool sawColon = false;
     int colonPos = 0;
 
-    const UChar* s = qualifiedName.characters();
+    const UChar* s = qualifiedName.bloatedCharacters();
     for (unsigned i = 0; i < length;) {
         UChar32 c;
         U16_NEXT(s, i, length, c)
@@ -4134,6 +4123,12 @@
     return ensureCachedCollection(DocAnchors);
 }
 
+PassRefPtr<HTMLCollection> Document::allForBinding()
+{
+    UseCounter::count(this, UseCounter::DocumentAll);
+    return all();
+}
+
 PassRefPtr<HTMLCollection> Document::all()
 {
     return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLAllCollection>(this, DocAll);
@@ -4479,8 +4474,10 @@
 HTMLCanvasElement* Document::getCSSCanvasElement(const String& name)
 {
     RefPtr<HTMLCanvasElement>& element = m_cssCanvasElements.add(name, 0).iterator->value;
-    if (!element)
+    if (!element) {
         element = HTMLCanvasElement::create(this);
+        element->setAccelerationDisabled(true);
+    }
     return element.get();
 }
 
@@ -4528,7 +4525,7 @@
     }
 
     if (Page* page = this->page())
-        page->console()->addMessage(source, level, message, sourceURL, lineNumber, callStack, state, requestIdentifier);
+        page->console()->addMessage(source, level, message, sourceURL, lineNumber, 0, callStack, state, requestIdentifier);
 }
 
 const SecurityOrigin* Document::topOrigin() const
@@ -5050,11 +5047,14 @@
 
     if (oldHoverObj != newHoverObj) {
         // If the old hovered node is not nil but it's renderer is, it was probably detached as part of the :hover style
-        // (for instance by setting display:none in the :hover pseudo-class). In this case, the old hovered element
+        // (for instance by setting display:none in the :hover pseudo-class). In this case, the old hovered element (and its ancestors)
         // must be updated, to ensure it's normal style is re-applied.
         if (oldHoverNode && !oldHoverObj) {
-            if (!mustBeInActiveChain || oldHoverNode->inActiveChain())
-                nodesToRemoveFromChain.append(oldHoverNode);
+            for (Node* node = oldHoverNode.get(); node; node = node->parentNode()) {
+                if (!mustBeInActiveChain || (node->isElementNode() && toElement(node)->inActiveChain()))
+                    nodesToRemoveFromChain.append(node);
+            }
+
         }
 
         // The old hover path only needs to be cleared up to (and not including) the common ancestor;
@@ -5226,11 +5226,14 @@
     m_associatedFormControls.clear();
 }
 
-void Document::addLifecycleObserver(DocumentLifecycleObserver* observer)
+PassOwnPtr<ContextLifecycleNotifier> Document::createLifecycleNotifier()
 {
-    if (!m_lifecycleNotifier)
-        m_lifecycleNotifier = DocumentLifecycleNotifier::create();
-    m_lifecycleNotifier->addObserver(observer);
+    return DocumentLifecycleNotifier::create(this);
+}
+
+DocumentLifecycleNotifier* Document::lifecycleNotifier()
+{
+    return static_cast<DocumentLifecycleNotifier*>(ScriptExecutionContext::lifecycleNotifier());
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/Document.h b/Source/core/dom/Document.h
index 8c28505..e77c623 100644
--- a/Source/core/dom/Document.h
+++ b/Source/core/dom/Document.h
@@ -41,23 +41,19 @@
 #include "core/dom/UserActionElementSet.h"
 #include "core/dom/ViewportArguments.h"
 #include "core/html/CollectionType.h"
-#include "core/inspector/InspectorCounters.h"
 #include "core/page/FocusDirection.h"
 #include "core/page/PageVisibilityState.h"
-#include "core/platform/PlatformScreen.h"
 #include "weborigin/ReferrerPolicy.h"
 #include "core/platform/Timer.h"
 #include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/IntRect.h"
 #include "core/platform/text/StringWithDirection.h"
 #include "core/rendering/HitTestRequest.h"
-#include <wtf/Deque.h>
-#include <wtf/FixedArray.h>
-#include <wtf/HashSet.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/WeakPtr.h>
+#include "wtf/Deque.h"
+#include "wtf/HashSet.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/WeakPtr.h"
 
 namespace WebCore {
 
@@ -174,7 +170,16 @@
     PageshowEventPersisted = 1
 };
 
-enum StyleResolverUpdateFlag { RecalcStyleImmediately, DeferRecalcStyle, RecalcStyleIfNeeded };
+// FIXME: We should rename DeferRecalcStyle to RecalcStyleDeferred to be consitent.
+
+enum StyleResolverUpdateType { RecalcStyleImmediately, DeferRecalcStyle };
+
+enum StyleResolverUpdateMode {
+    // Discards the StyleResolver and rebuilds it.
+    FullStyleUpdate,
+    // Attempts to use StyleInvalidationAnalysis to avoid discarding the entire StyleResolver.
+    AnalyzedStyleUpdate
+};
 
 enum NodeListInvalidationType {
     DoNotInvalidateOnAttributeChanges = 0,
@@ -395,6 +400,7 @@
     PassRefPtr<HTMLCollection> forms();
     PassRefPtr<HTMLCollection> anchors();
     PassRefPtr<HTMLCollection> scripts();
+    PassRefPtr<HTMLCollection> allForBinding();
     PassRefPtr<HTMLCollection> all();
 
     PassRefPtr<HTMLCollection> windowNamedItems(const AtomicString& name);
@@ -440,16 +446,8 @@
     bool gotoAnchorNeededAfterStylesheetsLoad() { return m_gotoAnchorNeededAfterStylesheetsLoad; }
     void setGotoAnchorNeededAfterStylesheetsLoad(bool b) { m_gotoAnchorNeededAfterStylesheetsLoad = b; }
 
-    /**
-     * Called when one or more stylesheets in the document may have been added, removed or changed.
-     *
-     * Creates a new style resolver and assign it to this document. This is done by iterating through all nodes in
-     * document (or those before <BODY> in a HTML document), searching for stylesheets. Stylesheets can be contained in
-     * <LINK>, <STYLE> or <BODY> elements, as well as processing instructions (XML documents only). A list is
-     * constructed from these which is used to create the a new style selector which collates all of the stylesheets
-     * found and is used to calculate the derived styles for all rendering objects.
-     */
-    void styleResolverChanged(StyleResolverUpdateFlag);
+    // Called when one or more stylesheets in the document may have been added, removed, or changed.
+    void styleResolverChanged(StyleResolverUpdateType, StyleResolverUpdateMode = FullStyleUpdate);
 
     void didAccessStyleResolver();
 
@@ -484,6 +482,7 @@
     void recalcStyle(StyleChange = NoChange);
     bool childNeedsAndNotInStyleRecalc();
     void updateStyleIfNeeded();
+    void updateStyleForNodeIfNeeded(Node*);
     void updateLayout();
     void updateLayoutIgnorePendingStylesheets();
     PassRefPtr<RenderStyle> styleForElementIgnoringPendingStylesheets(Element*);
@@ -533,7 +532,7 @@
     DocumentLoader* loader() const;
 
     void open(Document* ownerDocument = 0);
-    void implicitOpen();
+    PassRefPtr<DocumentParser> implicitOpen();
 
     // close() is the DOM API document.close()
     void close();
@@ -656,7 +655,6 @@
     void setActiveElement(PassRefPtr<Element>);
     Element* activeElement() const { return m_activeElement.get(); }
 
-    void focusedNodeRemoved();
     void removeFocusedNodeOfSubtree(Node*, bool amongChildrenOnly = false);
     void hoveredNodeDetached(Node*);
     void activeChainNodeDetached(Node*);
@@ -928,10 +926,6 @@
         displayBufferModifiedByEncodingInternal(buffer, len);
     }
 
-    // Quirk for the benefit of Apple's Dictionary application.
-    void setFrameElementsShouldIgnoreScrolling(bool ignore) { m_frameElementsShouldIgnoreScrolling = ignore; }
-    bool frameElementsShouldIgnoreScrolling() const { return m_frameElementsShouldIgnoreScrolling; }
-
     void setAnnotatedRegionsDirty(bool f) { m_annotatedRegionsDirty = f; }
     bool annotatedRegionsDirty() const { return m_annotatedRegionsDirty; }
     bool hasAnnotatedRegions () const { return m_hasAnnotatedRegions; }
@@ -1027,7 +1021,7 @@
     CustomElementRegistry* registry() const { return m_registry.get(); }
     CustomElementRegistry* ensureCustomElementRegistry();
 
-    HTMLImportsController* ensureImports();
+    void setImports(PassRefPtr<HTMLImportsController>);
     HTMLImportsController* imports() const { return m_imports.get(); }
     bool haveImportsLoaded() const;
     void didLoadAllImports();
@@ -1076,8 +1070,7 @@
     virtual const SecurityOrigin* topOrigin() const OVERRIDE;
 
     PassRefPtr<FontLoader> fontloader();
-
-    void addLifecycleObserver(DocumentLifecycleObserver*);
+    DocumentLifecycleNotifier* lifecycleNotifier();
 
 protected:
     Document(Frame*, const KURL&, DocumentClassFlags = DefaultDocumentClass);
@@ -1108,6 +1101,7 @@
 
     virtual void refScriptExecutionContext() { ref(); }
     virtual void derefScriptExecutionContext() { deref(); }
+    virtual PassOwnPtr<ContextLifecycleNotifier> createLifecycleNotifier() OVERRIDE;
 
     virtual const KURL& virtualURL() const; // Same as url(), but needed for ScriptExecutionContext to implement it without a performance loss for direct calls.
     virtual KURL virtualCompleteURL(const String&) const; // Same as completeURL() for the same reason as above.
@@ -1252,7 +1246,6 @@
     bool m_gotoAnchorNeededAfterStylesheetsLoad;
     bool m_isDNSPrefetchEnabled;
     bool m_haveExplicitlyDisabledDNSPrefetch;
-    bool m_frameElementsShouldIgnoreScrolling;
     bool m_containsValidityStyleRules;
     bool m_updateFocusAppearanceRestoresSelection;
 
@@ -1371,7 +1364,7 @@
     OwnPtr<TextAutosizer> m_textAutosizer;
 
     RefPtr<CustomElementRegistry> m_registry;
-    OwnPtr<HTMLImportsController> m_imports;
+    RefPtr<HTMLImportsController> m_imports;
 
     bool m_scheduledTasksAreSuspended;
     
@@ -1400,8 +1393,6 @@
 
     Timer<Document> m_didAssociateFormControlsTimer;
     HashSet<RefPtr<Element> > m_associatedFormControls;
-
-    OwnPtr<DocumentLifecycleNotifier> m_lifecycleNotifier;
 };
 
 inline void Document::notifyRemovePendingSheetIfNeeded()
diff --git a/Source/core/dom/Document.idl b/Source/core/dom/Document.idl
index 6d7fb1b..7afd390 100644
--- a/Source/core/dom/Document.idl
+++ b/Source/core/dom/Document.idl
@@ -285,3 +285,5 @@
     readonly attribute HTMLScriptElement currentScript;
 };
 
+Document implements ParentNode;
+
diff --git a/Source/core/dom/DocumentEventQueue.cpp b/Source/core/dom/DocumentEventQueue.cpp
index af1c3c7..b32cb00 100644
--- a/Source/core/dom/DocumentEventQueue.cpp
+++ b/Source/core/dom/DocumentEventQueue.cpp
@@ -33,8 +33,8 @@
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/page/DOMWindow.h"
 #include "core/page/SuspendableTimer.h"
-#include <wtf/MemoryInstrumentationHashSet.h>
-#include <wtf/MemoryInstrumentationListHashSet.h>
+#include "wtf/MemoryInstrumentationHashSet.h"
+#include "wtf/MemoryInstrumentationListHashSet.h"
 
 namespace WebCore {
     
diff --git a/Source/core/dom/DocumentEventQueue.h b/Source/core/dom/DocumentEventQueue.h
index 233192a..d877833 100644
--- a/Source/core/dom/DocumentEventQueue.h
+++ b/Source/core/dom/DocumentEventQueue.h
@@ -28,12 +28,11 @@
 #define DocumentEventQueue_h
 
 #include "core/dom/EventQueue.h"
-#include <wtf/Forward.h>
-#include <wtf/HashSet.h>
-#include <wtf/ListHashSet.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
+#include "wtf/Forward.h"
+#include "wtf/HashSet.h"
+#include "wtf/ListHashSet.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/DocumentFragment.h b/Source/core/dom/DocumentFragment.h
index 5d713fe..08ede54 100644
--- a/Source/core/dom/DocumentFragment.h
+++ b/Source/core/dom/DocumentFragment.h
@@ -25,7 +25,7 @@
 #define DocumentFragment_h
 
 #include "core/dom/ContainerNode.h"
-#include "core/dom/FragmentScriptingPermission.h"
+#include "core/dom/ParserContentPolicy.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/DocumentFragment.idl b/Source/core/dom/DocumentFragment.idl
index 6cd787a..076c949 100644
--- a/Source/core/dom/DocumentFragment.idl
+++ b/Source/core/dom/DocumentFragment.idl
@@ -26,3 +26,5 @@
     [RaisesException] NodeList querySelectorAll(DOMString selectors);
 };
 
+DocumentFragment implements ParentNode;
+
diff --git a/Source/core/dom/DocumentFullscreen.cpp b/Source/core/dom/DocumentFullscreen.cpp
index 472682c..17bc1ee 100644
--- a/Source/core/dom/DocumentFullscreen.cpp
+++ b/Source/core/dom/DocumentFullscreen.cpp
@@ -26,7 +26,6 @@
 #include "config.h"
 #include "core/dom/DocumentFullscreen.h"
 
-#include "core/dom/Document.h"
 #include "core/dom/FullscreenController.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/DocumentLifecycleObserver.cpp b/Source/core/dom/DocumentLifecycleObserver.cpp
index 2a231ac..2af13c0 100644
--- a/Source/core/dom/DocumentLifecycleObserver.cpp
+++ b/Source/core/dom/DocumentLifecycleObserver.cpp
@@ -32,21 +32,38 @@
 namespace WebCore {
 
 DocumentLifecycleObserver::DocumentLifecycleObserver(Document* document)
-    : ContextDestructionObserver(document)
+    : ContextLifecycleObserver(document, DocumentLifecycleObserverType)
 {
-    document->addLifecycleObserver(this);
 }
 
-PassOwnPtr<DocumentLifecycleNotifier> DocumentLifecycleNotifier::create()
+DocumentLifecycleObserver::~DocumentLifecycleObserver()
 {
-    return adoptPtr(new DocumentLifecycleNotifier());
+    observeContext(0, DocumentLifecycleObserverType);
 }
 
-void DocumentLifecycleNotifier::addObserver(DocumentLifecycleObserver* observer)
+DocumentLifecycleNotifier::DocumentLifecycleNotifier(ScriptExecutionContext* context)
+    : ContextLifecycleNotifier(context)
 {
-    ASSERT(!m_iterating);
-    ASSERT(!m_observers.contains(observer));
-    m_observers.append(observer);
+}
+
+void DocumentLifecycleNotifier::addObserver(ContextLifecycleObserver* observer, ContextLifecycleObserver::Type as)
+{
+    if (as == ContextLifecycleObserver::DocumentLifecycleObserverType) {
+        RELEASE_ASSERT(m_iterating != IteratingOverDocumentObservers);
+        m_documentObservers.add(static_cast<DocumentLifecycleObserver*>(observer));
+    }
+
+    ContextLifecycleNotifier::addObserver(observer, as);
+}
+
+void DocumentLifecycleNotifier::removeObserver(ContextLifecycleObserver* observer, ContextLifecycleObserver::Type as)
+{
+    if (as == ContextLifecycleObserver::DocumentLifecycleObserverType) {
+        RELEASE_ASSERT(m_iterating != IteratingOverDocumentObservers);
+        m_documentObservers.remove(static_cast<DocumentLifecycleObserver*>(observer));
+    }
+
+    ContextLifecycleNotifier::removeObserver(observer, as);
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/DocumentLifecycleObserver.h b/Source/core/dom/DocumentLifecycleObserver.h
index d6d0263..47a449f 100644
--- a/Source/core/dom/DocumentLifecycleObserver.h
+++ b/Source/core/dom/DocumentLifecycleObserver.h
@@ -26,61 +26,58 @@
 #ifndef DocumentLifecycleObserver_h
 #define DocumentLifecycleObserver_h
 
-#include "core/dom/ContextDestructionObserver.h"
+#include "core/dom/ContextLifecycleNotifier.h"
+#include "core/dom/ContextLifecycleObserver.h"
 #include "wtf/Assertions.h"
 #include "wtf/PassOwnPtr.h"
-#include "wtf/Vector.h"
+#include "wtf/TemporaryChange.h"
 
 namespace WebCore {
 
 class Document;
 
-class DocumentLifecycleObserver : public ContextDestructionObserver {
+class DocumentLifecycleObserver : public ContextLifecycleObserver {
 public:
     explicit DocumentLifecycleObserver(Document*);
-    virtual ~DocumentLifecycleObserver() { }
+    virtual ~DocumentLifecycleObserver();
     virtual void documentWasDetached() { }
     virtual void documentWasDisposed() { }
 };
 
-class DocumentLifecycleNotifier {
+class DocumentLifecycleNotifier  : public ContextLifecycleNotifier {
 public:
-    static PassOwnPtr<DocumentLifecycleNotifier> create();
+    static PassOwnPtr<DocumentLifecycleNotifier> create(ScriptExecutionContext*);
 
     void notifyDocumentWasDetached();
     void notifyDocumentWasDisposed();
 
-    void addObserver(DocumentLifecycleObserver*);
+    virtual void addObserver(ContextLifecycleObserver*, ContextLifecycleObserver::Type as) OVERRIDE;
+    virtual void removeObserver(ContextLifecycleObserver*, ContextLifecycleObserver::Type as) OVERRIDE;
 
 private:
-#if ASSERT_DISABLED
-    DocumentLifecycleNotifier() { }
-    void startIteration() { }
-    void endIteration() { }
-#else
-    DocumentLifecycleNotifier() : m_iterating(false) { }
-    void startIteration() { m_iterating = true; }
-    void endIteration() { m_iterating = false; }
-    bool m_iterating;
-#endif
+    explicit DocumentLifecycleNotifier(ScriptExecutionContext*);
 
-    Vector<DocumentLifecycleObserver*> m_observers; // Use Vector instead of HashSet for faster iteration
+    typedef HashSet<DocumentLifecycleObserver*> DocumentObserverSet;
+    DocumentObserverSet m_documentObservers;
 };
 
+inline PassOwnPtr<DocumentLifecycleNotifier> DocumentLifecycleNotifier::create(ScriptExecutionContext* context)
+{
+    return adoptPtr(new DocumentLifecycleNotifier(context));
+}
+
 inline void DocumentLifecycleNotifier::notifyDocumentWasDetached()
 {
-    startIteration();
-    for (size_t i = 0; i < m_observers.size(); ++i)
-        m_observers[i]->documentWasDetached();
-    endIteration();
+    TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverDocumentObservers);
+    for (DocumentObserverSet::iterator i = m_documentObservers.begin(); i != m_documentObservers.end(); ++i)
+        (*i)->documentWasDetached();
 }
 
 inline void DocumentLifecycleNotifier::notifyDocumentWasDisposed()
 {
-    startIteration();
-    for (size_t i = 0; i < m_observers.size(); ++i)
-        m_observers[i]->documentWasDisposed();
-    endIteration();
+    TemporaryChange<IterationType> scope(this->m_iterating, IteratingOverDocumentObservers);
+    for (DocumentObserverSet::iterator i = m_documentObservers.begin(); i != m_documentObservers.end(); ++i)
+        (*i)->documentWasDisposed();
 }
 
 } // namespace WebCore
diff --git a/Source/core/dom/DocumentOrderedList.cpp b/Source/core/dom/DocumentOrderedList.cpp
new file mode 100644
index 0000000..62802cc
--- /dev/null
+++ b/Source/core/dom/DocumentOrderedList.cpp
@@ -0,0 +1,73 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ *           (C) 1999 Antti Koivisto (koivisto@kde.org)
+ *           (C) 2001 Dirk Mueller (mueller@kde.org)
+ *           (C) 2006 Alexey Proskuryakov (ap@webkit.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2011, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2008, 2009, 2011, 2012 Google Inc. All rights reserved.
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ */
+
+#include "config.h"
+#include "core/dom/DocumentOrderedList.h"
+
+#include "core/dom/Node.h"
+
+namespace WebCore {
+
+void DocumentOrderedList::add(Node* node)
+{
+    if (m_nodes.isEmpty()) {
+        m_nodes.add(node);
+        return;
+    }
+
+    // Determine an appropriate insertion point.
+    iterator begin = m_nodes.begin();
+    iterator end = m_nodes.end();
+    iterator it = end;
+    Node* followingNode = 0;
+    do {
+        --it;
+        Node* n = *it;
+        unsigned short position = n->compareDocumentPositionInternal(node, Node::TreatShadowTreesAsComposed);
+        if (position & Node::DOCUMENT_POSITION_FOLLOWING) {
+            m_nodes.insertBefore(followingNode, node);
+            return;
+        }
+        followingNode = n;
+    } while (it != begin);
+
+    m_nodes.insertBefore(followingNode, node);
+}
+
+void DocumentOrderedList::parserAdd(Node* node)
+{
+    ASSERT(m_nodes.isEmpty() || m_nodes.last()->compareDocumentPositionInternal(node, Node::TreatShadowTreesAsComposed) & Node::DOCUMENT_POSITION_FOLLOWING);
+    m_nodes.add(node);
+}
+
+void DocumentOrderedList::remove(Node* node)
+{
+    m_nodes.remove(node);
+}
+
+}
+
diff --git a/Source/core/dom/DocumentOrderedList.h b/Source/core/dom/DocumentOrderedList.h
new file mode 100644
index 0000000..8dde172
--- /dev/null
+++ b/Source/core/dom/DocumentOrderedList.h
@@ -0,0 +1,60 @@
+/*
+ * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
+ *           (C) 1999 Antti Koivisto (koivisto@kde.org)
+ *           (C) 2001 Dirk Mueller (mueller@kde.org)
+ *           (C) 2006 Alexey Proskuryakov (ap@webkit.org)
+ * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2012 Apple Inc. All rights reserved.
+ * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved. (http://www.torchmobile.com/)
+ * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Library General Public
+ * License as published by the Free Software Foundation; either
+ * version 2 of the License, or (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Library General Public License for more details.
+ *
+ * You should have received a copy of the GNU Library General Public License
+ * along with this library; see the file COPYING.LIB.  If not, write to
+ * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
+ * Boston, MA 02110-1301, USA.
+ *
+ */
+
+#ifndef DocumentOrderedList_h
+#define DocumentOrderedList_h
+
+#include "wtf/FastAllocBase.h"
+#include "wtf/ListHashSet.h"
+
+namespace WebCore {
+
+class Node;
+
+class DocumentOrderedList {
+    WTF_MAKE_NONCOPYABLE(DocumentOrderedList); WTF_MAKE_FAST_ALLOCATED;
+public:
+    DocumentOrderedList() { }
+
+    void add(Node*);
+    void parserAdd(Node*);
+    void remove(Node*);
+    bool isEmpty() const { return m_nodes.isEmpty(); }
+    void clear() { m_nodes.clear(); }
+
+    typedef ListHashSet<Node*, 32>::iterator iterator;
+
+    iterator begin() { return m_nodes.begin(); }
+    iterator end() { return m_nodes.end(); }
+
+private:
+    ListHashSet<Node*, 32> m_nodes;
+};
+
+}
+
+#endif
diff --git a/Source/core/dom/DocumentParser.h b/Source/core/dom/DocumentParser.h
index f65d369..98a473b 100644
--- a/Source/core/dom/DocumentParser.h
+++ b/Source/core/dom/DocumentParser.h
@@ -47,8 +47,9 @@
     virtual void insert(const SegmentedString&) = 0;
 
     // appendBytes and flush are used by DocumentWriter (the loader).
-    virtual void appendBytes(DocumentWriter*, const char* bytes, size_t length) = 0;
-    virtual void flush(DocumentWriter*) = 0;
+    virtual size_t appendBytes(const char* bytes, size_t length) = 0;
+    virtual size_t flush() = 0;
+    virtual bool needsDecoder() const { return false; }
 
     virtual void pinToMainThread() { }
 
diff --git a/Source/core/dom/DocumentStyleSheetCollection.cpp b/Source/core/dom/DocumentStyleSheetCollection.cpp
index ab2b188..35b41b4 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.cpp
+++ b/Source/core/dom/DocumentStyleSheetCollection.cpp
@@ -226,33 +226,17 @@
 {
     if (!node->inDocument())
         return;
-    
+
     // Until the <body> exists, we have no choice but to compare document positions,
     // since styles outside of the body and head continue to be shunted into the head
     // (and thus can shift to end up before dynamically added DOM content that is also
     // outside the body).
-    if ((createdByParser && m_document->body()) || m_styleSheetCandidateNodes.isEmpty()) {
-        m_styleSheetCandidateNodes.add(node);
+    if (createdByParser && m_document->body()) {
+        m_styleSheetCandidateNodes.parserAdd(node);
         return;
     }
 
-    // Determine an appropriate insertion point.
-    StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
-    StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
-    StyleSheetCandidateListHashSet::iterator it = end;
-    Node* followingNode = 0;
-    do {
-        --it;
-        Node* n = *it;
-        unsigned short position = n->compareDocumentPositionInternal(node, Node::TreatShadowTreesAsComposed);
-        if (position & Node::DOCUMENT_POSITION_FOLLOWING) {
-            m_styleSheetCandidateNodes.insertBefore(followingNode, node);
-            return;
-        }
-        followingNode = n;
-    } while (it != begin);
-    
-    m_styleSheetCandidateNodes.insertBefore(followingNode, node);
+    m_styleSheetCandidateNodes.add(node);
 }
 
 void DocumentStyleSheetCollection::removeStyleSheetCandidateNode(Node* node)
@@ -260,21 +244,21 @@
     m_styleSheetCandidateNodes.remove(node);
 }
 
-void DocumentStyleSheetCollection::collectActiveStyleSheets(Vector<RefPtr<StyleSheet> >& sheets)
+void DocumentStyleSheetCollection::collectStyleSheets(Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets)
 {
     if (m_document->settings() && !m_document->settings()->authorAndUserStylesEnabled())
         return;
 
-    StyleSheetCandidateListHashSet::iterator begin = m_styleSheetCandidateNodes.begin();
-    StyleSheetCandidateListHashSet::iterator end = m_styleSheetCandidateNodes.end();
-    for (StyleSheetCandidateListHashSet::iterator it = begin; it != end; ++it) {
+    DocumentOrderedList::iterator begin = m_styleSheetCandidateNodes.begin();
+    DocumentOrderedList::iterator end = m_styleSheetCandidateNodes.end();
+    for (DocumentOrderedList::iterator it = begin; it != end; ++it) {
         Node* n = *it;
         StyleSheet* sheet = 0;
+        CSSStyleSheet* activeSheet = 0;
         if (n->nodeType() == Node::PROCESSING_INSTRUCTION_NODE) {
             // Processing instruction (XML documents only).
             // We don't support linking to embedded CSS stylesheets, see <https://bugs.webkit.org/show_bug.cgi?id=49281> for discussion.
             ProcessingInstruction* pi = static_cast<ProcessingInstruction*>(n);
-            sheet = pi->sheet();
             // Don't apply XSL transforms to already transformed documents -- <rdar://problem/4132806>
             if (pi->isXSL() && !m_document->transformSourceDocument()) {
                 // Don't apply XSL transforms until loading is finished.
@@ -282,6 +266,9 @@
                     m_document->applyXSLTransform(pi);
                 return;
             }
+            sheet = pi->sheet();
+            if (sheet && !sheet->disabled() && sheet->isCSSStyleSheet())
+                activeSheet = static_cast<CSSStyleSheet*>(sheet);
         } else if ((n->isHTMLElement() && (n->hasTagName(linkTag) || n->hasTagName(styleTag))) || (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))) {
             Element* e = toElement(n);
             AtomicString title = e->getAttribute(titleAttr);
@@ -289,10 +276,8 @@
             if (e->hasLocalName(linkTag)) {
                 // <LINK> element
                 HTMLLinkElement* linkElement = static_cast<HTMLLinkElement*>(n);
-                if (linkElement->isDisabled())
-                    continue;
                 enabledViaScript = linkElement->isEnabledViaScript();
-                if (linkElement->styleSheetIsLoading()) {
+                if (!linkElement->isDisabled() && linkElement->styleSheetIsLoading()) {
                     // it is loading but we should still decide which style sheet set to use
                     if (!enabledViaScript && !title.isEmpty() && m_preferredStylesheetSetName.isEmpty()) {
                         const AtomicString& rel = e->getAttribute(relAttr);
@@ -301,25 +286,26 @@
                             m_selectedStylesheetSetName = title;
                         }
                     }
+
                     continue;
                 }
-                if (!linkElement->sheet())
+                sheet = linkElement->sheet();
+                if (!sheet)
                     title = nullAtom;
-            }
-            // Get the current preferred styleset. This is the
-            // set of sheets that will be enabled.
-            if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag))
+            } else if (n->isSVGElement() && n->hasTagName(SVGNames::styleTag)) {
                 sheet = static_cast<SVGStyleElement*>(n)->sheet();
-            else if (e->hasLocalName(linkTag))
-                sheet = static_cast<HTMLLinkElement*>(n)->sheet();
-            else
-                // <STYLE> element
+            } else {
                 sheet = static_cast<HTMLStyleElement*>(n)->sheet();
+            }
+
+            if (sheet && !sheet->disabled() && sheet->isCSSStyleSheet())
+                activeSheet = static_cast<CSSStyleSheet*>(sheet);
+
             // Check to see if this sheet belongs to a styleset
             // (thus making it PREFERRED or ALTERNATE rather than
             // PERSISTENT).
             AtomicString rel = e->getAttribute(relAttr);
-            if (!enabledViaScript && !title.isEmpty()) {
+            if (!enabledViaScript && sheet && !title.isEmpty()) {
                 // Yes, we have a title.
                 if (m_preferredStylesheetSetName.isEmpty()) {
                     // No preferred set has been established. If
@@ -330,22 +316,24 @@
                         m_preferredStylesheetSetName = m_selectedStylesheetSetName = title;
                 }
                 if (title != m_preferredStylesheetSetName)
-                    sheet = 0;
+                    activeSheet = 0;
             }
 
             if (rel.contains("alternate") && title.isEmpty())
-                sheet = 0;
+                activeSheet = 0;
         }
         if (sheet)
-            sheets.append(sheet);
+            styleSheets.append(sheet);
+        if (activeSheet)
+            activeSheets.append(activeSheet);
     }
 }
 
-void DocumentStyleSheetCollection::analyzeStyleSheetChange(UpdateFlag updateFlag, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, StyleResolverUpdateType& styleResolverUpdateType, bool& requiresFullStyleRecalc)
+void DocumentStyleSheetCollection::analyzeStyleSheetChange(StyleResolverUpdateMode updateMode, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, StyleResolverUpdateType& styleResolverUpdateType, bool& requiresFullStyleRecalc)
 {
     styleResolverUpdateType = Reconstruct;
     requiresFullStyleRecalc = true;
-    
+
     // Stylesheets of <style> elements that @import stylesheets are active but loading. We need to trigger a full recalc when such loads are done.
     bool hasActiveLoadingStylesheet = false;
     unsigned newStylesheetCount = newStylesheets.size();
@@ -359,7 +347,7 @@
     }
     m_hadActiveLoadingStylesheet = hasActiveLoadingStylesheet;
 
-    if (updateFlag != OptimizedUpdate)
+    if (updateMode != AnalyzedStyleUpdate)
         return;
     if (!m_document->styleResolverIfExists())
         return;
@@ -409,17 +397,6 @@
     return false;
 }
 
-static void filterEnabledCSSStyleSheets(Vector<RefPtr<CSSStyleSheet> >& result, const Vector<RefPtr<StyleSheet> >& sheets)
-{
-    for (unsigned i = 0; i < sheets.size(); ++i) {
-        if (!sheets[i]->isCSSStyleSheet())
-            continue;
-        if (sheets[i]->disabled())
-            continue;
-        result.append(static_cast<CSSStyleSheet*>(sheets[i].get()));
-    }
-}
-
 static void collectActiveCSSStyleSheetsFromSeamlessParents(Vector<RefPtr<CSSStyleSheet> >& sheets, Document* document)
 {
     HTMLIFrameElement* seamlessParentIFrame = document->seamlessParentIFrame();
@@ -428,7 +405,7 @@
     sheets.append(seamlessParentIFrame->document()->styleSheetCollection()->activeAuthorStyleSheets());
 }
 
-bool DocumentStyleSheetCollection::updateActiveStyleSheets(UpdateFlag updateFlag)
+bool DocumentStyleSheetCollection::updateActiveStyleSheets(StyleResolverUpdateMode updateMode)
 {
     if (m_document->inStyleRecalc()) {
         // SVG <use> element may manage to invalidate style selector in the middle of a style recalc.
@@ -442,18 +419,16 @@
     if (!m_document->renderer() || !m_document->attached())
         return false;
 
-    Vector<RefPtr<StyleSheet> > activeStyleSheets;
-    collectActiveStyleSheets(activeStyleSheets);
-
+    Vector<RefPtr<StyleSheet> > styleSheets;
     Vector<RefPtr<CSSStyleSheet> > activeCSSStyleSheets;
     activeCSSStyleSheets.append(injectedAuthorStyleSheets());
     activeCSSStyleSheets.append(documentAuthorStyleSheets());
     collectActiveCSSStyleSheetsFromSeamlessParents(activeCSSStyleSheets, m_document);
-    filterEnabledCSSStyleSheets(activeCSSStyleSheets, activeStyleSheets);
+    collectStyleSheets(styleSheets, activeCSSStyleSheets);
 
     StyleResolverUpdateType styleResolverUpdateType;
     bool requiresFullStyleRecalc;
-    analyzeStyleSheetChange(updateFlag, activeCSSStyleSheets, styleResolverUpdateType, requiresFullStyleRecalc);
+    analyzeStyleSheetChange(updateMode, activeCSSStyleSheets, styleResolverUpdateType, requiresFullStyleRecalc);
 
     if (styleResolverUpdateType == Reconstruct)
         m_document->clearStyleResolver();
@@ -469,8 +444,8 @@
         resetCSSFeatureFlags();
     }
     m_activeAuthorStyleSheets.swap(activeCSSStyleSheets);
-    InspectorInstrumentation::activeStyleSheetsUpdated(m_document, activeStyleSheets);
-    m_styleSheetsForStyleSheetList.swap(activeStyleSheets);
+    InspectorInstrumentation::activeStyleSheetsUpdated(m_document, styleSheets);
+    m_styleSheetsForStyleSheetList.swap(styleSheets);
 
     m_usesRemUnits = styleSheetsUseRemUnits(m_activeAuthorStyleSheets);
     m_needsUpdateActiveStylesheetsOnStyleRecalc = false;
diff --git a/Source/core/dom/DocumentStyleSheetCollection.h b/Source/core/dom/DocumentStyleSheetCollection.h
index 51997fa..1a67e28 100644
--- a/Source/core/dom/DocumentStyleSheetCollection.h
+++ b/Source/core/dom/DocumentStyleSheetCollection.h
@@ -28,16 +28,17 @@
 #ifndef DocumentStyleSheetCollection_h
 #define DocumentStyleSheetCollection_h
 
-#include <wtf/FastAllocBase.h>
-#include <wtf/ListHashSet.h>
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
-#include <wtf/text/WTFString.h>
+#include "core/dom/Document.h"
+#include "core/dom/DocumentOrderedList.h"
+#include "wtf/FastAllocBase.h"
+#include "wtf/ListHashSet.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
 class CSSStyleSheet;
-class Document;
 class Node;
 class StyleSheet;
 class StyleSheetContents;
@@ -73,8 +74,7 @@
 
     bool needsUpdateActiveStylesheetsOnStyleRecalc() const { return m_needsUpdateActiveStylesheetsOnStyleRecalc; }
 
-    enum UpdateFlag { FullUpdate, OptimizedUpdate };
-    bool updateActiveStyleSheets(UpdateFlag);
+    bool updateActiveStyleSheets(StyleResolverUpdateMode);
 
     String preferredStylesheetSetName() const { return m_preferredStylesheetSetName; }
     String selectedStylesheetSetName() const { return m_selectedStylesheetSetName; }
@@ -108,13 +108,13 @@
 private:
     DocumentStyleSheetCollection(Document*);
 
-    void collectActiveStyleSheets(Vector<RefPtr<StyleSheet> >&);
+    void collectStyleSheets(Vector<RefPtr<StyleSheet> >& styleSheets, Vector<RefPtr<CSSStyleSheet> >& activeSheets);
     enum StyleResolverUpdateType {
         Reconstruct,
         Reset,
         Additive
     };
-    void analyzeStyleSheetChange(UpdateFlag, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, StyleResolverUpdateType&, bool& requiresFullStyleRecalc);
+    void analyzeStyleSheetChange(StyleResolverUpdateMode, const Vector<RefPtr<CSSStyleSheet> >& newStylesheets, StyleResolverUpdateType&, bool& requiresFullStyleRecalc);
 
     Document* m_document;
 
@@ -139,8 +139,7 @@
     bool m_hadActiveLoadingStylesheet;
     bool m_needsUpdateActiveStylesheetsOnStyleRecalc;
 
-    typedef ListHashSet<Node*, 32> StyleSheetCandidateListHashSet;
-    StyleSheetCandidateListHashSet m_styleSheetCandidateNodes;
+    DocumentOrderedList m_styleSheetCandidateNodes;
 
     String m_preferredStylesheetSetName;
     String m_selectedStylesheetSetName;
diff --git a/Source/core/dom/DocumentType.idl b/Source/core/dom/DocumentType.idl
index 352da12..8f192f3 100644
--- a/Source/core/dom/DocumentType.idl
+++ b/Source/core/dom/DocumentType.idl
@@ -29,11 +29,7 @@
 
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString publicId;
     [TreatReturnedNullStringAs=Null] readonly attribute DOMString systemId;
-    [TreatReturnedNullStringAs=Null] readonly attribute DOMString internalSubset;        
-
-    // ChildNode interface API
-    readonly attribute Element previousElementSibling;
-    readonly attribute Element nextElementSibling;
-    [RaisesException] void remove();
+    [TreatReturnedNullStringAs=Null] readonly attribute DOMString internalSubset;
 };
 
+DocumentType implements ChildNode;
diff --git a/Source/core/dom/Element.cpp b/Source/core/dom/Element.cpp
index bf2c5fc..ab2f94d 100644
--- a/Source/core/dom/Element.cpp
+++ b/Source/core/dom/Element.cpp
@@ -26,13 +26,20 @@
 #include "config.h"
 #include "core/dom/Element.h"
 
+#include "CSSPropertyNames.h"
+#include "CSSValueKeywords.h"
 #include "HTMLNames.h"
 #include "SVGNames.h"
 #include "XMLNames.h"
 #include "core/accessibility/AXObjectCache.h"
+#include "core/css/CSSParser.h"
+#include "core/css/CSSStyleSheet.h"
+#include "core/css/CSSValuePool.h"
+#include "core/css/PropertySetCSSStyleDeclaration.h"
 #include "core/css/StylePropertySet.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Attr.h"
+#include "core/dom/Attribute.h"
 #include "core/dom/ClientRect.h"
 #include "core/dom/ClientRectList.h"
 #include "core/dom/CustomElementRegistry.h"
@@ -48,6 +55,7 @@
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/NodeRenderingContext.h"
 #include "core/dom/PseudoElement.h"
+#include "core/dom/ScriptableDocumentParser.h"
 #include "core/dom/SelectorQuery.h"
 #include "core/dom/Text.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
@@ -66,6 +74,7 @@
 #include "core/html/HTMLOptionsCollection.h"
 #include "core/html/HTMLTableRowsCollection.h"
 #include "core/html/parser/HTMLParserIdioms.h"
+#include "core/page/ContentSecurityPolicy.h"
 #include "core/page/FocusController.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
@@ -78,8 +87,10 @@
 #include "core/svg/SVGDocumentExtensions.h"
 #include "core/svg/SVGElement.h"
 #include "wtf/BitVector.h"
+#include "wtf/HashFunctions.h"
 #include "wtf/MemoryInstrumentationVector.h"
 #include "wtf/text/CString.h"
+#include "wtf/text/TextPosition.h"
 
 namespace WebCore {
 
@@ -90,7 +101,7 @@
 {
     return e && e->document()->isHTMLDocument() && e->isHTMLElement();
 }
-    
+
 class StyleResolverParentPusher {
 public:
     StyleResolverParentPusher(Element* parent)
@@ -187,6 +198,9 @@
     }
 #endif
 
+    if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
+        cssomWrapper->clearParentElement();
+
     if (hasRareData()) {
         ElementRareData* data = elementRareData();
         data->setPseudoElement(BEFORE, 0);
@@ -406,7 +420,7 @@
         return;
     if (elementData()->m_styleAttributeIsDirty) {
         ASSERT(isStyledElement());
-        static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
+        synchronizeStyleAttributeInternal();
     }
     if (elementData()->m_animatedSVGAttributesAreDirty) {
         ASSERT(isSVGElement());
@@ -420,7 +434,7 @@
         return;
     if (UNLIKELY(name == styleAttr && elementData()->m_styleAttributeIsDirty)) {
         ASSERT(isStyledElement());
-        static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
+        synchronizeStyleAttributeInternal();
         return;
     }
     if (UNLIKELY(elementData()->m_animatedSVGAttributesAreDirty)) {
@@ -437,7 +451,7 @@
         return;
     if (elementData()->m_styleAttributeIsDirty && equalPossiblyIgnoringCase(localName, styleAttr.localName(), shouldIgnoreAttributeCase(this))) {
         ASSERT(isStyledElement());
-        static_cast<const StyledElement*>(this)->synchronizeStyleAttributeInternal();
+        synchronizeStyleAttributeInternal();
         return;
     }
     if (elementData()->m_animatedSVGAttributesAreDirty) {
@@ -457,7 +471,7 @@
     return nullAtom;
 }
 
-void Element::scrollIntoView(bool alignToTop) 
+void Element::scrollIntoView(bool alignToTop)
 {
     document()->updateLayoutIgnorePendingStylesheets();
 
@@ -564,6 +578,13 @@
 
 int Element::offsetWidth()
 {
+    document()->updateStyleForNodeIfNeeded(this);
+
+    if (RenderBox* renderer = renderBox()) {
+        if (!renderer->requiresLayoutToDetermineWidth())
+            return adjustLayoutUnitForAbsoluteZoom(renderer->fixedOffsetWidth(), renderer).round();
+    }
+
     document()->updateLayoutIgnorePendingStylesheets();
     if (RenderBoxModelObject* renderer = renderBoxModelObject())
         return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedOffsetWidth(), renderer).round();
@@ -626,7 +647,7 @@
                 return adjustForAbsoluteZoom(view->layoutWidth(), renderView);
         }
     }
-    
+
     if (RenderBox* renderer = renderBox())
         return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientWidth(), renderer).round();
     return 0;
@@ -638,7 +659,7 @@
 
     // When in strict mode, clientHeight for the document element should return the height of the containing frame.
     // When in quirks mode, clientHeight for the body element should return the height of the containing frame.
-    bool inQuirksMode = document()->inQuirksMode();     
+    bool inQuirksMode = document()->inQuirksMode();
 
     if ((!inQuirksMode && document()->documentElement() == this) ||
         (inQuirksMode && isHTMLElement() && document()->body() == this)) {
@@ -647,7 +668,7 @@
                 return adjustForAbsoluteZoom(view->layoutHeight(), renderView);
         }
     }
-    
+
     if (RenderBox* renderer = renderBox())
         return adjustLayoutUnitForAbsoluteZoom(renderer->pixelSnappedClientHeight(), renderer).round();
     return 0;
@@ -775,7 +796,7 @@
     document()->adjustFloatRectForScrollAndAbsoluteZoom(result, renderer());
     return ClientRect::create(result);
 }
-    
+
 IntRect Element::screenRect() const
 {
     if (!renderer())
@@ -874,7 +895,7 @@
     return false;
 }
 
-void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason)
+void Element::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
 {
     if (ElementShadow* parentElementShadow = shadowOfParentForDistribution(this)) {
         if (shouldInvalidateDistributionWhenAttributeChanged(parentElementShadow, name, newValue))
@@ -889,6 +910,13 @@
     bool testShouldInvalidateStyle = attached() && styleResolver && styleChangeType() < FullStyleChange;
     bool shouldInvalidateStyle = false;
 
+    if (isStyledElement() && name == styleAttr) {
+        styleAttributeChanged(newValue, reason);
+    } else if (isStyledElement() && isPresentationAttribute(name)) {
+        elementData()->m_presentationAttributeStyleIsDirty = true;
+        setNeedsStyleRecalc(InlineStyleChange);
+    }
+
     if (isIdAttributeName(name)) {
         AtomicString oldId = elementData()->idForStyleResolution();
         AtomicString newId = makeIdForStyleResolution(newValue, document()->inQuirksMode());
@@ -896,12 +924,13 @@
             elementData()->setIdForStyleResolution(newId);
             shouldInvalidateStyle = testShouldInvalidateStyle && checkNeedsStyleInvalidationForIdChange(oldId, newId, styleResolver);
         }
-    } else if (name == classAttr)
+    } else if (name == classAttr) {
         classAttributeChanged(newValue);
-    else if (name == HTMLNames::nameAttr)
+    } else if (name == HTMLNames::nameAttr) {
         setHasName(!newValue.isNull());
-    else if (name == HTMLNames::pseudoAttr)
+    } else if (name == HTMLNames::pseudoAttr) {
         shouldInvalidateStyle |= testShouldInvalidateStyle && isInShadowTree();
+    }
 
     invalidateNodeListCachesInAncestors(&name, this);
 
@@ -1168,7 +1197,7 @@
     return context.style()->display() != NONE;
 }
 
-RenderObject* Element::createRenderer(RenderArena*, RenderStyle* style)
+RenderObject* Element::createRenderer(RenderStyle* style)
 {
     return RenderObject::createObject(this, style);
 }
@@ -1207,7 +1236,9 @@
 bool Element::isInert() const
 {
     const Element* dialog = document()->activeModalDialog();
-    return dialog && !containsIncludingShadowDOM(dialog) && !dialog->containsIncludingShadowDOM(this);
+    if (dialog && !containsIncludingShadowDOM(dialog) && !dialog->containsIncludingShadowDOM(this))
+        return true;
+    return document()->ownerElement() && document()->ownerElement()->isInert();
 }
 
 Node::InsertionNotificationRequest Element::insertedInto(ContainerNode* insertionPoint)
@@ -1312,7 +1343,7 @@
     // When a shadow root exists, it does the work of attaching the children.
     if (ElementShadow* shadow = this->shadow()) {
         parentPusher.push();
-        shadow->attach();
+        shadow->attach(context);
     } else if (firstChild())
         parentPusher.push();
 
@@ -1320,7 +1351,7 @@
 
     createPseudoElementIfNeeded(AFTER);
 
-    if (hasRareData()) {   
+    if (hasRareData()) {
         ElementRareData* data = elementRareData();
         if (data->needsFocusAppearanceUpdateSoonAfterAttach()) {
             if (isFocusable() && document()->focusedNode() == this)
@@ -1328,6 +1359,12 @@
             data->setNeedsFocusAppearanceUpdateSoonAfterAttach(false);
         }
     }
+
+    // FIXME: It doesn't appear safe to call didRecalculateStyleForElement when
+    // not in a Document::recalcStyle. Since we're hopefully going to always
+    // lazyAttach in the future that problem should go away.
+    if (document()->inStyleRecalc())
+        InspectorInstrumentation::didRecalculateStyleForElement(this);
 }
 
 void Element::unregisterNamedFlowContentNode()
@@ -1348,12 +1385,10 @@
         data->setIsInCanvasSubtree(false);
         data->resetComputedStyle();
         data->resetDynamicRestyleObservations();
+        data->setIsInsideRegion(false);
     }
-
-    if (ElementShadow* shadow = this->shadow()) {
-        detachChildrenIfNeeded();
-        shadow->detach();
-    }
+    if (ElementShadow* shadow = this->shadow())
+        shadow->detach(context);
     ContainerNode::detach(context);
 }
 
@@ -1455,8 +1490,10 @@
             return;
         }
 
+        InspectorInstrumentation::didRecalculateStyleForElement(this);
+
         if (RenderObject* renderer = this->renderer()) {
-            if (localChange != NoChange || pseudoStyleCacheIsInvalid(currentStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || styleChangeType() == SyntheticStyleChange)
+            if (localChange != NoChange || pseudoStyleCacheIsInvalid(currentStyle.get(), newStyle.get()) || (change == Force && renderer->requiresForcedStyleRecalcPropagation()) || needsLayerUpdate())
                 renderer->setAnimatableStyle(newStyle.get());
             else if (needsStyleRecalc()) {
                 // Although no change occurred, we use the new style so that the cousin style sharing code won't get
@@ -1500,8 +1537,8 @@
         if (n->isTextNode()) {
             toText(n)->recalcTextStyle(change);
             continue;
-        } 
-        if (!n->isElementNode()) 
+        }
+        if (!n->isElementNode())
             continue;
         Element* element = toElement(n);
         bool childRulesChanged = element->needsStyleRecalc() && element->styleChangeType() == FullStyleChange;
@@ -1520,10 +1557,9 @@
 
     clearNeedsStyleRecalc();
     clearChildNeedsStyleRecalc();
-    
+
     if (hasCustomStyleCallbacks())
         didRecalcStyle(change);
-    InspectorInstrumentation::didRecalculateStyleForElement(this);
 }
 
 ElementShadow* Element::shadow() const
@@ -1627,7 +1663,7 @@
 {
     // :empty selector.
     checkForEmptyStyleChange(e, style);
-    
+
     if (!style || (e->needsStyleRecalc() && e->childrenAffectedByPositionalRules()))
         return;
 
@@ -1638,18 +1674,18 @@
         // Find our new first child.
         Node* newFirstChild = 0;
         for (newFirstChild = e->firstChild(); newFirstChild && !newFirstChild->isElementNode(); newFirstChild = newFirstChild->nextSibling()) {};
-        
+
         // Find the first element node following |afterChange|
         Node* firstElementAfterInsertion = 0;
         for (firstElementAfterInsertion = afterChange;
              firstElementAfterInsertion && !firstElementAfterInsertion->isElementNode();
              firstElementAfterInsertion = firstElementAfterInsertion->nextSibling()) {};
-        
+
         // This is the insert/append case.
         if (newFirstChild != firstElementAfterInsertion && firstElementAfterInsertion && firstElementAfterInsertion->attached() &&
             firstElementAfterInsertion->renderStyle() && firstElementAfterInsertion->renderStyle()->firstChildState())
             firstElementAfterInsertion->setNeedsStyleRecalc();
-            
+
         // We also have to handle node removal.
         if (childCountDelta < 0 && newFirstChild == firstElementAfterInsertion && newFirstChild && (!newFirstChild->renderStyle() || !newFirstChild->renderStyle()->firstChildState()))
             newFirstChild->setNeedsStyleRecalc();
@@ -1661,17 +1697,17 @@
         // Find our new last child.
         Node* newLastChild = 0;
         for (newLastChild = e->lastChild(); newLastChild && !newLastChild->isElementNode(); newLastChild = newLastChild->previousSibling()) {};
-        
+
         // Find the last element node going backwards from |beforeChange|
         Node* lastElementBeforeInsertion = 0;
         for (lastElementBeforeInsertion = beforeChange;
              lastElementBeforeInsertion && !lastElementBeforeInsertion->isElementNode();
              lastElementBeforeInsertion = lastElementBeforeInsertion->previousSibling()) {};
-        
+
         if (newLastChild != lastElementBeforeInsertion && lastElementBeforeInsertion && lastElementBeforeInsertion->attached() &&
             lastElementBeforeInsertion->renderStyle() && lastElementBeforeInsertion->renderStyle()->lastChildState())
             lastElementBeforeInsertion->setNeedsStyleRecalc();
-            
+
         // We also have to handle node removal.  The parser callback case is similar to node removal as well in that we need to change the last child
         // to match now.
         if ((childCountDelta < 0 || finishedParsingCallback) && newLastChild == lastElementBeforeInsertion && newLastChild && (!newLastChild->renderStyle() || !newLastChild->renderStyle()->lastChildState()))
@@ -1803,6 +1839,7 @@
     setAttributeInternal(index, attrNode->qualifiedName(), attrNode->value(), NotInSynchronizationOfLazyAttribute);
 
     attrNode->attachToElement(this);
+    treeScope()->adoptIfNeeded(attrNode);
     ensureAttrNodeListForElement(this)->append(attrNode);
 
     return oldAttrNode.release();
@@ -1906,7 +1943,7 @@
     size_t index = elementData()->getAttributeItemIndex(localName, false);
     if (index == notFound) {
         if (UNLIKELY(localName == styleAttr) && elementData()->m_styleAttributeIsDirty && isStyledElement())
-            static_cast<StyledElement*>(this)->removeAllInlineStyleProperties();
+            removeAllInlineStyleProperties();
         return;
     }
 
@@ -1958,11 +1995,6 @@
     return elementData()->getAttributeItem(qName);
 }
 
-CSSStyleDeclaration *Element::style()
-{
-    return 0;
-}
-
 void Element::focus(bool restorePreviousSelection, FocusDirection direction)
 {
     if (!inDocument())
@@ -1974,7 +2006,7 @@
 
     // If the stylesheets have already been loaded we can reliably check isFocusable.
     // If not, we continue and set the focused node on the focus controller below so
-    // that it can be updated soon after attach. 
+    // that it can be updated soon after attach.
     if (doc->haveStylesheetsLoaded()) {
         doc->updateLayoutIgnorePendingStylesheets();
         if (!isFocusable())
@@ -2001,7 +2033,7 @@
         ensureElementRareData()->setNeedsFocusAppearanceUpdateSoonAfterAttach(true);
         return;
     }
-        
+
     cancelFocusAppearanceUpdate();
     updateFocusAppearance(restorePreviousSelection);
 }
@@ -2012,14 +2044,14 @@
         Frame* frame = document()->frame();
         if (!frame)
             return;
-        
+
         // When focusing an editable element in an iframe, don't reset the selection if it already contains a selection.
         if (this == frame->selection()->rootEditableElement())
             return;
 
         // FIXME: We should restore the previous selection if there is one.
         VisibleSelection newSelection = VisibleSelection(firstPositionInOrBeforeNode(this), DOWNSTREAM);
-        
+
         if (frame->selection()->shouldChangeSelection(newSelection)) {
             frame->selection()->setSelection(newSelection);
             frame->selection()->revealSelection();
@@ -2061,6 +2093,46 @@
     return innerText();
 }
 
+String Element::textFromChildren()
+{
+    Text* firstTextNode = 0;
+    bool foundMultipleTextNodes = false;
+    unsigned totalLength = 0;
+
+    for (Node* child = firstChild(); child; child = child->nextSibling()) {
+        if (!child->isTextNode())
+            continue;
+        Text* text = toText(child);
+        if (!firstTextNode)
+            firstTextNode = text;
+        else
+            foundMultipleTextNodes = true;
+        unsigned length = text->data().length();
+        if (length > std::numeric_limits<unsigned>::max() - totalLength)
+            return emptyString();
+        totalLength += length;
+    }
+
+    if (!firstTextNode)
+        return emptyString();
+
+    if (firstTextNode && !foundMultipleTextNodes) {
+        firstTextNode->atomize();
+        return firstTextNode->data();
+    }
+
+    StringBuilder content;
+    content.reserveCapacity(totalLength);
+    for (Node* child = firstTextNode; child; child = child->nextSibling()) {
+        if (!child->isTextNode())
+            continue;
+        content.append(toText(child)->data());
+    }
+
+    ASSERT(content.length() == totalLength);
+    return content.toString();
+}
+
 String Element::title() const
 {
     return String();
@@ -2260,6 +2332,29 @@
     return isCustomElement() && document()->registry()->isUnresolved(this);
 }
 
+void Element::setIsInsideRegion(bool value)
+{
+    if (value == isInsideRegion())
+        return;
+
+    ensureElementRareData()->setIsInsideRegion(value);
+}
+
+bool Element::isInsideRegion() const
+{
+    return hasRareData() ? elementRareData()->isInsideRegion() : false;
+}
+
+void Element::setRegionOversetState(RegionOversetState state)
+{
+    ensureElementRareData()->setRegionOversetState(state);
+}
+
+RegionOversetState Element::regionOversetState() const
+{
+    return hasRareData() ? elementRareData()->regionOversetState() : RegionUndefined;
+}
+
 AtomicString Element::computeInheritedLanguage() const
 {
     const Node* n = this;
@@ -2548,6 +2643,22 @@
     return 0;
 }
 
+bool Element::shouldMoveToFlowThread(RenderStyle* styleToUse) const
+{
+    ASSERT(styleToUse);
+
+    if (FullscreenController::isActiveFullScreenElement(this))
+        return false;
+
+    if (isInShadowTree())
+        return false;
+
+    if (styleToUse->flowThread().isEmpty())
+        return false;
+
+    return !isRegisteredWithNamedFlow();
+}
+
 const AtomicString& Element::webkitRegionOverset() const
 {
     document()->updateLayoutIgnorePendingStylesheets();
@@ -2556,20 +2667,20 @@
     if (!RuntimeEnabledFeatures::cssRegionsEnabled() || !renderRegion())
         return undefinedState;
 
-    switch (renderRegion()->regionState()) {
-    case RenderRegion::RegionFit: {
+    switch (renderRegion()->regionOversetState()) {
+    case RegionFit: {
         DEFINE_STATIC_LOCAL(AtomicString, fitState, ("fit", AtomicString::ConstructFromLiteral));
         return fitState;
     }
-    case RenderRegion::RegionEmpty: {
+    case RegionEmpty: {
         DEFINE_STATIC_LOCAL(AtomicString, emptyState, ("empty", AtomicString::ConstructFromLiteral));
         return emptyState;
     }
-    case RenderRegion::RegionOverset: {
+    case RegionOverset: {
         DEFINE_STATIC_LOCAL(AtomicString, overflowState, ("overset", AtomicString::ConstructFromLiteral));
         return overflowState;
     }
-    case RenderRegion::RegionUndefined:
+    case RegionUndefined:
         return undefinedState;
     }
 
@@ -2752,17 +2863,17 @@
     return ensureRareData()->ensureNodeLists()->addCacheWithAtomicName<HTMLCollection>(this, type);
 }
 
-static void needsSyntheticStyleChangeCallback(Node* node)
+static void scheduleLayerUpdateCallback(Node* node)
 {
-    node->setNeedsStyleRecalc(SyntheticStyleChange);
+    node->setNeedsLayerUpdate();
 }
 
-void Element::scheduleSyntheticStyleChange()
+void Element::scheduleLayerUpdate()
 {
     if (postAttachCallbacksAreSuspended())
-        queuePostAttachCallback(needsSyntheticStyleChangeCallback, this);
+        queuePostAttachCallback(scheduleLayerUpdateCallback, this);
     else
-        setNeedsStyleRecalc(SyntheticStyleChange);
+        setNeedsLayerUpdate();
 }
 
 HTMLCollection* Element::cachedHTMLCollection(CollectionType type)
@@ -2934,6 +3045,345 @@
     ensureElementRareData()->setHasPendingResources(false);
 }
 
+struct PresentationAttributeCacheKey {
+    PresentationAttributeCacheKey() : tagName(0) { }
+    AtomicStringImpl* tagName;
+    // Only the values need refcounting.
+    Vector<pair<AtomicStringImpl*, AtomicString>, 3> attributesAndValues;
+};
+
+struct PresentationAttributeCacheEntry {
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    PresentationAttributeCacheKey key;
+    RefPtr<StylePropertySet> value;
+};
+
+typedef HashMap<unsigned, OwnPtr<PresentationAttributeCacheEntry>, AlreadyHashed> PresentationAttributeCache;
+
+static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b)
+{
+    if (a.tagName != b.tagName)
+        return true;
+    return a.attributesAndValues != b.attributesAndValues;
+}
+
+static PresentationAttributeCache& presentationAttributeCache()
+{
+    DEFINE_STATIC_LOCAL(PresentationAttributeCache, cache, ());
+    return cache;
+}
+
+class PresentationAttributeCacheCleaner {
+    WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); WTF_MAKE_FAST_ALLOCATED;
+public:
+    PresentationAttributeCacheCleaner()
+        : m_hitCount(0)
+        , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
+    {
+    }
+
+    void didHitPresentationAttributeCache()
+    {
+        if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
+            return;
+
+        m_hitCount++;
+
+        if (!m_cleanTimer.isActive())
+            m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
+    }
+
+private:
+    static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
+    static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
+    static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
+
+    void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
+    {
+        ASSERT_UNUSED(timer, timer == &m_cleanTimer);
+        unsigned hitCount = m_hitCount;
+        m_hitCount = 0;
+        if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
+            return;
+        presentationAttributeCache().clear();
+    }
+
+    unsigned m_hitCount;
+    Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
+};
+
+static PresentationAttributeCacheCleaner& presentationAttributeCacheCleaner()
+{
+    DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cleaner, ());
+    return cleaner;
+}
+
+void Element::synchronizeStyleAttributeInternal() const
+{
+    ASSERT(isStyledElement());
+    ASSERT(elementData());
+    ASSERT(elementData()->m_styleAttributeIsDirty);
+    elementData()->m_styleAttributeIsDirty = false;
+    if (const StylePropertySet* inlineStyle = this->inlineStyle())
+        const_cast<Element*>(this)->setSynchronizedLazyAttribute(styleAttr, inlineStyle->asText());
+}
+
+CSSStyleDeclaration* Element::style()
+{
+    if (!isStyledElement())
+        return 0;
+    return ensureMutableInlineStyle()->ensureInlineCSSStyleDeclaration(this);
+}
+
+MutableStylePropertySet* Element::ensureMutableInlineStyle()
+{
+    ASSERT(isStyledElement());
+    RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
+    if (!inlineStyle)
+        inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document()->inQuirksMode()));
+    else if (!inlineStyle->isMutable())
+        inlineStyle = inlineStyle->mutableCopy();
+    ASSERT(inlineStyle->isMutable());
+    return static_cast<MutableStylePropertySet*>(inlineStyle.get());
+}
+
+PropertySetCSSStyleDeclaration* Element::inlineStyleCSSOMWrapper()
+{
+    if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
+        return 0;
+    PropertySetCSSStyleDeclaration* cssomWrapper = ensureMutableInlineStyle()->cssStyleDeclaration();
+    ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
+    return cssomWrapper;
+}
+
+inline void Element::setInlineStyleFromString(const AtomicString& newStyleString)
+{
+    ASSERT(isStyledElement());
+    RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
+
+    // Avoid redundant work if we're using shared attribute data with already parsed inline style.
+    if (inlineStyle && !elementData()->isUnique())
+        return;
+
+    // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
+    // This makes wrapperless property sets immutable and so cacheable.
+    if (inlineStyle && !inlineStyle->isMutable())
+        inlineStyle.clear();
+
+    if (!inlineStyle) {
+        inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
+    } else {
+        ASSERT(inlineStyle->isMutable());
+        static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document()->elementSheet()->contents());
+    }
+}
+
+void Element::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
+{
+    ASSERT(isStyledElement());
+    WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
+    if (document() && document()->scriptableDocumentParser() && !document()->isInDocumentWrite())
+        startLineNumber = document()->scriptableDocumentParser()->lineNumber();
+
+    if (newStyleString.isNull()) {
+        if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
+            cssomWrapper->clearParentElement();
+        ensureUniqueElementData()->m_inlineStyle.clear();
+    } else if (modificationReason == ModifiedByCloning || document()->contentSecurityPolicy()->allowInlineStyle(document()->url(), startLineNumber)) {
+        setInlineStyleFromString(newStyleString);
+    }
+
+    elementData()->m_styleAttributeIsDirty = false;
+
+    setNeedsStyleRecalc(InlineStyleChange);
+    InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
+}
+
+void Element::inlineStyleChanged()
+{
+    ASSERT(isStyledElement());
+    setNeedsStyleRecalc(InlineStyleChange);
+    ASSERT(elementData());
+    elementData()->m_styleAttributeIsDirty = true;
+    InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
+}
+
+bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
+{
+    ASSERT(isStyledElement());
+    ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
+    inlineStyleChanged();
+    return true;
+}
+
+bool Element::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
+{
+    ASSERT(isStyledElement());
+    ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
+    inlineStyleChanged();
+    return true;
+}
+
+bool Element::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
+{
+    ASSERT(isStyledElement());
+    ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
+    inlineStyleChanged();
+    return true;
+}
+
+bool Element::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
+{
+    ASSERT(isStyledElement());
+    bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document()->elementSheet()->contents());
+    if (changes)
+        inlineStyleChanged();
+    return changes;
+}
+
+bool Element::removeInlineStyleProperty(CSSPropertyID propertyID)
+{
+    ASSERT(isStyledElement());
+    if (!inlineStyle())
+        return false;
+    bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
+    if (changes)
+        inlineStyleChanged();
+    return changes;
+}
+
+void Element::removeAllInlineStyleProperties()
+{
+    ASSERT(isStyledElement());
+    if (!inlineStyle() || inlineStyle()->isEmpty())
+        return;
+    ensureMutableInlineStyle()->clear();
+    inlineStyleChanged();
+}
+
+void Element::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
+{
+    ASSERT(isStyledElement());
+    if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
+        inlineStyle->addSubresourceStyleURLs(urls, document()->elementSheet()->contents());
+}
+
+static inline bool attributeNameSort(const pair<AtomicStringImpl*, AtomicString>& p1, const pair<AtomicStringImpl*, AtomicString>& p2)
+{
+    // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same.
+    return p1.first < p2.first;
+}
+
+void Element::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
+{
+    ASSERT(isStyledElement());
+    // FIXME: Enable for SVG.
+    if (namespaceURI() != xhtmlNamespaceURI)
+        return;
+    // Interpretation of the size attributes on <input> depends on the type attribute.
+    if (hasTagName(inputTag))
+        return;
+    unsigned size = attributeCount();
+    for (unsigned i = 0; i < size; ++i) {
+        const Attribute* attribute = attributeItem(i);
+        if (!isPresentationAttribute(attribute->name()))
+            continue;
+        if (!attribute->namespaceURI().isNull())
+            return;
+        // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
+        if (attribute->name() == backgroundAttr)
+            return;
+        result.attributesAndValues.append(std::make_pair(attribute->localName().impl(), attribute->value()));
+    }
+    if (result.attributesAndValues.isEmpty())
+        return;
+    // Attribute order doesn't matter. Sort for easy equality comparison.
+    std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
+    // The cache key is non-null when the tagName is set.
+    result.tagName = localName().impl();
+}
+
+static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
+{
+    if (!key.tagName)
+        return 0;
+    ASSERT(key.attributesAndValues.size());
+    unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
+    return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
+}
+
+void Element::rebuildPresentationAttributeStyle()
+{
+    ASSERT(isStyledElement());
+    PresentationAttributeCacheKey cacheKey;
+    makePresentationAttributeCacheKey(cacheKey);
+
+    unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
+
+    PresentationAttributeCache::iterator cacheIterator;
+    if (cacheHash) {
+        cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
+        if (cacheIterator->value && cacheIterator->value->key != cacheKey)
+            cacheHash = 0;
+    } else {
+        cacheIterator = presentationAttributeCache().end();
+    }
+
+    RefPtr<StylePropertySet> style;
+    if (cacheHash && cacheIterator->value) {
+        style = cacheIterator->value->value;
+        presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
+    } else {
+        style = MutableStylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSQuirksMode);
+        unsigned size = attributeCount();
+        for (unsigned i = 0; i < size; ++i) {
+            const Attribute* attribute = attributeItem(i);
+            collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
+        }
+    }
+
+    // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
+    UniqueElementData* elementData = ensureUniqueElementData();
+
+    elementData->m_presentationAttributeStyleIsDirty = false;
+    elementData->m_presentationAttributeStyle = style->isEmpty() ? 0 : style;
+
+    if (!cacheHash || cacheIterator->value)
+        return;
+
+    OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
+    newEntry->key = cacheKey;
+    newEntry->value = style.release();
+
+    static const int presentationAttributeCacheMaximumSize = 4096;
+    if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
+        // Start building from scratch if the cache ever gets big.
+        presentationAttributeCache().clear();
+        presentationAttributeCache().set(cacheHash, newEntry.release());
+    } else {
+        cacheIterator->value = newEntry.release();
+    }
+}
+
+void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
+{
+    ASSERT(isStyledElement());
+    style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
+}
+
+void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
+{
+    ASSERT(isStyledElement());
+    style->setProperty(propertyID, cssValuePool().createValue(value, unit));
+}
+
+void Element::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
+{
+    ASSERT(isStyledElement());
+    style->setProperty(propertyID, value, false, document()->elementSheet()->contents());
+}
+
 void ElementData::deref()
 {
     if (!derefBase())
diff --git a/Source/core/dom/Element.h b/Source/core/dom/Element.h
index fed0c42..2aa1745 100644
--- a/Source/core/dom/Element.h
+++ b/Source/core/dom/Element.h
@@ -25,19 +25,21 @@
 #ifndef Element_h
 #define Element_h
 
+#include "CSSPropertyNames.h"
 #include "HTMLNames.h"
+#include "core/css/CSSPrimitiveValue.h"
 #include "core/dom/Attribute.h"
 #include "core/dom/Document.h"
-#include "core/dom/FragmentScriptingPermission.h"
 #include "core/dom/SpaceSplitString.h"
 #include "core/html/CollectionType.h"
 #include "core/platform/ScrollTypes.h"
+#include "core/rendering/RegionOversetState.h"
 
 namespace WebCore {
 
 class Animation;
-
 class Attr;
+class Attribute;
 class ClientRect;
 class ClientRectList;
 class DOMStringMap;
@@ -48,6 +50,8 @@
 class InputMethodContext;
 class IntSize;
 class Locale;
+class MutableStylePropertySet;
+class PropertySetCSSStyleDeclaration;
 class PseudoElement;
 class RenderRegion;
 class ShadowRoot;
@@ -55,6 +59,8 @@
 class StylePropertySet;
 class UniqueElementData;
 
+struct PresentationAttributeCacheKey;
+
 class ElementData : public RefCounted<ElementData> {
     WTF_MAKE_FAST_ALLOCATED;
 public:
@@ -108,7 +114,6 @@
 
 private:
     friend class Element;
-    friend class StyledElement;
     friend class ShareableElementData;
     friend class UniqueElementData;
     friend class SVGElement;
@@ -345,7 +350,7 @@
 
     const Vector<RefPtr<Attr> >& attrNodeList();
 
-    virtual CSSStyleDeclaration* style();
+    CSSStyleDeclaration* style();
 
     const QualifiedName& tagQName() const { return m_tagName; }
     String tagName() const { return nodeName(); }
@@ -366,13 +371,30 @@
     PassRefPtr<Element> cloneElementWithChildren();
     PassRefPtr<Element> cloneElementWithoutChildren();
 
-    void scheduleSyntheticStyleChange();
+    void scheduleLayerUpdate();
 
     void normalizeAttributes();
     String nodeNamePreservingCase() const;
 
     void setBooleanAttribute(const QualifiedName& name, bool);
 
+    virtual const StylePropertySet* additionalPresentationAttributeStyle() { return 0; }
+    void invalidateStyleAttribute();
+
+    const StylePropertySet* inlineStyle() const { return elementData() ? elementData()->m_inlineStyle.get() : 0; }
+
+    bool setInlineStyleProperty(CSSPropertyID, CSSValueID identifier, bool important = false);
+    bool setInlineStyleProperty(CSSPropertyID, CSSPropertyID identifier, bool important = false);
+    bool setInlineStyleProperty(CSSPropertyID, double value, CSSPrimitiveValue::UnitTypes, bool important = false);
+    bool setInlineStyleProperty(CSSPropertyID, const String& value, bool important = false);
+    bool removeInlineStyleProperty(CSSPropertyID);
+    void removeAllInlineStyleProperties();
+
+    void synchronizeStyleAttributeInternal() const;
+
+    const StylePropertySet* presentationAttributeStyle();
+    virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) { }
+
     // For exposing to DOM only.
     NamedNodeMap* attributes() const;
 
@@ -408,7 +430,7 @@
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool rendererIsNeeded(const NodeRenderingContext&);
     void recalcStyle(StyleChange = NoChange);
     void didAffectSelector(AffectedSelectorMask);
@@ -459,6 +481,12 @@
 
     bool isUnresolvedCustomElement();
 
+    void setIsInsideRegion(bool);
+    bool isInsideRegion() const;
+
+    void setRegionOversetState(RegionOversetState);
+    RegionOversetState regionOversetState() const;
+
     AtomicString computeInheritedLanguage() const;
     Locale& locale() const;
 
@@ -480,6 +508,8 @@
     String innerText();
     String outerText();
  
+    String textFromChildren();
+
     virtual String title() const;
 
     const AtomicString& pseudo() const;
@@ -578,6 +608,7 @@
     PassRefPtr<RenderStyle> originalStyleForRenderer();
 
     RenderRegion* renderRegion() const;
+    virtual bool shouldMoveToFlowThread(RenderStyle*) const;
     const AtomicString& webkitRegionOverset() const;
     Vector<RefPtr<Range> > webkitGetRegionFlowRanges() const;
 
@@ -605,6 +636,14 @@
         ScriptWrappable::init(this);
     }
 
+    virtual bool isPresentationAttribute(const QualifiedName&) const { return false; }
+
+    void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, CSSValueID identifier);
+    void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, double value, CSSPrimitiveValue::UnitTypes);
+    void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, const String& value);
+
+    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
+
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0) OVERRIDE;
@@ -632,6 +671,16 @@
     void classAttributeChanged(const AtomicString& newClassString);
 
 private:
+    void styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason);
+
+    void inlineStyleChanged();
+    PropertySetCSSStyleDeclaration* inlineStyleCSSOMWrapper();
+    void setInlineStyleFromString(const AtomicString&);
+    MutableStylePropertySet* ensureMutableInlineStyle();
+
+    void makePresentationAttributeCacheKey(PresentationAttributeCacheKey&) const;
+    void rebuildPresentationAttributeStyle();
+
     void updatePseudoElement(PseudoId, StyleChange);
     void createPseudoElementIfNeeded(PseudoId);
 
@@ -771,7 +820,7 @@
     Node* n = previousSibling();
     while (n && !n->isElementNode())
         n = n->previousSibling();
-    return static_cast<Element*>(n);
+    return toElement(n);
 }
 
 inline Element* Node::nextElementSibling() const
@@ -779,7 +828,7 @@
     Node* n = nextSibling();
     while (n && !n->isElementNode())
         n = n->nextSibling();
-    return static_cast<Element*>(n);
+    return toElement(n);
 }
 
 inline bool Element::fastHasAttribute(const QualifiedName& name) const
@@ -914,6 +963,21 @@
         clearFlag(IsInShadowTreeFlag);
 }
 
+inline void Element::invalidateStyleAttribute()
+{
+    ASSERT(elementData());
+    elementData()->m_styleAttributeIsDirty = true;
+}
+
+inline const StylePropertySet* Element::presentationAttributeStyle()
+{
+    if (!elementData())
+        return 0;
+    if (elementData()->m_presentationAttributeStyleIsDirty)
+        rebuildPresentationAttributeStyle();
+    return elementData()->presentationAttributeStyle();
+}
+
 inline bool isShadowHost(const Node* node)
 {
     return node && node->isElementNode() && toElement(node)->shadow();
diff --git a/Source/core/dom/Element.idl b/Source/core/dom/Element.idl
index 55f592f..543a8a1 100644
--- a/Source/core/dom/Element.idl
+++ b/Source/core/dom/Element.idl
@@ -105,11 +105,6 @@
     [ImplementedAs=createShadowRoot, RaisesException] ShadowRoot webkitCreateShadowRoot();
     [ImplementedAs=shadowRoot, PerWorldBindings] readonly attribute ShadowRoot webkitShadowRoot;
 
-    // ChildNode interface API
-    [PerWorldBindings] readonly attribute Element previousElementSibling;
-    [PerWorldBindings] readonly attribute Element nextElementSibling;
-    [RaisesException] void remove();
-
     // CSSOM View Module API
     ClientRectList getClientRects();
     ClientRect getBoundingClientRect();
@@ -199,3 +194,7 @@
     [NotEnumerable, PerWorldBindings] attribute EventListener onwebkitfullscreenchange;
     [NotEnumerable, PerWorldBindings] attribute EventListener onwebkitfullscreenerror;
 };
+
+Element implements ParentNode;
+Element implements ChildNode;
+
diff --git a/Source/core/dom/ElementRareData.cpp b/Source/core/dom/ElementRareData.cpp
index 24e14a9..dd404bf 100644
--- a/Source/core/dom/ElementRareData.cpp
+++ b/Source/core/dom/ElementRareData.cpp
@@ -32,6 +32,7 @@
 #include "core/dom/ElementRareData.h"
 
 #include "core/dom/WebCoreMemoryInstrumentation.h"
+#include "core/rendering/RegionOversetState.h"
 #include "core/rendering/style/RenderStyle.h"
 
 namespace WebCore {
@@ -39,6 +40,7 @@
 struct SameSizeAsElementRareData : NodeRareData {
     short indices[2];
     unsigned bitfields;
+    RegionOversetState regionOversetState;
     LayoutSize sizeForResizing;
     IntSize scrollOffset;
     void* pointers[9];
diff --git a/Source/core/dom/ElementRareData.h b/Source/core/dom/ElementRareData.h
index 89bee36..440df8e 100644
--- a/Source/core/dom/ElementRareData.h
+++ b/Source/core/dom/ElementRareData.h
@@ -22,7 +22,6 @@
 #ifndef ElementRareData_h
 #define ElementRareData_h
 
-#include "core/animation/Animation.h"
 #include "core/dom/DatasetDOMStringMap.h"
 #include "core/dom/NamedNodeMap.h"
 #include "core/dom/NodeRareData.h"
@@ -31,7 +30,7 @@
 #include "core/html/ClassList.h"
 #include "core/html/ime/InputMethodContext.h"
 #include "core/rendering/style/StyleInheritedData.h"
-#include <wtf/OwnPtr.h>
+#include "wtf/OwnPtr.h"
 
 namespace WebCore {
 
@@ -64,6 +63,12 @@
     bool isInCanvasSubtree() const { return m_isInCanvasSubtree; }
     void setIsInCanvasSubtree(bool value) { m_isInCanvasSubtree = value; }
 
+    bool isInsideRegion() const { return m_isInsideRegion; }
+    void setIsInsideRegion(bool value) { m_isInsideRegion = value; }
+
+    RegionOversetState regionOversetState() const { return m_regionOversetState; }
+    void setRegionOversetState(RegionOversetState state) { m_regionOversetState = state; }
+
     bool containsFullScreenElement() { return m_containsFullScreenElement; }
     void setContainsFullScreenElement(bool value) { m_containsFullScreenElement = value; }
 
@@ -164,6 +169,9 @@
     unsigned m_childrenAffectedByForwardPositionalRules : 1;
     unsigned m_childrenAffectedByBackwardPositionalRules : 1;
 
+    unsigned m_isInsideRegion : 1;
+    RegionOversetState m_regionOversetState;
+
     LayoutSize m_minimumSizeForResizing;
     IntSize m_savedLayerScrollOffset;
     RefPtr<RenderStyle> m_computedStyle;
@@ -207,6 +215,8 @@
     , m_childrenAffectedByDirectAdjacentRules(false)
     , m_childrenAffectedByForwardPositionalRules(false)
     , m_childrenAffectedByBackwardPositionalRules(false)
+    , m_isInsideRegion(false)
+    , m_regionOversetState(RegionUndefined)
     , m_minimumSizeForResizing(defaultMinimumSizeForResizing())
 {
 }
diff --git a/Source/core/dom/Event.cpp b/Source/core/dom/Event.cpp
index c713e0d..770e175 100644
--- a/Source/core/dom/Event.cpp
+++ b/Source/core/dom/Event.cpp
@@ -172,11 +172,6 @@
     info.addMember(m_underlyingEvent, "underlyingEvent");
 }
 
-PassRefPtr<Event> Event::cloneFor(HTMLIFrameElement*) const
-{
-    return Event::create(type(), bubbles(), cancelable());
-}
-
 void Event::setTarget(PassRefPtr<EventTarget> target)
 {
     if (m_target == target)
diff --git a/Source/core/dom/Event.h b/Source/core/dom/Event.h
index f736261..60a60fa 100644
--- a/Source/core/dom/Event.h
+++ b/Source/core/dom/Event.h
@@ -27,11 +27,8 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/DOMTimeStamp.h"
 #include "core/dom/EventContext.h"
-#include "core/dom/EventNames.h"
-#include <wtf/HashMap.h>
-#include <wtf/ListHashSet.h>
-#include <wtf/RefCounted.h>
-#include <wtf/text/AtomicString.h>
+#include "wtf/RefCounted.h"
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
@@ -169,8 +166,6 @@
 
     virtual void reportMemoryUsage(MemoryObjectInfo*) const;
 
-    virtual PassRefPtr<Event> cloneFor(HTMLIFrameElement*) const;
-
 protected:
     Event();
     Event(const AtomicString& type, bool canBubble, bool cancelable);
diff --git a/Source/core/dom/EventAliases.in b/Source/core/dom/EventAliases.in
new file mode 100644
index 0000000..07c2e49
--- /dev/null
+++ b/Source/core/dom/EventAliases.in
@@ -0,0 +1,13 @@
+# Aliases
+Events ImplementedAs=Event
+HTMLEvents ImplementedAs=Event
+KeyboardEvents ImplementedAs=KeyboardEvent
+MouseEvents ImplementedAs=MouseEvent
+MutationEvents ImplementedAs=MutationEvent
+OrientationEvent ImplementedAs=Event, Conditional=ORIENTATION_EVENTS
+SVGEvents ImplementedAs=Event
+SVGZoomEvents ImplementedAs=SVGZoomEvent
+UIEvents ImplementedAs=UIEvent
+WebKitTransitionEvent ImplementedAs=TransitionEvent
+
+core/dom/TouchEvent EnabledAtRuntime=touchEnabled
diff --git a/Source/core/dom/EventDispatcher.cpp b/Source/core/dom/EventDispatcher.cpp
index c84ede2..bf9f40b 100644
--- a/Source/core/dom/EventDispatcher.cpp
+++ b/Source/core/dom/EventDispatcher.cpp
@@ -35,8 +35,7 @@
 #include "core/dom/WindowEventContext.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/FrameView.h"
-#include <wtf/RefPtr.h>
-#include <wtf/UnusedParam.h>
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
@@ -200,6 +199,7 @@
     // implementation detail and not part of the DOM.
     if (!m_event->defaultPrevented() && !m_event->defaultHandled()) {
         // Non-bubbling events call only one default event handler, the one for the target.
+        m_node->willCallDefaultEventHandler(*m_event);
         m_node->defaultEventHandler(m_event.get());
         ASSERT(!m_event->defaultPrevented());
         if (m_event->defaultHandled())
@@ -209,6 +209,7 @@
         if (m_event->bubbles()) {
             size_t size = m_event->eventPath().size();
             for (size_t i = 1; i < size; ++i) {
+                m_event->eventPath()[i]->node()->willCallDefaultEventHandler(*m_event);
                 m_event->eventPath()[i]->node()->defaultEventHandler(m_event.get());
                 ASSERT(!m_event->defaultPrevented());
                 if (m_event->defaultHandled())
diff --git a/Source/core/dom/EventDispatcher.h b/Source/core/dom/EventDispatcher.h
index b4a439e..5587132 100644
--- a/Source/core/dom/EventDispatcher.h
+++ b/Source/core/dom/EventDispatcher.h
@@ -28,10 +28,8 @@
 
 #include "core/dom/EventContext.h"
 #include "core/dom/SimulatedClickOptions.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/EventListenerMap.cpp b/Source/core/dom/EventListenerMap.cpp
index 7753865..1bc8690 100644
--- a/Source/core/dom/EventListenerMap.cpp
+++ b/Source/core/dom/EventListenerMap.cpp
@@ -34,12 +34,11 @@
 #include "core/dom/EventListenerMap.h"
 
 #include "core/dom/EventTarget.h"
-#include <wtf/MainThread.h>
-#include <wtf/StdLibExtras.h>
-#include <wtf/Vector.h>
+#include "wtf/StdLibExtras.h"
+#include "wtf/Vector.h"
 
 #ifndef NDEBUG
-#include <wtf/Threading.h>
+#include "wtf/Threading.h"
 #endif
 
 using namespace WTF;
diff --git a/Source/core/dom/EventNames.h b/Source/core/dom/EventNames.h
index 9438b10..69796a9 100644
--- a/Source/core/dom/EventNames.h
+++ b/Source/core/dom/EventNames.h
@@ -252,6 +252,8 @@
     \
     macro(webkitregionlayoutupdate) \
     \
+    macro(webkitregionoversetchange) \
+    \
     macro(webkitnetworkinfochange) \
     \
     macro(webkitresourcetimingbufferfull) \
diff --git a/Source/core/dom/EventNames.in b/Source/core/dom/EventNames.in
deleted file mode 100644
index 25a9ac3..0000000
--- a/Source/core/dom/EventNames.in
+++ /dev/null
@@ -1,64 +0,0 @@
-namespace="Event"
-
-core/css/CSSFontFaceLoadEvent
-core/dom/AutocompleteErrorEvent
-core/dom/BeforeLoadEvent
-core/dom/CompositionEvent
-core/dom/CustomEvent
-core/dom/DeviceOrientationEvent
-core/dom/ErrorEvent
-core/dom/Event
-core/dom/FocusEvent
-core/dom/HashChangeEvent
-core/dom/KeyboardEvent
-core/dom/MessageEvent
-core/dom/MouseEvent
-core/dom/MutationEvent
-core/dom/OverflowEvent
-core/dom/PageTransitionEvent
-core/dom/PopStateEvent
-core/dom/ProgressEvent
-core/dom/ResourceProgressEvent
-core/dom/SecurityPolicyViolationEvent
-core/dom/TextEvent
-core/dom/TouchEvent runtimeConditional=touchEnabled
-core/dom/TransitionEvent
-core/dom/UIEvent
-core/dom/WebKitAnimationEvent implementedAs=AnimationEvent
-core/dom/WebKitTransitionEvent implementedAs=TransitionEvent
-core/dom/WheelEvent
-core/html/MediaKeyEvent
-core/html/canvas/WebGLContextEvent
-core/html/track/TrackEvent
-core/page/SpeechInputEvent conditional=INPUT_SPEECH
-core/storage/StorageEvent
-core/svg/SVGEvents implementedAs=Event
-core/svg/SVGZoomEvent
-core/xml/XMLHttpRequestProgressEvent
-modules/device_orientation/DeviceMotionEvent
-modules/encryptedmedia/MediaKeyMessageEvent conditional=ENCRYPTED_MEDIA_V2
-modules/encryptedmedia/MediaKeyNeededEvent conditional=ENCRYPTED_MEDIA_V2
-modules/indexeddb/IDBVersionChangeEvent
-modules/mediastream/MediaStreamEvent
-modules/mediastream/MediaStreamTrackEvent
-modules/mediastream/RTCDTMFToneChangeEvent
-modules/mediastream/RTCDataChannelEvent
-modules/mediastream/RTCIceCandidateEvent
-modules/speech/SpeechRecognitionError
-modules/speech/SpeechRecognitionEvent
-modules/speech/SpeechSynthesisEvent
-modules/webaudio/AudioProcessingEvent conditional=WEB_AUDIO
-modules/webaudio/OfflineAudioCompletionEvent conditional=WEB_AUDIO
-modules/webmidi/MIDIConnectionEvent
-modules/webmidi/MIDIMessageEvent
-modules/websockets/CloseEvent
-
-# Aliases
-Events implementedAs=Event
-HTMLEvents implementedAs=Event
-KeyboardEvents implementedAs=KeyboardEvent
-MouseEvents implementedAs=MouseEvent
-MutationEvents implementedAs=MutationEvent
-OrientationEvent implementedAs=Event, conditional=ORIENTATION_EVENTS
-SVGZoomEvents implementedAs=SVGZoomEvent
-UIEvents implementedAs=UIEvent
diff --git a/Source/core/dom/EventRetargeter.h b/Source/core/dom/EventRetargeter.h
index 76cfd9e..f274e70 100644
--- a/Source/core/dom/EventRetargeter.h
+++ b/Source/core/dom/EventRetargeter.h
@@ -27,7 +27,6 @@
 #include "core/svg/SVGElementInstance.h"
 #include "core/svg/SVGUseElement.h"
 #include "wtf/HashMap.h"
-#include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/EventTarget.cpp b/Source/core/dom/EventTarget.cpp
index c06d6dd..15fb804 100644
--- a/Source/core/dom/EventTarget.cpp
+++ b/Source/core/dom/EventTarget.cpp
@@ -37,9 +37,8 @@
 #include "core/dom/Event.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include <wtf/MainThread.h>
-#include <wtf/StdLibExtras.h>
-#include <wtf/Vector.h>
+#include "wtf/StdLibExtras.h"
+#include "wtf/Vector.h"
 
 using namespace WTF;
 
diff --git a/Source/core/dom/EventTarget.h b/Source/core/dom/EventTarget.h
index 58837f0..2d8a0a9 100644
--- a/Source/core/dom/EventTarget.h
+++ b/Source/core/dom/EventTarget.h
@@ -34,14 +34,12 @@
 
 #include "core/dom/EventListenerMap.h"
 #include "core/dom/EventNames.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/text/AtomicStringHash.h>
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
     class AudioContext;
-    class DedicatedWorkerContext;
+    class DedicatedWorkerGlobalScope;
     class DOMApplicationCache;
     class DOMWindow;
     class Event;
@@ -65,7 +63,7 @@
     class ScriptExecutionContext;
     class ScriptProcessorNode;
     class SharedWorker;
-    class SharedWorkerContext;
+    class SharedWorkerGlobalScope;
     class TextTrack;
     class TextTrackCue;
     class WebSocket;
diff --git a/Source/core/dom/EventTargetFactory.in b/Source/core/dom/EventTargetFactory.in
index 5ebf267..1929c1e 100644
--- a/Source/core/dom/EventTargetFactory.in
+++ b/Source/core/dom/EventTargetFactory.in
@@ -3,7 +3,7 @@
 core/css/FontLoader
 core/dom/MessagePort
 core/dom/Node
-core/dom/WebKitNamedFlow implementedAs=NamedFlow
+core/dom/WebKitNamedFlow ImplementedAs=NamedFlow
 core/fileapi/FileReader
 core/html/MediaController
 core/html/track/TextTrack
@@ -12,15 +12,15 @@
 core/loader/appcache/DOMApplicationCache
 core/page/EventSource
 core/page/Performance
-core/page/Window implementedAs=DOMWindow
+core/page/Window ImplementedAs=DOMWindow
 core/svg/SVGElementInstance
-core/workers/DedicatedWorkerContext
+core/workers/DedicatedWorkerGlobalScope
 core/workers/SharedWorker
-core/workers/SharedWorkerContext
+core/workers/SharedWorkerGlobalScope
 core/workers/Worker
 core/xml/XMLHttpRequest
 core/xml/XMLHttpRequestUpload
-modules/encryptedmedia/MediaKeySession conditional=ENCRYPTED_MEDIA_V2
+modules/encryptedmedia/MediaKeySession Conditional=ENCRYPTED_MEDIA_V2
 modules/filesystem/FileWriter
 modules/indexeddb/IDBDatabase
 modules/indexeddb/IDBOpenDBRequest
@@ -36,11 +36,11 @@
 modules/mediastream/RTCDTMFSender
 modules/mediastream/RTCDataChannel
 modules/mediastream/RTCPeerConnection
-modules/notifications/Notification conditional=NOTIFICATIONS
+modules/notifications/Notification Conditional=NOTIFICATIONS
 modules/speech/SpeechRecognition
 modules/speech/SpeechSynthesisUtterance
-modules/webaudio/AudioContext conditional=WEB_AUDIO
-modules/webaudio/AudioNode conditional=WEB_AUDIO
+modules/webaudio/AudioContext Conditional=WEB_AUDIO
+modules/webaudio/AudioNode Conditional=WEB_AUDIO
 modules/webmidi/MIDIAccess
 modules/webmidi/MIDIInput
 modules/webmidi/MIDIPort
diff --git a/Source/core/dom/ExceptionBase.cpp b/Source/core/dom/ExceptionBase.cpp
deleted file mode 100644
index 9276fd7..0000000
--- a/Source/core/dom/ExceptionBase.cpp
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/dom/ExceptionBase.h"
-#include "core/dom/ExceptionCode.h"
-
-#include <wtf/text/WTFString.h>
-
-namespace WebCore {
-
-ExceptionBase::ExceptionBase(const ExceptionCodeDescription& description)
-    : m_code(description.code)
-    , m_description(description.description)
-{
-    if (description.name)
-        m_name = description.name;
-    else
-        m_name = description.typeName;
-}
-
-String ExceptionBase::toString() const
-{
-    return m_name + ": " + message();
-}
-
-} // namespace WebCore
diff --git a/Source/core/dom/ExceptionCode.h b/Source/core/dom/ExceptionCode.h
index 84b520e..cf6dc69 100644
--- a/Source/core/dom/ExceptionCode.h
+++ b/Source/core/dom/ExceptionCode.h
@@ -19,9 +19,6 @@
 #ifndef ExceptionCode_h
 #define ExceptionCode_h
 
-// FIXME: Move this header into the files that actually need it.
-#include "DOMException.h"
-
 namespace WebCore {
 
     // The DOM standards use unsigned short for exception codes.
@@ -34,40 +31,76 @@
     // Some of these are considered historical since they have been
     // changed or removed from the specifications.
     enum {
+        // FIXME: Rename these to use CamelCase matching the exception name.
         INDEX_SIZE_ERR = 1,
-        HIERARCHY_REQUEST_ERR = 3,
-        WRONG_DOCUMENT_ERR = 4,
-        INVALID_CHARACTER_ERR = 5,
-        NO_MODIFICATION_ALLOWED_ERR = 7,
-        NOT_FOUND_ERR = 8,
-        NOT_SUPPORTED_ERR = 9,
-        INUSE_ATTRIBUTE_ERR = 10, // Historical. Only used in setAttributeNode etc which have been removed from the DOM specs.
+        HIERARCHY_REQUEST_ERR,
+        WRONG_DOCUMENT_ERR,
+        INVALID_CHARACTER_ERR,
+        NO_MODIFICATION_ALLOWED_ERR,
+        NOT_FOUND_ERR,
+        NOT_SUPPORTED_ERR,
+        INUSE_ATTRIBUTE_ERR, // Historical. Only used in setAttributeNode etc which have been removed from the DOM specs.
 
         // Introduced in DOM Level 2:
-        INVALID_STATE_ERR = 11,
-        SYNTAX_ERR = 12,
-        INVALID_MODIFICATION_ERR = 13,
-        NAMESPACE_ERR = 14,
-        INVALID_ACCESS_ERR = 15,
+        INVALID_STATE_ERR,
+        SYNTAX_ERR,
+        INVALID_MODIFICATION_ERR,
+        NAMESPACE_ERR,
+        INVALID_ACCESS_ERR,
 
         // Introduced in DOM Level 3:
-        TYPE_MISMATCH_ERR = 17, // Historical; use TypeError instead
+        TYPE_MISMATCH_ERR, // Historical; use TypeError instead
 
         // XMLHttpRequest extension:
-        SECURITY_ERR = 18,
+        SECURITY_ERR,
 
         // Others introduced in HTML5:
-        NETWORK_ERR = 19,
-        ABORT_ERR = 20,
-        URL_MISMATCH_ERR = 21,
-        QUOTA_EXCEEDED_ERR = 22,
-        TIMEOUT_ERR = 23,
-        INVALID_NODE_TYPE_ERR = 24,
-        DATA_CLONE_ERR = 25,
+        NETWORK_ERR,
+        ABORT_ERR,
+        URL_MISMATCH_ERR,
+        QUOTA_EXCEEDED_ERR,
+        TIMEOUT_ERR,
+        INVALID_NODE_TYPE_ERR,
+        DATA_CLONE_ERR,
+
+        // These are IDB-specific.
+        IDBNotFoundError,
+        UnknownError,
+        ConstraintError,
+        DataError,
+        TransactionInactiveError,
+        ReadOnlyError,
+        VersionError,
+
+        // File system
+        // FIXME: Consolidate these once https://crbug.com/252233 is fixed.
+        FSNotFoundError,
+        FSSecurityError,
+        FSAbortError,
+        FSNotReadableError,
+        FSEncodingError,
+        FSNoModificationAllowedError,
+        FSInvalidStateError,
+        FSSyntaxError,
+        FSInvalidModificationError,
+        FSQuotaExceededError,
+        FSTypeMismatchError,
+        FSPathExistsError,
+
+        // SQL
+        // FIXME: Consolidate these once https://crbug.com/252233 is fixed.
+        SQLUnknownError,
+        SQLDatabaseError,
+        SQLVersionError,
+        SQLTooLargeError,
+        SQLQuotaExceededError,
+        SQLSyntaxError,
+        SQLConstraintError,
+        SQLTimeoutError,
 
         // WebIDL exception types, handled by the binding layer.
         // FIXME: Add GeneralError, EvalError, etc. when implemented in the bindings.
-        TypeError = 105,
+        TypeError,
     };
 
 } // namespace WebCore
diff --git a/Source/core/dom/FullscreenController.cpp b/Source/core/dom/FullscreenController.cpp
index b01d12b..ed63fee 100644
--- a/Source/core/dom/FullscreenController.cpp
+++ b/Source/core/dom/FullscreenController.cpp
@@ -98,17 +98,9 @@
     return false;
 }
 
-bool FullscreenController::isAnimatingFullScreen(Document* document)
-{
-    if (FullscreenController* found = fromIfExists(document))
-        return found->isAnimatingFullScreen();
-    return false;
-}
-
 FullscreenController::FullscreenController(Document* document)
     : DocumentLifecycleObserver(document)
     , m_areKeysEnabledInFullScreen(false)
-    , m_isAnimatingFullScreen(false)
     , m_fullScreenRenderer(0)
     , m_fullScreenChangeDelayTimer(this, &FullscreenController::fullScreenChangeDelayTimerFired)
 {
@@ -539,18 +531,6 @@
         fullScreenElementRemoved();
 }
 
-void FullscreenController::setAnimatingFullScreen(bool flag)
-{
-    if (m_isAnimatingFullScreen == flag)
-        return;
-    m_isAnimatingFullScreen = flag;
-
-    if (m_fullScreenElement && m_fullScreenElement->isDescendantOf(document())) {
-        m_fullScreenElement->setNeedsStyleRecalc();
-        document()->scheduleForcedStyleRecalc();
-    }
-}
-
 void FullscreenController::clearFullscreenElementStack()
 {
     m_fullScreenElementStack.clear();
diff --git a/Source/core/dom/FullscreenController.h b/Source/core/dom/FullscreenController.h
index b32a96b..9fbfe3d 100644
--- a/Source/core/dom/FullscreenController.h
+++ b/Source/core/dom/FullscreenController.h
@@ -57,7 +57,6 @@
     static Element* fullscreenElementFrom(Document*);
     static Element* currentFullScreenElementFrom(Document*);
     static bool isFullScreen(Document*);
-    static bool isAnimatingFullScreen(Document*);
     static bool isActiveFullScreenElement(const Element*);
 
     enum FullScreenCheckType {
@@ -85,8 +84,6 @@
     bool fullScreenIsAllowedForElement(Element*) const;
     void fullScreenElementRemoved();
     void removeFullScreenElementOfSubtree(Node*, bool amongChildrenOnly = false);
-    bool isAnimatingFullScreen() const { return m_isAnimatingFullScreen; }
-    void setAnimatingFullScreen(bool);
 
     // W3C API
     static bool webkitFullscreenEnabled(Document*);
@@ -109,7 +106,6 @@
     void fullScreenChangeDelayTimerFired(Timer<FullscreenController>*);
 
     bool m_areKeysEnabledInFullScreen;
-    bool m_isAnimatingFullScreen;
     RefPtr<Element> m_fullScreenElement;
     Vector<RefPtr<Element> > m_fullScreenElementStack;
     RenderFullScreen* m_fullScreenRenderer;
diff --git a/Source/core/dom/GestureEvent.h b/Source/core/dom/GestureEvent.h
index f0809b8..a0d6f2e 100644
--- a/Source/core/dom/GestureEvent.h
+++ b/Source/core/dom/GestureEvent.h
@@ -27,11 +27,7 @@
 #define GestureEvent_h
 
 #include "core/dom/EventDispatcher.h"
-#include "core/dom/EventNames.h"
 #include "core/dom/MouseRelatedEvent.h"
-#include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/platform/PlatformEvent.h"
 #include "core/platform/PlatformGestureEvent.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/KeyboardEvent.cpp b/Source/core/dom/KeyboardEvent.cpp
index 25e42d4..5354fc0 100644
--- a/Source/core/dom/KeyboardEvent.cpp
+++ b/Source/core/dom/KeyboardEvent.cpp
@@ -212,9 +212,10 @@
 
 KeyboardEvent* findKeyboardEvent(Event* event)
 {
-    for (Event* e = event; e; e = e->underlyingEvent())
+    for (Event* e = event; e; e = e->underlyingEvent()) {
         if (e->isKeyboardEvent())
-            return static_cast<KeyboardEvent*>(e);
+            return toKeyboardEvent(e);
+    }
     return 0;
 }
 
diff --git a/Source/core/dom/KeyboardEvent.h b/Source/core/dom/KeyboardEvent.h
index 1900174..acb0d32 100644
--- a/Source/core/dom/KeyboardEvent.h
+++ b/Source/core/dom/KeyboardEvent.h
@@ -26,7 +26,6 @@
 
 #include "core/dom/EventDispatchMediator.h"
 #include "core/dom/UIEventWithKeyState.h"
-#include <wtf/Vector.h>
 
 namespace WebCore {
 
@@ -123,6 +122,12 @@
     virtual bool dispatchEvent(EventDispatcher*) const OVERRIDE;
 };
 
+inline KeyboardEvent* toKeyboardEvent(Event* event)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!event || event->isKeyboardEvent());
+    return static_cast<KeyboardEvent*>(event);
+}
+
 } // namespace WebCore
 
 #endif // KeyboardEvent_h
diff --git a/Source/core/dom/MessageChannel.idl b/Source/core/dom/MessageChannel.idl
index ca0e39f..c380c44 100644
--- a/Source/core/dom/MessageChannel.idl
+++ b/Source/core/dom/MessageChannel.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     Constructor,
     ConstructorCallWith=ScriptExecutionContext,
     CustomConstructor
diff --git a/Source/core/dom/MessageEvent.idl b/Source/core/dom/MessageEvent.idl
index 540b17d..7b5fec3 100644
--- a/Source/core/dom/MessageEvent.idl
+++ b/Source/core/dom/MessageEvent.idl
@@ -26,7 +26,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     ConstructorTemplate=Event
 ] interface MessageEvent : Event {
     [InitializedByEventConstructor] readonly attribute DOMString origin;
diff --git a/Source/core/dom/MessagePort.cpp b/Source/core/dom/MessagePort.cpp
index dec07cf..37181e2 100644
--- a/Source/core/dom/MessagePort.cpp
+++ b/Source/core/dom/MessagePort.cpp
@@ -27,15 +27,13 @@
 #include "config.h"
 #include "core/dom/MessagePort.h"
 
-#include <wtf/text/AtomicString.h>
 #include "core/dom/Document.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/MessageEvent.h"
 #include "core/page/DOMWindow.h"
-#include "core/platform/Timer.h"
-#include "core/workers/WorkerContext.h"
-#include "weborigin/SecurityOrigin.h"
+#include "core/workers/WorkerGlobalScope.h"
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
@@ -164,7 +162,7 @@
     while (m_entangledChannel && m_entangledChannel->tryGetMessageFromRemote(message, channels)) {
 
         // close() in Worker onmessage handler should prevent next message from dispatching.
-        if (m_scriptExecutionContext->isWorkerContext() && static_cast<WorkerContext*>(m_scriptExecutionContext)->isClosing())
+        if (m_scriptExecutionContext->isWorkerGlobalScope() && toWorkerGlobalScope(m_scriptExecutionContext)->isClosing())
             return;
 
         OwnPtr<MessagePortArray> ports = MessagePort::entanglePorts(*m_scriptExecutionContext, channels.release());
diff --git a/Source/core/dom/MessagePortChannel.h b/Source/core/dom/MessagePortChannel.h
index c11c363..5c78a31 100644
--- a/Source/core/dom/MessagePortChannel.h
+++ b/Source/core/dom/MessagePortChannel.h
@@ -32,13 +32,9 @@
 #define MessagePortChannel_h
 
 #include "bindings/v8/SerializedScriptValue.h"
-#include <wtf/Forward.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/Forward.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/platform/mediastream/MediaStreamSourcesQueryClient.h b/Source/core/dom/Microtask.cpp
similarity index 67%
rename from Source/core/platform/mediastream/MediaStreamSourcesQueryClient.h
rename to Source/core/dom/Microtask.cpp
index 6268c5a..cb0b12b 100644
--- a/Source/core/platform/mediastream/MediaStreamSourcesQueryClient.h
+++ b/Source/core/dom/Microtask.cpp
@@ -1,6 +1,5 @@
 /*
- * Copyright (C) 2011 Ericsson AB. All rights reserved.
- * Copyright (C) 2012 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -12,7 +11,7 @@
  *    notice, this list of conditions and the following disclaimer
  *    in the documentation and/or other materials provided with the
  *    distribution.
- * 3. Neither the name of Ericsson nor the names of its contributors
+ * 3. Neither the name of Google Inc. nor the names of its contributors
  *    may be used to endorse or promote products derived from this
  *    software without specific prior written permission.
  *
@@ -29,23 +28,29 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef MediaStreamSourcesQueryClient_h
-#define MediaStreamSourcesQueryClient_h
+#include "config.h"
+#include "core/dom/Microtask.h"
 
-#include "core/platform/mediastream/MediaStreamSource.h"
+#include "core/dom/CustomElementCallbackDispatcher.h"
+#include "core/dom/MutationObserver.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
-class MediaStreamSourcesQueryClient : public RefCounted<MediaStreamSourcesQueryClient> {
-public:
-    virtual ~MediaStreamSourcesQueryClient() { }
+void Microtask::performCheckpoint()
+{
+    static bool performingCheckpoint = false;
+    if (performingCheckpoint)
+        return;
+    performingCheckpoint = true;
 
-    virtual bool audio() const = 0;
-    virtual bool video() const = 0;
+    bool anyWorkDone;
+    do {
+        MutationObserver::deliverAllMutations();
+        anyWorkDone = CustomElementCallbackDispatcher::instance().dispatch();
+    } while (anyWorkDone);
 
-    virtual void didCompleteQuery(const MediaStreamSourceVector& audioSources, const MediaStreamSourceVector& videoSources) = 0;
-};
+    performingCheckpoint = false;
+}
 
 } // namespace WebCore
-
-#endif // MediaStreamSourcesQueryClient_h
diff --git a/Source/core/platform/mediastream/MediaStreamSourcesQueryClient.h b/Source/core/dom/Microtask.h
similarity index 66%
copy from Source/core/platform/mediastream/MediaStreamSourcesQueryClient.h
copy to Source/core/dom/Microtask.h
index 6268c5a..27f72cb 100644
--- a/Source/core/platform/mediastream/MediaStreamSourcesQueryClient.h
+++ b/Source/core/dom/Microtask.h
@@ -1,6 +1,5 @@
 /*
- * Copyright (C) 2011 Ericsson AB. All rights reserved.
- * Copyright (C) 2012 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -12,7 +11,7 @@
  *    notice, this list of conditions and the following disclaimer
  *    in the documentation and/or other materials provided with the
  *    distribution.
- * 3. Neither the name of Ericsson nor the names of its contributors
+ * 3. Neither the name of Google Inc. nor the names of its contributors
  *    may be used to endorse or promote products derived from this
  *    software without specific prior written permission.
  *
@@ -29,23 +28,19 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef MediaStreamSourcesQueryClient_h
-#define MediaStreamSourcesQueryClient_h
-
-#include "core/platform/mediastream/MediaStreamSource.h"
+#ifndef Microtask_h
+#define Microtask_h
 
 namespace WebCore {
 
-class MediaStreamSourcesQueryClient : public RefCounted<MediaStreamSourcesQueryClient> {
+class Microtask {
 public:
-    virtual ~MediaStreamSourcesQueryClient() { }
+    static void performCheckpoint();
 
-    virtual bool audio() const = 0;
-    virtual bool video() const = 0;
-
-    virtual void didCompleteQuery(const MediaStreamSourceVector& audioSources, const MediaStreamSourceVector& videoSources) = 0;
+private:
+    explicit Microtask();
 };
 
-} // namespace WebCore
+}
 
-#endif // MediaStreamSourcesQueryClient_h
+#endif // Microtask_h
diff --git a/Source/core/dom/MouseEvent.cpp b/Source/core/dom/MouseEvent.cpp
index c1a8f6c..c0a6cbe 100644
--- a/Source/core/dom/MouseEvent.cpp
+++ b/Source/core/dom/MouseEvent.cpp
@@ -204,36 +204,6 @@
     return target() ? target()->toNode() : 0;
 }
 
-// FIXME: Fix positioning. e.g. We need to consider border/padding.
-// https://bugs.webkit.org/show_bug.cgi?id=93696
-inline static int adjustedClientX(int innerClientX, HTMLIFrameElement* iframe, FrameView* frameView)
-{
-    return iframe->offsetLeft() - frameView->scrollX() + innerClientX;
-}
-
-inline static int adjustedClientY(int innerClientY, HTMLIFrameElement* iframe, FrameView* frameView)
-{
-    return iframe->offsetTop() - frameView->scrollY() + innerClientY;
-}
-
-PassRefPtr<Event> MouseEvent::cloneFor(HTMLIFrameElement* iframe) const
-{
-    ASSERT(iframe);
-    RefPtr<MouseEvent> clonedMouseEvent = MouseEvent::create();
-    Frame* frame = iframe->document()->frame();
-    FrameView* frameView = frame ? frame->view() : 0;
-    clonedMouseEvent->initMouseEvent(type(), bubbles(), cancelable(),
-            iframe->document()->defaultView(),
-            detail(), screenX(), screenY(),
-            frameView ? adjustedClientX(clientX(), iframe, frameView) : 0,
-            frameView ? adjustedClientY(clientY(), iframe, frameView) : 0,
-            ctrlKey(), altKey(), shiftKey(), metaKey(),
-            button(),
-            // Nullifies relatedTarget.
-            0);
-    return clonedMouseEvent.release();
-}
-
 PassRefPtr<SimulatedMouseEvent> SimulatedMouseEvent::create(const AtomicString& eventType, PassRefPtr<AbstractView> view, PassRefPtr<Event> underlyingEvent)
 {
     return adoptRef(new SimulatedMouseEvent(eventType, view, underlyingEvent));
@@ -257,7 +227,7 @@
     setUnderlyingEvent(underlyingEvent);
 
     if (this->underlyingEvent() && this->underlyingEvent()->isMouseEvent()) {
-        MouseEvent* mouseEvent = static_cast<MouseEvent*>(this->underlyingEvent());
+        MouseEvent* mouseEvent = toMouseEvent(this->underlyingEvent());
         m_screenLocation = mouseEvent->screenLocation();
         initCoordinates(mouseEvent->clientLocation());
     }
@@ -275,7 +245,7 @@
 
 MouseEvent* MouseEventDispatchMediator::event() const
 {
-    return static_cast<MouseEvent*>(EventDispatchMediator::event());
+    return toMouseEvent(EventDispatchMediator::event());
 }
 
 bool MouseEventDispatchMediator::dispatchEvent(EventDispatcher* dispatcher) const
diff --git a/Source/core/dom/MouseEvent.h b/Source/core/dom/MouseEvent.h
index d91daff..5ef39b0 100644
--- a/Source/core/dom/MouseEvent.h
+++ b/Source/core/dom/MouseEvent.h
@@ -98,8 +98,6 @@
     virtual bool isDragEvent() const;
     virtual int which() const;
 
-    virtual PassRefPtr<Event> cloneFor(HTMLIFrameElement*) const OVERRIDE;
-
 protected:
     MouseEvent(const AtomicString& type, bool canBubble, bool cancelable, PassRefPtr<AbstractView>,
         int detail, int screenX, int screenY, int pageX, int pageY,
@@ -143,7 +141,7 @@
 
 inline MouseEvent* toMouseEvent(Event* event)
 {
-    ASSERT(event && event->isMouseEvent());
+    ASSERT_WITH_SECURITY_IMPLICATION(!event || event->isMouseEvent());
     return static_cast<MouseEvent*>(event);
 }
 
diff --git a/Source/core/dom/MutationObserver.h b/Source/core/dom/MutationObserver.h
index 643a4e9..eb0da18 100644
--- a/Source/core/dom/MutationObserver.h
+++ b/Source/core/dom/MutationObserver.h
@@ -32,13 +32,10 @@
 #define MutationObserver_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
-#include "wtf/text/AtomicString.h"
-#include "wtf/text/AtomicStringHash.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/MutationRecord.cpp b/Source/core/dom/MutationRecord.cpp
index cc3b05a..5d86f3e 100644
--- a/Source/core/dom/MutationRecord.cpp
+++ b/Source/core/dom/MutationRecord.cpp
@@ -36,8 +36,7 @@
 #include "core/dom/NodeList.h"
 #include "core/dom/QualifiedName.h"
 #include "core/dom/StaticNodeList.h"
-#include <wtf/Assertions.h>
-#include <wtf/StdLibExtras.h>
+#include "wtf/StdLibExtras.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/MutationRecord.h b/Source/core/dom/MutationRecord.h
index c5001c2..2c9812e 100644
--- a/Source/core/dom/MutationRecord.h
+++ b/Source/core/dom/MutationRecord.h
@@ -34,7 +34,6 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
-#include "wtf/RefPtr.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/NamedFlow.cpp b/Source/core/dom/NamedFlow.cpp
index 6f6d936..00519a1 100644
--- a/Source/core/dom/NamedFlow.cpp
+++ b/Source/core/dom/NamedFlow.cpp
@@ -33,7 +33,6 @@
 #include "RuntimeEnabledFeatures.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/NamedFlowCollection.h"
-#include "core/dom/ScriptExecutionContext.h"
 #include "core/dom/StaticNodeList.h"
 #include "core/dom/UIEvent.h"
 #include "core/rendering/RenderNamedFlowThread.h"
@@ -104,7 +103,7 @@
     RenderRegionList::const_iterator iter = regionList.begin();
     for (int index = 0; iter != regionList.end(); ++index, ++iter) {
         const RenderRegion* renderRegion = *iter;
-        if (renderRegion->regionState() == RenderRegion::RegionEmpty)
+        if (renderRegion->regionOversetState() == RegionEmpty)
             return index;
     }
     return -1;
@@ -218,6 +217,19 @@
     dispatchEvent(event);
 }
 
+void NamedFlow::dispatchRegionOversetChangeEvent()
+{
+    ASSERT(!NoEventDispatchAssertion::isEventDispatchForbidden());
+
+    // If the flow is in the "NULL" state the event should not be dispatched any more.
+    if (flowState() == FlowStateNull)
+        return;
+
+    RefPtr<Event> event = UIEvent::create(eventNames().webkitregionoversetchangeEvent, false, false, m_flowManager->document()->defaultView(), 0);
+
+    dispatchEvent(event);
+}
+
 const AtomicString& NamedFlow::interfaceName() const
 {
     return eventNames().interfaceForNamedFlow;
diff --git a/Source/core/dom/NamedFlow.h b/Source/core/dom/NamedFlow.h
index 060a3ff..13306cc 100644
--- a/Source/core/dom/NamedFlow.h
+++ b/Source/core/dom/NamedFlow.h
@@ -32,7 +32,6 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/EventTarget.h"
-#include "wtf/ListHashSet.h"
 #include "wtf/RefCounted.h"
 #include "wtf/RefPtr.h"
 #include "wtf/text/AtomicString.h"
@@ -79,6 +78,7 @@
     FlowState flowState() const { return m_parentFlowThread ? FlowStateCreated : FlowStateNull; }
 
     void dispatchRegionLayoutUpdateEvent();
+    void dispatchRegionOversetChangeEvent();
 
 private:
     NamedFlow(PassRefPtr<NamedFlowCollection>, const AtomicString&);
diff --git a/Source/core/dom/NamedFlowCollection.cpp b/Source/core/dom/NamedFlowCollection.cpp
index ea88831..8672d6d 100644
--- a/Source/core/dom/NamedFlowCollection.cpp
+++ b/Source/core/dom/NamedFlowCollection.cpp
@@ -42,7 +42,7 @@
 namespace WebCore {
 
 NamedFlowCollection::NamedFlowCollection(Document* document)
-    : ContextDestructionObserver(document)
+    : ContextLifecycleObserver(document)
 {
     ASSERT(RuntimeEnabledFeatures::cssRegionsEnabled());
 }
@@ -104,7 +104,7 @@
 
 Document* NamedFlowCollection::document() const
 {
-    ScriptExecutionContext* context = ContextDestructionObserver::scriptExecutionContext();
+    ScriptExecutionContext* context = ContextLifecycleObserver::scriptExecutionContext();
     return toDocument(context);
 }
 
diff --git a/Source/core/dom/NamedFlowCollection.h b/Source/core/dom/NamedFlowCollection.h
index ef163b8..47107e0 100644
--- a/Source/core/dom/NamedFlowCollection.h
+++ b/Source/core/dom/NamedFlowCollection.h
@@ -30,7 +30,7 @@
 #ifndef NamedFlowCollection_h
 #define NamedFlowCollection_h
 
-#include "core/dom/ContextDestructionObserver.h"
+#include "core/dom/ContextLifecycleObserver.h"
 #include "core/dom/NamedFlow.h"
 #include <wtf/Forward.h>
 #include <wtf/ListHashSet.h>
@@ -43,7 +43,7 @@
 class Document;
 class DOMNamedFlowCollection;
 
-class NamedFlowCollection : public RefCounted<NamedFlowCollection>, public ContextDestructionObserver {
+class NamedFlowCollection : public RefCounted<NamedFlowCollection>, public ContextLifecycleObserver {
 public:
     static PassRefPtr<NamedFlowCollection> create(Document* doc) { return adoptRef(new NamedFlowCollection(doc)); }
 
diff --git a/Source/core/dom/NamedNodeMap.cpp b/Source/core/dom/NamedNodeMap.cpp
index 5e054e7..05f194f 100644
--- a/Source/core/dom/NamedNodeMap.cpp
+++ b/Source/core/dom/NamedNodeMap.cpp
@@ -92,7 +92,7 @@
         return 0;
     }
 
-    return m_element->setAttributeNode(static_cast<Attr*>(node), ec);
+    return m_element->setAttributeNode(toAttr(node), ec);
 }
 
 PassRefPtr<Node> NamedNodeMap::setNamedItemNS(Node* node, ExceptionCode& ec)
diff --git a/Source/core/dom/NamedNodesCollection.cpp b/Source/core/dom/NamedNodesCollection.cpp
index 51fac3c..9112f03 100644
--- a/Source/core/dom/NamedNodesCollection.cpp
+++ b/Source/core/dom/NamedNodesCollection.cpp
@@ -31,7 +31,6 @@
 #include "core/dom/NamedNodesCollection.h"
 
 #include "core/dom/Element.h"
-#include "core/dom/NamedNodeMap.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/Node.cpp b/Source/core/dom/Node.cpp
index 730d4eb..3f107e9 100644
--- a/Source/core/dom/Node.cpp
+++ b/Source/core/dom/Node.cpp
@@ -28,19 +28,12 @@
 #include "HTMLNames.h"
 #include "XMLNames.h"
 #include "core/accessibility/AXObjectCache.h"
-#include "core/css/CSSParser.h"
-#include "core/css/CSSRule.h"
-#include "core/css/CSSSelector.h"
-#include "core/css/CSSSelectorList.h"
-#include "core/css/CSSStyleRule.h"
-#include "core/css/CSSStyleSheet.h"
 #include "core/dom/Attr.h"
 #include "core/dom/Attribute.h"
 #include "core/dom/BeforeLoadEvent.h"
 #include "core/dom/ChildListMutationScope.h"
 #include "core/dom/ChildNodeList.h"
 #include "core/dom/ClassNodeList.h"
-#include "core/dom/ContainerNodeAlgorithms.h"
 #include "core/dom/DOMImplementation.h"
 #include "core/dom/Document.h"
 #include "core/dom/DocumentFragment.h"
@@ -48,7 +41,6 @@
 #include "core/dom/Element.h"
 #include "core/dom/ElementRareData.h"
 #include "core/dom/Event.h"
-#include "core/dom/EventContext.h"
 #include "core/dom/EventDispatchMediator.h"
 #include "core/dom/EventDispatcher.h"
 #include "core/dom/EventListener.h"
@@ -62,16 +54,11 @@
 #include "core/dom/MouseEvent.h"
 #include "core/dom/MutationEvent.h"
 #include "core/dom/NameNodeList.h"
-#include "core/dom/NamedNodeMap.h"
 #include "core/dom/NodeRareData.h"
 #include "core/dom/NodeRenderingContext.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/ProcessingInstruction.h"
-#include "core/dom/ProgressEvent.h"
-#include "core/dom/RegisteredEventListener.h"
-#include "core/dom/ScopedEventQueue.h"
 #include "core/dom/SelectorQuery.h"
-#include "core/dom/StaticNodeList.h"
 #include "core/dom/TagNodeList.h"
 #include "core/dom/TemplateContentDocumentFragment.h"
 #include "core/dom/Text.h"
@@ -79,40 +66,25 @@
 #include "core/dom/TouchEvent.h"
 #include "core/dom/TreeScopeAdopter.h"
 #include "core/dom/UIEvent.h"
-#include "core/dom/UIEventWithKeyState.h"
 #include "core/dom/UserActionElementSet.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/dom/WheelEvent.h"
-#include "core/dom/WindowEventContext.h"
 #include "core/dom/shadow/ElementShadow.h"
-#include "core/dom/shadow/InsertionPoint.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/htmlediting.h"
-#include "core/html/DOMSettableTokenList.h"
-#include "core/html/HTMLElement.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/html/HTMLStyleElement.h"
-#include "core/html/LabelsNodeList.h"
 #include "core/html/RadioNodeList.h"
 #include "core/inspector/InspectorCounters.h"
-#include "core/page/Chrome.h"
-#include "core/page/ChromeClient.h"
 #include "core/page/ContextMenuController.h"
 #include "core/page/EventHandler.h"
 #include "core/page/Frame.h"
-#include "core/page/FrameView.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
-#include "core/platform/Logging.h"
-#include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/PlatformWheelEvent.h"
-#include "core/rendering/RenderBlock.h"
+#include "core/platform/Partitions.h"
+#include "core/rendering/FlowThreadController.h"
 #include "core/rendering/RenderBox.h"
-#include "core/rendering/RenderTextControl.h"
-#include "core/rendering/RenderView.h"
-#include "core/storage/StorageEvent.h"
 #include "wtf/HashSet.h"
-#include "wtf/PartitionAlloc.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/RefCountedLeakCounter.h"
 #include "wtf/UnusedParam.h"
@@ -120,10 +92,6 @@
 #include "wtf/text/CString.h"
 #include "wtf/text/StringBuilder.h"
 
-#ifndef NDEBUG
-#include "core/rendering/RenderLayer.h"
-#endif
-
 using namespace std;
 
 namespace WebCore {
@@ -131,11 +99,9 @@
 using namespace HTMLNames;
 
 #if ENABLE(PARTITION_ALLOC)
-static PartitionRoot root;
-
 void* Node::operator new(size_t size)
 {
-    return partitionAlloc(&root, size);
+    return partitionAlloc(Partitions::getObjectModelPartition(), size);
 }
 
 void Node::operator delete(void* ptr)
@@ -144,20 +110,6 @@
 }
 #endif // ENABLE(PARTITION_ALLOC)
 
-void Node::init()
-{
-#if ENABLE(PARTITION_ALLOC)
-    partitionAllocInit(&root);
-#endif
-}
-
-void Node::shutdown()
-{
-#if ENABLE(PARTITION_ALLOC)
-    partitionAllocShutdown(&root);
-#endif
-}
-
 bool Node::isSupported(const String& feature, const String& version)
 {
     return DOMImplementation::hasFeature(feature, version);
@@ -875,6 +827,12 @@
     if (!attached()) // changed compared to what?
         return;
 
+    // FIXME: Switch all callers to use setNeedsLayerUpdate and get rid of SyntheticStyleChange.
+    if (changeType == SyntheticStyleChange) {
+        setNeedsLayerUpdate();
+        return;
+    }
+
     StyleChangeType existingChangeType = styleChangeType();
     if (changeType > existingChangeType)
         setStyleChange(changeType);
@@ -883,6 +841,12 @@
         markAncestorsWithChildNeedsStyleRecalc();
 }
 
+void Node::setNeedsLayerUpdate()
+{
+    setFlag(NeedsLayerUpdate);
+    setNeedsStyleRecalc(InlineStyleChange);
+}
+
 void Node::lazyAttach(ShouldSetAttached shouldSetAttached)
 {
     // It's safe to synchronously attach here because we're in the middle of style recalc
@@ -912,7 +876,8 @@
 {
     if (!inDocument() || !supportsFocus())
         return false;
-
+    if (isElementNode() && toElement(this)->isInert())
+        return false;
     return rendererIsFocusable();
 }
 
@@ -931,6 +896,12 @@
     return this;
 }
 
+bool Node::shouldHaveFocusAppearance() const
+{
+    ASSERT(focused());
+    return true;
+}
+
 unsigned Node::nodeIndex() const
 {
     Node *_tempNode = previousSibling();
@@ -1035,8 +1006,10 @@
     // Return true if other is an ancestor of this, otherwise false
     if (!other || !other->hasChildNodes() || inDocument() != other->inDocument())
         return false;
-    if (other->isDocumentNode())
-        return document() == other && !isDocumentNode() && inDocument() && !isInShadowTree();
+    if (other->treeScope() != treeScope())
+        return false;
+    if (other->isTreeScope())
+        return !isTreeScope();
     for (const ContainerNode* n = parentNode(); n; n = n->parentNode()) {
         if (n == other)
             return true;
@@ -1233,6 +1206,11 @@
     return parentOrShadowHostNode() ? parentOrShadowHostNode()->canStartSelection() : true;
 }
 
+bool Node::isRegisteredWithNamedFlow() const
+{
+    return document()->renderView()->flowThreadController()->isContentNodeRegisteredWithAnyNamedFlow(this);
+}
+
 Element* Node::shadowHost() const
 {
     if (ShadowRoot* root = containingShadowRoot())
@@ -1515,7 +1493,7 @@
         case DOCUMENT_FRAGMENT_NODE:
             return false;
         case ATTRIBUTE_NODE: {
-            const Attr* attr = static_cast<const Attr*>(this);
+            const Attr* attr = toAttr(this);
             if (attr->ownerElement())
                 return attr->ownerElement()->isDefaultNamespace(namespaceURI);
             return false;
@@ -1537,7 +1515,7 @@
     
     switch (nodeType()) {
         case ELEMENT_NODE:
-            return lookupNamespacePrefix(namespaceURI, static_cast<const Element *>(this));
+            return lookupNamespacePrefix(namespaceURI, toElement(this));
         case DOCUMENT_NODE:
             if (Element* de = toDocument(this)->documentElement())
                 return de->lookupPrefix(namespaceURI);
@@ -1570,7 +1548,7 @@
     
     switch (nodeType()) {
         case ELEMENT_NODE: {
-            const Element *elem = static_cast<const Element *>(this);
+            const Element *elem = toElement(this);
             
             if (!elem->namespaceURI().isNull() && elem->prefix() == prefix)
                 return elem->namespaceURI();
@@ -1753,8 +1731,8 @@
     if (otherNode == this)
         return DOCUMENT_POSITION_EQUIVALENT;
     
-    const Attr* attr1 = nodeType() == ATTRIBUTE_NODE ? static_cast<const Attr*>(this) : 0;
-    const Attr* attr2 = otherNode->nodeType() == ATTRIBUTE_NODE ? static_cast<const Attr*>(otherNode) : 0;
+    const Attr* attr1 = nodeType() == ATTRIBUTE_NODE ? toAttr(this) : 0;
+    const Attr* attr2 = otherNode->nodeType() == ATTRIBUTE_NODE ? toAttr(otherNode) : 0;
     
     const Node* start1 = attr1 ? attr1->ownerElement() : this;
     const Node* start2 = attr2 ? attr2->ownerElement() : otherNode;
@@ -1910,11 +1888,10 @@
 
     if (hasClass()) {
         name.appendLiteral(" class=\'");
-        const StyledElement* styledElement = static_cast<const StyledElement*>(this);
-        for (size_t i = 0; i < styledElement->classNames().size(); ++i) {
+        for (size_t i = 0; i < toElement(this)->classNames().size(); ++i) {
             if (i > 0)
                 name.append(' ');
-            name.append(styledElement->classNames()[i]);
+            name.append(toElement(this)->classNames()[i]);
         }
         name.append('\'');
     }
@@ -2511,9 +2488,10 @@
         return;
     const AtomicString& eventType = event->type();
     if (eventType == eventNames().keydownEvent || eventType == eventNames().keypressEvent) {
-        if (event->isKeyboardEvent())
+        if (event->isKeyboardEvent()) {
             if (Frame* frame = document()->frame())
-                frame->eventHandler()->defaultKeyboardEventHandler(static_cast<KeyboardEvent*>(event));
+                frame->eventHandler()->defaultKeyboardEventHandler(toKeyboardEvent(event));
+        }
     } else if (eventType == eventNames().clickEvent) {
         int detail = event->isUIEvent() ? static_cast<UIEvent*>(event)->detail() : 0;
         if (dispatchDOMActivateEvent(detail, event))
@@ -2528,7 +2506,7 @@
                 frame->eventHandler()->defaultTextInputEventHandler(static_cast<TextEvent*>(event));
 #if ENABLE(PAN_SCROLLING)
     } else if (eventType == eventNames().mousedownEvent && event->isMouseEvent()) {
-        MouseEvent* mouseEvent = static_cast<MouseEvent*>(event);
+        MouseEvent* mouseEvent = toMouseEvent(event);
         if (mouseEvent->button() == MiddleButton) {
             if (enclosingLinkEventParentOrSelf())
                 return;
@@ -2560,6 +2538,10 @@
     }
 }
 
+void Node::willCallDefaultEventHandler(const Event&)
+{
+}
+
 bool Node::willRespondToMouseMoveEvents()
 {
     if (isDisabledFormControl(this))
@@ -2701,7 +2683,7 @@
 {
     size_t count = 0;
     for (Node* child = firstChild(); child; child = child->nextSibling()) {
-        if (child->hasTagName(HTMLNames::styleTag) && static_cast<HTMLStyleElement*>(child)->isRegisteredAsScoped())
+        if (child->hasTagName(HTMLNames::styleTag) && toHTMLStyleElement(child)->isRegisteredAsScoped())
             count++;
     }
 
diff --git a/Source/core/dom/Node.h b/Source/core/dom/Node.h
index 87c486b..6df001f 100644
--- a/Source/core/dom/Node.h
+++ b/Source/core/dom/Node.h
@@ -75,7 +75,6 @@
 class QualifiedName;
 class RadioNodeList;
 class RegisteredEventListener;
-class RenderArena;
 class RenderBox;
 class RenderBoxModelObject;
 class RenderObject;
@@ -88,14 +87,13 @@
 
 const int nodeStyleChangeShift = 15;
 
-// SyntheticStyleChange means that we need to go through the entire style change logic even though
-// no style property has actually changed. It is used to restructure the tree when, for instance,
-// RenderLayers are created or destroyed due to animation changes.
 enum StyleChangeType {
     NoStyleChange = 0,
     InlineStyleChange = 1 << nodeStyleChangeShift,
-    SyntheticStyleChange = 2 << nodeStyleChangeShift,
-    FullStyleChange = 3 << nodeStyleChangeShift,
+    FullStyleChange = 2 << nodeStyleChangeShift,
+
+    // FIXME: SyntheticStyleChange is deprecated, instead you should use setNeedsLayerUpdate().
+    SyntheticStyleChange = 3 << nodeStyleChangeShift,
 };
 
 class NodeRareDataBase {
@@ -156,8 +154,6 @@
         DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC = 0x20,
     };
 
-    static void init();
-    static void shutdown();
 #if ENABLE(PARTITION_ALLOC)
     // All Nodes are placed in their own heap partition for security.
     // See http://crbug.com/246860 for detail.
@@ -273,6 +269,8 @@
     bool inNamedFlow() const { return getFlag(InNamedFlowFlag); }
     bool hasCustomStyleCallbacks() const { return getFlag(HasCustomStyleCallbacksFlag); }
 
+    bool isRegisteredWithNamedFlow() const;
+
     bool hasSyntheticAttrChildNodes() const { return getFlag(HasSyntheticAttrChildNodesFlag); }
     void setHasSyntheticAttrChildNodes(bool flag) { setFlag(flag, HasSyntheticAttrChildNodesFlag); }
 
@@ -376,7 +374,14 @@
     void clearChildNeedsStyleRecalc() { clearFlag(ChildNeedsStyleRecalcFlag); }
 
     void setNeedsStyleRecalc(StyleChangeType changeType = FullStyleChange);
-    void clearNeedsStyleRecalc() { m_nodeFlags &= ~StyleChangeMask; }
+    void clearNeedsStyleRecalc()
+    {
+        m_nodeFlags &= ~StyleChangeMask;
+        clearFlag(NeedsLayerUpdate);
+    }
+
+    void setNeedsLayerUpdate();
+    bool needsLayerUpdate() const { return getFlag(NeedsLayerUpdate); }
 
     void setIsLink(bool f) { setFlag(f, IsLinkFlag); }
     void setIsLink() { setFlag(IsLinkFlag); }
@@ -417,6 +422,8 @@
     virtual bool isKeyboardFocusable(KeyboardEvent*) const;
     virtual bool isMouseFocusable() const;
     virtual Node* focusDelegate();
+    // This is called only when the node is focused.
+    virtual bool shouldHaveFocusAppearance() const;
 
     enum UserSelectAllTreatment {
         UserSelectAllDoesNotAffectEditability,
@@ -670,6 +677,7 @@
 
     // Perform the default action for an event.
     virtual void defaultEventHandler(Event*);
+    virtual void willCallDefaultEventHandler(const Event&);
 
     using TreeShared<Node>::ref;
     using TreeShared<Node>::deref;
@@ -735,10 +743,12 @@
         IsInShadowTreeFlag = 1 << 26,
         IsCustomElement = 1 << 27,
 
+        NeedsLayerUpdate = 1 << 28,
+
         DefaultNodeFlags = IsParsingChildrenFinishedFlag
     };
 
-    // 4 bits remaining
+    // 3 bits remaining
 
     bool getFlag(NodeFlags mask) const { return m_nodeFlags & mask; }
     void setFlag(bool f, NodeFlags mask) const { m_nodeFlags = (m_nodeFlags & ~mask) | (-(int32_t)f & mask); } 
@@ -914,8 +924,11 @@
 
 inline void Node::lazyReattach(ShouldSetAttached shouldSetAttached)
 {
+    AttachContext context;
+    context.performingReattach = true;
+
     if (attached())
-        detach();
+        detach(context);
     lazyAttach(shouldSetAttached);
 }
 
diff --git a/Source/core/dom/NodeRareData.cpp b/Source/core/dom/NodeRareData.cpp
index 2aec8fa..e11eb42 100644
--- a/Source/core/dom/NodeRareData.cpp
+++ b/Source/core/dom/NodeRareData.cpp
@@ -32,9 +32,7 @@
 #include "core/dom/NodeRareData.h"
 
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/MemoryInstrumentationHashSet.h>
-#include <wtf/MemoryInstrumentationVector.h>
+#include "wtf/MemoryInstrumentationHashMap.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/NodeRareData.h b/Source/core/dom/NodeRareData.h
index f20b19a..7da5008 100644
--- a/Source/core/dom/NodeRareData.h
+++ b/Source/core/dom/NodeRareData.h
@@ -22,21 +22,17 @@
 #ifndef NodeRareData_h
 #define NodeRareData_h
 
-#include "HTMLNames.h"
 #include "core/dom/ChildNodeList.h"
 #include "core/dom/LiveNodeList.h"
-#include "core/dom/MutationObserver.h"
 #include "core/dom/MutationObserverRegistration.h"
 #include "core/dom/QualifiedName.h"
 #include "core/dom/TagNodeList.h"
-#include "core/html/DOMSettableTokenList.h"
-#include "core/html/track/TextTrack.h"
 #include "core/page/Page.h"
-#include <wtf/HashSet.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/text/AtomicString.h>
-#include <wtf/text/StringHash.h>
+#include "wtf/HashSet.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/text/AtomicString.h"
+#include "wtf/text/StringHash.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/NodeRenderingContext.cpp b/Source/core/dom/NodeRenderingContext.cpp
index 856fc6f..8ea7f81 100644
--- a/Source/core/dom/NodeRenderingContext.cpp
+++ b/Source/core/dom/NodeRenderingContext.cpp
@@ -26,19 +26,12 @@
 #include "config.h"
 #include "core/dom/NodeRenderingContext.h"
 
-#include "HTMLNames.h"
 #include "SVGNames.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/ContainerNode.h"
 #include "core/dom/FullscreenController.h"
 #include "core/dom/Node.h"
-#include "core/dom/PseudoElement.h"
 #include "core/dom/Text.h"
-#include "core/dom/shadow/ContentDistributor.h"
-#include "core/dom/shadow/ElementShadow.h"
-#include "core/dom/shadow/ShadowRoot.h"
-#include "core/html/HTMLInputElement.h"
-#include "core/html/shadow/HTMLContentElement.h"
 #include "core/html/shadow/HTMLShadowElement.h"
 #include "core/rendering/FlowThreadController.h"
 #include "core/rendering/RenderFullScreen.h"
@@ -46,12 +39,9 @@
 #include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderText.h"
 #include "core/rendering/RenderView.h"
-#include "core/rendering/style/StyleInheritedData.h"
 
 namespace WebCore {
 
-using namespace HTMLNames;
-
 NodeRenderingContext::NodeRenderingContext(Node* node)
     : m_node(node)
     , m_parentFlowRenderer(0)
@@ -184,6 +174,7 @@
 {
     if (!m_renderingParent)
         return false;
+
     RenderObject* parentRenderer = this->parentRenderer();
     if (!parentRenderer)
         return false;
@@ -194,37 +185,41 @@
     return true;
 }
 
+// Check the specific case of elements that are children of regions but are flowed into a flow thread themselves.
+bool NodeRenderingContext::elementInsideRegionNeedsRenderer()
+{
+    Element* element = toElement(m_node);
+    bool elementInsideRegionNeedsRenderer = false;
+    RenderObject* parentRenderer = this->parentRenderer();
+    if ((parentRenderer && !parentRenderer->canHaveChildren() && parentRenderer->isRenderRegion())
+        || (!parentRenderer && element->parentElement() && element->parentElement()->isInsideRegion())) {
+
+        if (!m_style)
+            m_style = element->styleForRenderer();
+
+        elementInsideRegionNeedsRenderer = element->shouldMoveToFlowThread(m_style.get());
+
+        // Children of this element will only be allowed to be flowed into other flow-threads if display is NOT none.
+        if (element->rendererIsNeeded(*this))
+            element->setIsInsideRegion(true);
+    }
+
+    return elementInsideRegionNeedsRenderer;
+}
+
 void NodeRenderingContext::moveToFlowThreadIfNeeded()
 {
-    ASSERT(m_node->isElementNode());
-    ASSERT(m_style);
     if (!RuntimeEnabledFeatures::cssRegionsEnabled())
         return;
 
-    if (m_style->flowThread().isEmpty())
+    Element* element = toElement(m_node);
+
+    if (!element->shouldMoveToFlowThread(m_style.get()))
         return;
 
-    // As per http://dev.w3.org/csswg/css3-regions/#flow-into, pseudo-elements such as ::first-line, ::first-letter, ::before or ::after
-    // cannot be directly collected into a named flow.
-    if (m_node->isPseudoElement())
-        return;
-
-    // FIXME: Do not collect elements if they are in shadow tree.
-    if (m_node->isInShadowTree())
-        return;
-
-    if (m_node->isElementNode() && FullscreenController::isActiveFullScreenElement(toElement(m_node)))
-        return;
-
-    // Allow only svg root elements to be directly collected by a render flow thread.
-    if (m_node->isSVGElement()
-        && (!(m_node->hasTagName(SVGNames::svgTag) && m_node->parentNode() && !m_node->parentNode()->isSVGElement())))
-        return;
-
-    m_flowThread = m_style->flowThread();
     ASSERT(m_node->document()->renderView());
     FlowThreadController* flowThreadController = m_node->document()->renderView()->flowThreadController();
-    m_parentFlowRenderer = flowThreadController->ensureRenderFlowThreadWithName(m_flowThread);
+    m_parentFlowRenderer = flowThreadController->ensureRenderFlowThreadWithName(m_style->flowThread());
     flowThreadController->registerNamedFlowContentNode(m_node, m_parentFlowRenderer);
 }
 
@@ -244,9 +239,13 @@
 
     Element* element = toElement(m_node);
 
-    if (!shouldCreateRenderer())
+    element->setIsInsideRegion(false);
+
+    if (!shouldCreateRenderer() && !elementInsideRegionNeedsRenderer())
         return;
-    m_style = element->styleForRenderer();
+
+    if (!m_style)
+        m_style = element->styleForRenderer();
     ASSERT(m_style);
 
     moveToFlowThreadIfNeeded();
@@ -258,7 +257,7 @@
     RenderObject* nextRenderer = this->nextRenderer();
 
     Document* document = element->document();
-    RenderObject* newRenderer = element->createRenderer(document->renderArena(), m_style.get());
+    RenderObject* newRenderer = element->createRenderer(m_style.get());
     if (!newRenderer)
         return;
 
@@ -304,7 +303,7 @@
 
     if (!textNode->textRendererIsNeeded(*this))
         return;
-    RenderText* newRenderer = textNode->createTextRenderer(document->renderArena(), m_style.get());
+    RenderText* newRenderer = textNode->createTextRenderer(m_style.get());
     if (!newRenderer)
         return;
     if (!parentRenderer->isChildAllowed(newRenderer, m_style.get())) {
diff --git a/Source/core/dom/NodeRenderingContext.h b/Source/core/dom/NodeRenderingContext.h
index c0e0c9d..3bacbf4 100644
--- a/Source/core/dom/NodeRenderingContext.h
+++ b/Source/core/dom/NodeRenderingContext.h
@@ -28,9 +28,8 @@
 
 #include "core/dom/NodeRenderingTraversal.h"
 
-#include <wtf/Noncopyable.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/AtomicString.h>
+#include "wtf/RefPtr.h"
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
@@ -69,6 +68,7 @@
 private:
     bool shouldCreateRenderer() const;
     void moveToFlowThreadIfNeeded();
+    bool elementInsideRegionNeedsRenderer();
 
     Node* m_node;
     ContainerNode* m_renderingParent;
diff --git a/Source/core/dom/NodeRenderingTraversal.cpp b/Source/core/dom/NodeRenderingTraversal.cpp
index a04d763..482b8ad 100644
--- a/Source/core/dom/NodeRenderingTraversal.cpp
+++ b/Source/core/dom/NodeRenderingTraversal.cpp
@@ -49,9 +49,8 @@
 
 ContainerNode* parent(const Node* node, ParentDetails* details)
 {
-    if (ShadowRoot* root = node->containingShadowRoot())
-        root->host()->ensureDistribution();
-
+    // FIXME(morrita): We should ensure shadow tree distribution to be valid here through ContentDistributor::ensureDistribution().
+    // Currently we rely on the caller side since doing it here is expensive.
     ComposedShadowTreeWalker walker(node, ComposedShadowTreeWalker::CrossUpperBoundary, ComposedShadowTreeWalker::CanStartFromShadowBoundary);
     ContainerNode* found = toContainerNode(walker.traverseParent(walker.get(), details));
     return details->outOfComposition() ? 0 : found;
diff --git a/Source/core/dom/ParentNode.idl b/Source/core/dom/ParentNode.idl
index fef5c3b..10b418e 100644
--- a/Source/core/dom/ParentNode.idl
+++ b/Source/core/dom/ParentNode.idl
@@ -7,6 +7,3 @@
     [PerWorldBindings] readonly attribute unsigned long childElementCount;
 };
 
-Document implements ParentNode;
-DocumentFragment implements ParentNode;
-Element implements ParentNode;
diff --git a/Source/core/dom/FragmentScriptingPermission.h b/Source/core/dom/ParserContentPolicy.h
similarity index 96%
rename from Source/core/dom/FragmentScriptingPermission.h
rename to Source/core/dom/ParserContentPolicy.h
index 21b3552..5d3ecd4 100644
--- a/Source/core/dom/FragmentScriptingPermission.h
+++ b/Source/core/dom/ParserContentPolicy.h
@@ -23,8 +23,6 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-// FIXME: Move this file to ParserContentPolicy.h.
-
 #ifndef ParserContentPolicy_h
 #define ParserContentPolicy_h
 
@@ -37,7 +35,7 @@
     AllowScriptingContentAndDoNotMarkAlreadyStarted,
 };
 
-static inline bool scriptingContentIsAllowed(ParserContentPolicy parserContentPolicy) 
+static inline bool scriptingContentIsAllowed(ParserContentPolicy parserContentPolicy)
 {
     return parserContentPolicy == AllowScriptingContent || parserContentPolicy == AllowScriptingContentAndDoNotMarkAlreadyStarted;
 }
diff --git a/Source/core/dom/Position.cpp b/Source/core/dom/Position.cpp
index 21f5080..627bfa1 100644
--- a/Source/core/dom/Position.cpp
+++ b/Source/core/dom/Position.cpp
@@ -35,15 +35,14 @@
 #include "core/editing/VisiblePosition.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
-#include "RuntimeEnabledFeatures.h"
 #include "core/platform/Logging.h"
 #include "core/rendering/InlineIterator.h"
 #include "core/rendering/InlineTextBox.h"
 #include "core/rendering/RenderBlock.h"
 #include "core/rendering/RenderInline.h"
 #include "core/rendering/RenderText.h"
-#include <wtf/text/CString.h>
-#include <wtf/unicode/CharacterNames.h>
+#include "wtf/text/CString.h"
+#include "wtf/unicode/CharacterNames.h"
 
 namespace WebCore {
 
@@ -843,7 +842,7 @@
 
 bool Position::nodeIsUserSelectNone(Node* node)
 {
-    return node && node->renderer() && node->renderer()->style()->userSelect() == SELECT_NONE;
+    return node && node->renderer() && node->renderer()->style()->userSelect() == SELECT_NONE && node->renderer()->style()->userModify() == READ_ONLY;
 }
 
 ContainerNode* Position::findParent(const Node* node)
diff --git a/Source/core/workers/WorkerContextProxy.cpp b/Source/core/dom/Promise.h
similarity index 83%
copy from Source/core/workers/WorkerContextProxy.cpp
copy to Source/core/dom/Promise.h
index 7f0ff2e..2c842aa 100644
--- a/Source/core/workers/WorkerContextProxy.cpp
+++ b/Source/core/dom/Promise.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,11 +28,19 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/workers/WorkerContextProxy.h"
+// FIXME: This file should be deleted.
+#ifndef Promise_h
+#define Promise_h
+
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
-WorkerContextProxy::CreateDelegate* WorkerContextProxy::s_createDelegate = 0;
+// An empty class. This is here because a generated file use it.
+class Promise : public RefCounted<Promise> {
+};
 
 } // namespace WebCore
+
+
+#endif // Promise_h
diff --git a/Source/core/workers/SharedWorkerContext.idl b/Source/core/dom/Promise.idl
similarity index 86%
copy from Source/core/workers/SharedWorkerContext.idl
copy to Source/core/dom/Promise.idl
index 52fc0a2..893b8ee 100644
--- a/Source/core/workers/SharedWorkerContext.idl
+++ b/Source/core/dom/Promise.idl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -29,9 +29,7 @@
  */
 
 [
-    NoInterfaceObject
-] interface SharedWorkerContext : WorkerContext {
-    readonly attribute DOMString name;
-             attribute EventListener onconnect;
+   CustomConstructor(any init),
+   EnabledAtRuntime=promise
+] interface Promise {
 };
-
diff --git a/Source/core/workers/WorkerContextProxy.cpp b/Source/core/dom/PromiseResolver.h
similarity index 81%
copy from Source/core/workers/WorkerContextProxy.cpp
copy to Source/core/dom/PromiseResolver.h
index 7f0ff2e..664018a 100644
--- a/Source/core/workers/WorkerContextProxy.cpp
+++ b/Source/core/dom/PromiseResolver.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,11 +28,19 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/workers/WorkerContextProxy.h"
+// FIXME: This file should be deleted.
+#ifndef PromiseResolver_h
+#define PromiseResolver_h
+
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
-WorkerContextProxy::CreateDelegate* WorkerContextProxy::s_createDelegate = 0;
+// An empty class. This is here because a generated file use it.
+class PromiseResolver : public RefCounted<PromiseResolver> {
+};
 
 } // namespace WebCore
+
+
+#endif // PromiseResolver_h
diff --git a/Source/core/workers/SharedWorkerContext.idl b/Source/core/dom/PromiseResolver.idl
similarity index 85%
copy from Source/core/workers/SharedWorkerContext.idl
copy to Source/core/dom/PromiseResolver.idl
index 52fc0a2..f2c80b4 100644
--- a/Source/core/workers/SharedWorkerContext.idl
+++ b/Source/core/dom/PromiseResolver.idl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -29,9 +29,9 @@
  */
 
 [
-    NoInterfaceObject
-] interface SharedWorkerContext : WorkerContext {
-    readonly attribute DOMString name;
-             attribute EventListener onconnect;
+   EnabledAtRuntime=promise
+] interface PromiseResolver {
+   [Custom] void fulfill(optional any value);
+   [Custom] void resolve(optional any value);
+   [Custom] void reject(optional any value);
 };
-
diff --git a/Source/core/dom/PseudoElement.h b/Source/core/dom/PseudoElement.h
index a5d7018..0575704 100644
--- a/Source/core/dom/PseudoElement.h
+++ b/Source/core/dom/PseudoElement.h
@@ -28,9 +28,8 @@
 #define PseudoElement_h
 
 #include "core/dom/Element.h"
-#include "core/dom/Event.h"
 #include "core/rendering/style/RenderStyle.h"
-#include <wtf/Forward.h>
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
@@ -46,6 +45,10 @@
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
 
+    // As per http://dev.w3.org/csswg/css3-regions/#flow-into, pseudo-elements such as ::first-line, ::first-letter, ::before or ::after
+    // cannot be directly collected into a named flow.
+    virtual bool shouldMoveToFlowThread(RenderStyle*) const OVERRIDE { return false; }
+
     virtual bool canStartSelection() const OVERRIDE { return false; }
     virtual bool canContainRangeEndPoint() const OVERRIDE { return false; }
 
diff --git a/Source/core/dom/QualifiedName.cpp b/Source/core/dom/QualifiedName.cpp
index c7f59fb..6edcf87 100644
--- a/Source/core/dom/QualifiedName.cpp
+++ b/Source/core/dom/QualifiedName.cpp
@@ -72,7 +72,7 @@
     if (!gNameCache)
         gNameCache = new QNameSet;
     QualifiedNameComponents components = { p.impl(), l.impl(), n.isEmpty() ? nullAtom.impl() : n.impl() };
-    QNameSet::AddResult addResult = gNameCache->add<QualifiedNameComponents, QNameComponentsTranslator>(components);
+    QNameSet::AddResult addResult = gNameCache->add<QNameComponentsTranslator>(components);
     m_impl = *addResult.iterator;
     if (!addResult.isNewEntry)
         m_impl->ref();
diff --git a/Source/core/dom/Range.cpp b/Source/core/dom/Range.cpp
index 7817efd..15a10d0 100644
--- a/Source/core/dom/Range.cpp
+++ b/Source/core/dom/Range.cpp
@@ -693,9 +693,13 @@
         return fragment;
     }
 
+    // Since mutation observers can modify the range during the process, the boundary points need to be saved.
+    RangeBoundaryPoint originalStart(m_start);
+    RangeBoundaryPoint originalEnd(m_end);
+
     // what is the highest node that partially selects the start / end of the range?
-    RefPtr<Node> partialStart = highestAncestorUnderCommonRoot(m_start.container(), commonRoot.get());
-    RefPtr<Node> partialEnd = highestAncestorUnderCommonRoot(m_end.container(), commonRoot.get());
+    RefPtr<Node> partialStart = highestAncestorUnderCommonRoot(originalStart.container(), commonRoot.get());
+    RefPtr<Node> partialEnd = highestAncestorUnderCommonRoot(originalEnd.container(), commonRoot.get());
 
     // Start and end containers are different.
     // There are three possibilities here:
@@ -718,22 +722,22 @@
     // after any DOM mutation event, at various stages below. See webkit bug 60350.
 
     RefPtr<Node> leftContents;
-    if (m_start.container() != commonRoot && commonRoot->contains(m_start.container())) {
-        leftContents = processContentsBetweenOffsets(action, 0, m_start.container(), m_start.offset(), lengthOfContentsInNode(m_start.container()), ec);
-        leftContents = processAncestorsAndTheirSiblings(action, m_start.container(), ProcessContentsForward, leftContents, commonRoot.get(), ec);
+    if (originalStart.container() != commonRoot && commonRoot->contains(originalStart.container())) {
+        leftContents = processContentsBetweenOffsets(action, 0, originalStart.container(), originalStart.offset(), lengthOfContentsInNode(originalStart.container()), ec);
+        leftContents = processAncestorsAndTheirSiblings(action, originalStart.container(), ProcessContentsForward, leftContents, commonRoot.get(), ec);
     }
 
     RefPtr<Node> rightContents;
-    if (m_end.container() != commonRoot && commonRoot->contains(m_end.container())) {
-        rightContents = processContentsBetweenOffsets(action, 0, m_end.container(), 0, m_end.offset(), ec);
-        rightContents = processAncestorsAndTheirSiblings(action, m_end.container(), ProcessContentsBackward, rightContents, commonRoot.get(), ec);
+    if (m_end.container() != commonRoot && commonRoot->contains(originalEnd.container())) {
+        rightContents = processContentsBetweenOffsets(action, 0, originalEnd.container(), 0, originalEnd.offset(), ec);
+        rightContents = processAncestorsAndTheirSiblings(action, originalEnd.container(), ProcessContentsBackward, rightContents, commonRoot.get(), ec);
     }
 
     // delete all children of commonRoot between the start and end container
-    RefPtr<Node> processStart = childOfCommonRootBeforeOffset(m_start.container(), m_start.offset(), commonRoot.get());
-    if (processStart && m_start.container() != commonRoot) // processStart contains nodes before m_start.
+    RefPtr<Node> processStart = childOfCommonRootBeforeOffset(originalStart.container(), originalStart.offset(), commonRoot.get());
+    if (processStart && originalStart.container() != commonRoot) // processStart contains nodes before m_start.
         processStart = processStart->nextSibling();
-    RefPtr<Node> processEnd = childOfCommonRootBeforeOffset(m_end.container(), m_end.offset(), commonRoot.get());
+    RefPtr<Node> processEnd = childOfCommonRootBeforeOffset(originalEnd.container(), originalEnd.offset(), commonRoot.get());
 
     // Collapse the range, making sure that the result is not within a node that was partially selected.
     if (action == EXTRACT_CONTENTS || action == DELETE_CONTENTS) {
@@ -746,6 +750,9 @@
         m_end = m_start;
     }
 
+    originalStart.clear();
+    originalEnd.clear();
+
     // Now add leftContents, stuff in between, and rightContents to the fragment
     // (or just delete the stuff in between)
 
@@ -1062,7 +1069,7 @@
             int length = data.length();
             int start = (n == m_start.container()) ? min(max(0, m_start.offset()), length) : 0;
             int end = (n == m_end.container()) ? min(max(start, m_end.offset()), length) : length;
-            builder.append(data.characters() + start, end - start);
+            builder.append(data, start, end - start);
         }
     }
 
diff --git a/Source/core/dom/Range.h b/Source/core/dom/Range.h
index 0df40c2..dea17c6 100644
--- a/Source/core/dom/Range.h
+++ b/Source/core/dom/Range.h
@@ -27,13 +27,12 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/ExceptionCodePlaceholder.h"
-#include "core/dom/FragmentScriptingPermission.h"
 #include "core/dom/RangeBoundaryPoint.h"
 #include "core/platform/graphics/FloatRect.h"
 #include "core/platform/graphics/IntRect.h"
-#include <wtf/Forward.h>
-#include <wtf/RefCounted.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/RangeBoundaryPoint.h b/Source/core/dom/RangeBoundaryPoint.h
index e868452..77c025d 100644
--- a/Source/core/dom/RangeBoundaryPoint.h
+++ b/Source/core/dom/RangeBoundaryPoint.h
@@ -35,6 +35,8 @@
 public:
     explicit RangeBoundaryPoint(PassRefPtr<Node> container);
 
+    explicit RangeBoundaryPoint(const RangeBoundaryPoint&);
+
     const Position toPosition() const;
 
     Node* container() const;
@@ -56,7 +58,7 @@
 
 private:
     static const int invalidOffset = -1;
-    
+
     RefPtr<Node> m_containerNode;
     mutable int m_offsetInContainer;
     RefPtr<Node> m_childBeforeBoundary;
@@ -70,6 +72,13 @@
     ASSERT(m_containerNode);
 }
 
+inline RangeBoundaryPoint::RangeBoundaryPoint(const RangeBoundaryPoint& other)
+    : m_containerNode(other.container())
+    , m_offsetInContainer(other.offset())
+    , m_childBeforeBoundary(other.childBefore())
+{
+}
+
 inline Node* RangeBoundaryPoint::container() const
 {
     return m_containerNode.get();
diff --git a/Source/core/dom/RawDataDocumentParser.h b/Source/core/dom/RawDataDocumentParser.h
index 47d9952..b56a694 100644
--- a/Source/core/dom/RawDataDocumentParser.h
+++ b/Source/core/dom/RawDataDocumentParser.h
@@ -26,6 +26,7 @@
 #ifndef RawDataDocumentParser_h
 #define RawDataDocumentParser_h
 
+#include "core/dom/Document.h"
 #include "core/dom/DocumentParser.h"
 
 namespace WebCore {
@@ -44,10 +45,11 @@
     }
 
 private:
-    virtual void flush(DocumentWriter* writer)
+    virtual size_t flush() OVERRIDE
     {
         // Make sure appendBytes is called at least once.
-        appendBytes(writer, 0, 0);
+        appendBytes(0, 0);
+        return 0;
     }
 
     virtual void insert(const SegmentedString&)
diff --git a/Source/core/dom/ScriptElement.cpp b/Source/core/dom/ScriptElement.cpp
index d80a9c8..94018c1 100644
--- a/Source/core/dom/ScriptElement.cpp
+++ b/Source/core/dom/ScriptElement.cpp
@@ -36,7 +36,6 @@
 #include "core/dom/Text.h"
 #include "core/html/HTMLScriptElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/CrossOriginAccessControl.h"
 #include "core/loader/cache/CachedResourceLoader.h"
 #include "core/loader/cache/CachedResourceRequest.h"
 #include "core/loader/cache/CachedScript.h"
@@ -65,7 +64,6 @@
     , m_willExecuteWhenDocumentFinishedParsing(false)
     , m_forceAsync(!parserInserted)
     , m_willExecuteInOrder(false)
-    , m_requestUsesAccessControl(false)
 {
     ASSERT(m_element);
     if (parserInserted && m_element->document()->scriptableDocumentParser() && !m_element->document()->isInDocumentWrite())
@@ -253,9 +251,8 @@
 
         String crossOriginMode = m_element->fastGetAttribute(HTMLNames::crossoriginAttr);
         if (!crossOriginMode.isNull()) {
-            m_requestUsesAccessControl = true;
             StoredCredentials allowCredentials = equalIgnoringCase(crossOriginMode, "use-credentials") ? AllowStoredCredentials : DoNotAllowStoredCredentials;
-            updateRequestForAccessControl(request.mutableResourceRequest(), m_element->document()->securityOrigin(), allowCredentials);
+            request.setPotentiallyCrossOriginEnabled(m_element->document()->securityOrigin(), allowCredentials);
         }
         request.setCharset(scriptCharset());
 
@@ -358,14 +355,8 @@
     ASSERT_UNUSED(resource, resource == m_cachedScript);
     if (!m_cachedScript)
         return;
-
-    String error;
-    if (m_requestUsesAccessControl
-        && !m_element->document()->securityOrigin()->canRequest(m_cachedScript->response().url())
-        && !m_cachedScript->passesAccessControlCheck(m_element->document()->securityOrigin(), error)) {
-
+    if (!m_element->document()->cachedResourceLoader()->canAccess(m_cachedScript.get())) {
         dispatchErrorEvent();
-        m_element->document()->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Script from origin '" + SecurityOrigin::create(m_cachedScript->response().url())->toString() + "' has been blocked from loading by Cross-Origin Resource Sharing policy: " + error);
         return;
     }
 
@@ -400,31 +391,7 @@
 
 String ScriptElement::scriptContent() const
 {
-    StringBuilder content;
-    Text* firstTextNode = 0;
-    bool foundMultipleTextNodes = false;
-
-    for (Node* n = m_element->firstChild(); n; n = n->nextSibling()) {
-        if (!n->isTextNode())
-            continue;
-
-        Text* t = toText(n);
-        if (foundMultipleTextNodes)
-            content.append(t->data());
-        else if (firstTextNode) {
-            content.append(firstTextNode->data());
-            content.append(t->data());
-            foundMultipleTextNodes = true;
-        } else
-            firstTextNode = t;
-    }
-
-    if (firstTextNode && !foundMultipleTextNodes) {
-        firstTextNode->atomize();
-        return firstTextNode->data();
-    }
-
-    return content.toString();
+    return m_element->textFromChildren();
 }
 
 ScriptElement* toScriptElementIfPossible(Element* element)
diff --git a/Source/core/dom/ScriptElement.h b/Source/core/dom/ScriptElement.h
index 7f9869e..32a011d 100644
--- a/Source/core/dom/ScriptElement.h
+++ b/Source/core/dom/ScriptElement.h
@@ -103,7 +103,6 @@
     bool m_willExecuteWhenDocumentFinishedParsing : 1;
     bool m_forceAsync : 1;
     bool m_willExecuteInOrder : 1;
-    bool m_requestUsesAccessControl : 1;
     String m_characterEncoding;
     String m_fallbackCharacterEncoding;
 };
diff --git a/Source/core/dom/ScriptExecutionContext.cpp b/Source/core/dom/ScriptExecutionContext.cpp
index 2f621cd..f8d343e 100644
--- a/Source/core/dom/ScriptExecutionContext.cpp
+++ b/Source/core/dom/ScriptExecutionContext.cpp
@@ -28,6 +28,7 @@
 #include "config.h"
 #include "core/dom/ScriptExecutionContext.h"
 
+#include "core/dom/ContextLifecycleNotifier.h"
 #include "core/dom/ErrorEvent.h"
 #include "core/dom/EventTarget.h"
 #include "core/dom/MessagePort.h"
@@ -36,16 +37,17 @@
 #include "core/inspector/ScriptCallStack.h"
 #include "core/loader/cache/CachedScript.h"
 #include "core/page/DOMTimer.h"
-#include "core/workers/WorkerContext.h"
+#include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerThread.h"
 #include "modules/webdatabase/DatabaseContext.h"
-#include <wtf/MainThread.h>
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/MemoryInstrumentationVector.h>
+#include "wtf/MainThread.h"
+#include "wtf/MemoryInstrumentationHashMap.h"
+#include "wtf/MemoryInstrumentationHashSet.h"
+#include "wtf/MemoryInstrumentationVector.h"
 
 namespace WTF {
 
-template<> struct SequenceMemoryInstrumentationTraits<WebCore::ContextDestructionObserver*> {
+template<> struct SequenceMemoryInstrumentationTraits<WebCore::ContextLifecycleObserver*> {
     template <typename I> static void reportMemoryUsage(I, I, MemoryClassInfo&) { }
 };
 
@@ -87,9 +89,7 @@
 }
 
 ScriptExecutionContext::ScriptExecutionContext()
-    : m_iteratingActiveDOMObjects(false)
-    , m_inDestructor(false)
-    , m_circularSequentialID(0)
+    : m_circularSequentialID(0)
     , m_inDispatchErrorEvent(false)
     , m_activeDOMObjectsAreSuspended(false)
     , m_reasonForSuspendingActiveDOMObjects(static_cast<ActiveDOMObject::ReasonForSuspension>(-1))
@@ -99,14 +99,6 @@
 
 ScriptExecutionContext::~ScriptExecutionContext()
 {
-    m_inDestructor = true;
-    for (HashSet<ContextDestructionObserver*>::iterator iter = m_destructionObservers.begin(); iter != m_destructionObservers.end(); iter = m_destructionObservers.begin()) {
-        ContextDestructionObserver* observer = *iter;
-        m_destructionObservers.remove(observer);
-        ASSERT(observer->scriptExecutionContext() == this);
-        observer->contextDestroyed();
-    }
-
     HashSet<MessagePort*>::iterator messagePortsEnd = m_messagePorts.end();
     for (HashSet<MessagePort*>::iterator iter = m_messagePorts.begin(); iter != messagePortsEnd; ++iter) {
         ASSERT((*iter)->scriptExecutionContext() == this);
@@ -141,7 +133,7 @@
 {
     ASSERT(port);
     ASSERT((isDocument() && isMainThread())
-        || (isWorkerContext() && static_cast<WorkerContext*>(this)->thread()->isCurrentThread()));
+        || (isWorkerGlobalScope() && toWorkerGlobalScope(this)->thread()->isCurrentThread()));
 
     m_messagePorts.add(port);
 }
@@ -150,39 +142,33 @@
 {
     ASSERT(port);
     ASSERT((isDocument() && isMainThread())
-        || (isWorkerContext() && static_cast<WorkerContext*>(this)->thread()->isCurrentThread()));
+        || (isWorkerGlobalScope() && toWorkerGlobalScope(this)->thread()->isCurrentThread()));
 
     m_messagePorts.remove(port);
 }
 
 bool ScriptExecutionContext::canSuspendActiveDOMObjects()
 {
-    // No protection against m_activeDOMObjects changing during iteration: canSuspend() shouldn't execute arbitrary JS.
-    m_iteratingActiveDOMObjects = true;
-    ActiveDOMObjectsSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
-    for (ActiveDOMObjectsSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
-        ASSERT((*iter)->scriptExecutionContext() == this);
-        ASSERT((*iter)->suspendIfNeededCalled());
-        if (!(*iter)->canSuspend()) {
-            m_iteratingActiveDOMObjects = false;
-            return false;
-        }
+    return lifecycleNotifier()->canSuspendActiveDOMObjects();
+}
+
+bool ScriptExecutionContext::hasPendingActivity()
+{
+    if (lifecycleNotifier()->hasPendingActivity())
+        return true;
+
+    HashSet<MessagePort*>::const_iterator messagePortsEnd = m_messagePorts.end();
+    for (HashSet<MessagePort*>::const_iterator iter = m_messagePorts.begin(); iter != messagePortsEnd; ++iter) {
+        if ((*iter)->hasPendingActivity())
+            return true;
     }
-    m_iteratingActiveDOMObjects = false;
-    return true;
+
+    return false;
 }
 
 void ScriptExecutionContext::suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension why)
 {
-    // No protection against m_activeDOMObjects changing during iteration: suspend() shouldn't execute arbitrary JS.
-    m_iteratingActiveDOMObjects = true;
-    ActiveDOMObjectsSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
-    for (ActiveDOMObjectsSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
-        ASSERT((*iter)->scriptExecutionContext() == this);
-        ASSERT((*iter)->suspendIfNeededCalled());
-        (*iter)->suspend(why);
-    }
-    m_iteratingActiveDOMObjects = false;
+    lifecycleNotifier()->notifySuspendingActiveDOMObjects(why);
     m_activeDOMObjectsAreSuspended = true;
     m_reasonForSuspendingActiveDOMObjects = why;
 }
@@ -190,70 +176,33 @@
 void ScriptExecutionContext::resumeActiveDOMObjects()
 {
     m_activeDOMObjectsAreSuspended = false;
-    // No protection against m_activeDOMObjects changing during iteration: resume() shouldn't execute arbitrary JS.
-    m_iteratingActiveDOMObjects = true;
-    ActiveDOMObjectsSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
-    for (ActiveDOMObjectsSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
-        ASSERT((*iter)->scriptExecutionContext() == this);
-        ASSERT((*iter)->suspendIfNeededCalled());
-        (*iter)->resume();
-    }
-    m_iteratingActiveDOMObjects = false;
+    lifecycleNotifier()->notifyResumingActiveDOMObjects();
 }
 
 void ScriptExecutionContext::stopActiveDOMObjects()
 {
     m_activeDOMObjectsAreStopped = true;
-    // No protection against m_activeDOMObjects changing during iteration: stop() shouldn't execute arbitrary JS.
-    m_iteratingActiveDOMObjects = true;
-    ActiveDOMObjectsSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
-    for (ActiveDOMObjectsSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter) {
-        ASSERT((*iter)->scriptExecutionContext() == this);
-        ASSERT((*iter)->suspendIfNeededCalled());
-        (*iter)->stop();
-    }
-    m_iteratingActiveDOMObjects = false;
-
+    lifecycleNotifier()->notifyStoppingActiveDOMObjects();
     // Also close MessagePorts. If they were ActiveDOMObjects (they could be) then they could be stopped instead.
     closeMessagePorts();
 }
 
 void ScriptExecutionContext::suspendActiveDOMObjectIfNeeded(ActiveDOMObject* object)
 {
-    ASSERT(m_activeDOMObjects.contains(object));
+    ASSERT(lifecycleNotifier()->contains(object));
     // Ensure all ActiveDOMObjects are suspended also newly created ones.
     if (m_activeDOMObjectsAreSuspended)
         object->suspend(m_reasonForSuspendingActiveDOMObjects);
 }
 
-void ScriptExecutionContext::didCreateActiveDOMObject(ActiveDOMObject* object)
+void ScriptExecutionContext::wasObservedBy(ContextLifecycleObserver* observer, ContextLifecycleObserver::Type as)
 {
-    ASSERT(object);
-    ASSERT(!m_inDestructor);
-    if (m_iteratingActiveDOMObjects)
-        CRASH();
-    m_activeDOMObjects.add(object);
+    lifecycleNotifier()->addObserver(observer, as);
 }
 
-void ScriptExecutionContext::willDestroyActiveDOMObject(ActiveDOMObject* object)
+void ScriptExecutionContext::wasUnobservedBy(ContextLifecycleObserver* observer, ContextLifecycleObserver::Type as)
 {
-    ASSERT(object);
-    if (m_iteratingActiveDOMObjects)
-        CRASH();
-    m_activeDOMObjects.remove(object);
-}
-
-void ScriptExecutionContext::didCreateDestructionObserver(ContextDestructionObserver* observer)
-{
-    ASSERT(observer);
-    ASSERT(!m_inDestructor);
-    m_destructionObservers.add(observer);
-}
-
-void ScriptExecutionContext::willDestroyDestructionObserver(ContextDestructionObserver* observer)
-{
-    ASSERT(observer);
-    m_destructionObservers.remove(observer);
+    lifecycleNotifier()->removeObserver(observer, as);
 }
 
 void ScriptExecutionContext::closeMessagePorts() {
@@ -350,19 +299,27 @@
     return DOMTimer::visiblePageAlignmentInterval();
 }
 
+ContextLifecycleNotifier* ScriptExecutionContext::lifecycleNotifier()
+{
+    if (!m_lifecycleNotifier)
+        m_lifecycleNotifier = const_cast<ScriptExecutionContext*>(this)->createLifecycleNotifier();
+    return m_lifecycleNotifier.get();
+}
+
+PassOwnPtr<ContextLifecycleNotifier> ScriptExecutionContext::createLifecycleNotifier()
+{
+    return ContextLifecycleNotifier::create(this);
+}
+
 void ScriptExecutionContext::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
 {
     MemoryClassInfo info(memoryObjectInfo, this, WebCoreMemoryTypes::DOM);
     SecurityContext::reportMemoryUsage(memoryObjectInfo);
     info.addMember(m_messagePorts, "messagePorts");
-    info.addMember(m_destructionObservers, "destructionObservers");
-    info.addMember(m_activeDOMObjects, "activeDOMObjects");
+    info.addMember(m_lifecycleNotifier, "lifecycleObserver");
     info.addMember(m_timeouts, "timeouts");
     info.addMember(m_pendingExceptions, "pendingExceptions");
     info.addMember(m_publicURLManager, "publicURLManager");
-    ActiveDOMObjectsSet::iterator activeObjectsEnd = m_activeDOMObjects.end();
-    for (ActiveDOMObjectsSet::iterator iter = m_activeDOMObjects.begin(); iter != activeObjectsEnd; ++iter)
-        info.addMember(*iter, "activeDOMObject", WTF::RetainingPointer);
 }
 
 ScriptExecutionContext::Task::~Task()
@@ -371,7 +328,6 @@
 
 void ScriptExecutionContext::setDatabaseContext(DatabaseContext* databaseContext)
 {
-    ASSERT(!m_databaseContext);
     m_databaseContext = databaseContext;
 }
 
diff --git a/Source/core/dom/ScriptExecutionContext.h b/Source/core/dom/ScriptExecutionContext.h
index af5e831..ea1759a 100644
--- a/Source/core/dom/ScriptExecutionContext.h
+++ b/Source/core/dom/ScriptExecutionContext.h
@@ -38,6 +38,7 @@
 namespace WebCore {
 
 class CachedScript;
+class ContextLifecycleNotifier;
 class DatabaseContext;
 class DOMTimer;
 class EventListener;
@@ -54,7 +55,7 @@
     virtual ~ScriptExecutionContext();
 
     virtual bool isDocument() const { return false; }
-    virtual bool isWorkerContext() const { return false; }
+    virtual bool isWorkerGlobalScope() const { return false; }
 
     virtual bool isContextThread() const { return true; }
     virtual bool isJSExecutionForbidden() const = 0;
@@ -78,6 +79,8 @@
 
     // Active objects are not garbage collected even if inaccessible, e.g. because their activity may result in callbacks being invoked.
     bool canSuspendActiveDOMObjects();
+    bool hasPendingActivity();
+
     // Active objects can be asked to suspend even if canSuspendActiveDOMObjects() returns 'false' -
     // step-by-step JS debugging is one example.
     virtual void suspendActiveDOMObjects(ActiveDOMObject::ReasonForSuspension);
@@ -87,18 +90,12 @@
     bool activeDOMObjectsAreSuspended() const { return m_activeDOMObjectsAreSuspended; }
     bool activeDOMObjectsAreStopped() const { return m_activeDOMObjectsAreStopped; }
 
-    // Called from the constructor and destructors of ActiveDOMObject.
-    void didCreateActiveDOMObject(ActiveDOMObject*);
-    void willDestroyActiveDOMObject(ActiveDOMObject*);
-
     // Called after the construction of an ActiveDOMObject to synchronize suspend state.
     void suspendActiveDOMObjectIfNeeded(ActiveDOMObject*);
 
-    typedef HashSet<ActiveDOMObject*> ActiveDOMObjectsSet;
-    const ActiveDOMObjectsSet& activeDOMObjects() const { return m_activeDOMObjects; }
-
-    void didCreateDestructionObserver(ContextDestructionObserver*);
-    void willDestroyDestructionObserver(ContextDestructionObserver*);
+    // Called from the constructor and destructors of ContextLifecycleObserver
+    void wasObservedBy(ContextLifecycleObserver*, ContextLifecycleObserver::Type as);
+    void wasUnobservedBy(ContextLifecycleObserver*, ContextLifecycleObserver::Type as);
 
     // MessagePort is conceptually a kind of ActiveDOMObject, but it needs to be tracked separately for message dispatch.
     void processMessagePortMessagesSoon();
@@ -159,6 +156,8 @@
         String m_message;
     };
 
+    ContextLifecycleNotifier* lifecycleNotifier();
+
 private:
     virtual const KURL& virtualURL() const = 0;
     virtual KURL virtualCompleteURL(const String&) const = 0;
@@ -172,12 +171,10 @@
 
     virtual void refScriptExecutionContext() = 0;
     virtual void derefScriptExecutionContext() = 0;
+    virtual PassOwnPtr<ContextLifecycleNotifier> createLifecycleNotifier();
 
+    OwnPtr<ContextLifecycleNotifier> m_lifecycleNotifier;
     HashSet<MessagePort*> m_messagePorts;
-    HashSet<ContextDestructionObserver*> m_destructionObservers;
-    ActiveDOMObjectsSet m_activeDOMObjects;
-    bool m_iteratingActiveDOMObjects;
-    bool m_inDestructor;
 
     int m_circularSequentialID;
     typedef HashMap<int, DOMTimer*> TimeoutMap;
diff --git a/Source/core/dom/ScriptRunner.h b/Source/core/dom/ScriptRunner.h
index c52bd89..1790764 100644
--- a/Source/core/dom/ScriptRunner.h
+++ b/Source/core/dom/ScriptRunner.h
@@ -28,11 +28,10 @@
 
 #include "core/loader/cache/CachedResourceHandle.h"
 #include "core/platform/Timer.h"
-#include <wtf/HashMap.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/HashMap.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/ScriptableDocumentParser.h b/Source/core/dom/ScriptableDocumentParser.h
index 9a8581d..f8a95ad 100644
--- a/Source/core/dom/ScriptableDocumentParser.h
+++ b/Source/core/dom/ScriptableDocumentParser.h
@@ -27,7 +27,7 @@
 #define ScriptableDocumentParser_h
 
 #include "core/dom/DecodedDataDocumentParser.h"
-#include "core/dom/FragmentScriptingPermission.h"
+#include "core/dom/ParserContentPolicy.h"
 #include <wtf/text/TextPosition.h>
 
 namespace WebCore {
diff --git a/Source/core/dom/ScriptedAnimationController.h b/Source/core/dom/ScriptedAnimationController.h
index 9737c89..4379b2a 100644
--- a/Source/core/dom/ScriptedAnimationController.h
+++ b/Source/core/dom/ScriptedAnimationController.h
@@ -26,10 +26,9 @@
 #ifndef ScriptedAnimationController_h
 #define ScriptedAnimationController_h
 
-#include "core/dom/DOMTimeStamp.h"
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/RefCounted.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/SecurityContext.cpp b/Source/core/dom/SecurityContext.cpp
index cfaeacd2..80fcaba 100644
--- a/Source/core/dom/SecurityContext.cpp
+++ b/Source/core/dom/SecurityContext.cpp
@@ -90,18 +90,17 @@
     // http://www.w3.org/TR/html5/the-iframe-element.html#attr-iframe-sandbox
     // Parse the unordered set of unique space-separated tokens.
     SandboxFlags flags = SandboxAll;
-    const UChar* characters = policy.characters();
     unsigned length = policy.length();
     unsigned start = 0;
     unsigned numberOfTokenErrors = 0;
     StringBuilder tokenErrors;
     while (true) {
-        while (start < length && isHTMLSpace(characters[start]))
+        while (start < length && isHTMLSpace(policy[start]))
             ++start;
         if (start >= length)
             break;
         unsigned end = start + 1;
-        while (end < length && !isHTMLSpace(characters[end]))
+        while (end < length && !isHTMLSpace(policy[end]))
             ++end;
 
         // Turn off the corresponding sandbox flag if it's set as "allowed".
diff --git a/Source/core/dom/SpaceSplitString.cpp b/Source/core/dom/SpaceSplitString.cpp
index 4af9a1c..29222d4 100644
--- a/Source/core/dom/SpaceSplitString.cpp
+++ b/Source/core/dom/SpaceSplitString.cpp
@@ -22,10 +22,9 @@
 #include "core/dom/SpaceSplitString.h"
 
 #include "core/html/parser/HTMLParserIdioms.h"
-#include <wtf/ASCIICType.h>
-#include <wtf/HashMap.h>
-#include <wtf/text/AtomicStringHash.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/ASCIICType.h"
+#include "wtf/HashMap.h"
+#include "wtf/text/AtomicStringHash.h"
 
 using namespace WTF;
 
diff --git a/Source/core/dom/StyleElement.cpp b/Source/core/dom/StyleElement.cpp
index 7093671..83f797b 100644
--- a/Source/core/dom/StyleElement.cpp
+++ b/Source/core/dom/StyleElement.cpp
@@ -34,13 +34,6 @@
 
 namespace WebCore {
 
-static bool isValidStyleChild(Node* node)
-{
-    ASSERT(node);
-    Node::NodeType nodeType = node->nodeType();
-    return nodeType == Node::TEXT_NODE || nodeType == Node::CDATA_SECTION_NODE;
-}
-
 static bool isCSS(Element* element, const AtomicString& type)
 {
     return type.isEmpty() || (element->isHTMLElement() ? equalIgnoringCase(type, "text/css") : (type == "text/css"));
@@ -111,33 +104,11 @@
     m_createdByParser = false;
 }
 
-void StyleElement::process(Element* e)
+void StyleElement::process(Element* element)
 {
-    if (!e || !e->inDocument())
+    if (!element || !element->inDocument())
         return;
-
-    unsigned resultLength = 0;
-    for (Node* c = e->firstChild(); c; c = c->nextSibling()) {
-        if (isValidStyleChild(c)) {
-            unsigned length = c->nodeValue().length();
-            if (length > std::numeric_limits<unsigned>::max() - resultLength) {
-                createSheet(e, "");
-                return;
-            }
-            resultLength += length;
-        }
-    }
-    StringBuilder sheetText;
-    sheetText.reserveCapacity(resultLength);
-
-    for (Node* c = e->firstChild(); c; c = c->nextSibling()) {
-        if (isValidStyleChild(c)) {
-            sheetText.append(c->nodeValue());
-        }
-    }
-    ASSERT(sheetText.length() == resultLength);
-
-    createSheet(e, sheetText.toString());
+    createSheet(element, element->textFromChildren());
 }
 
 void StyleElement::clearSheet()
diff --git a/Source/core/dom/StyledElement.cpp b/Source/core/dom/StyledElement.cpp
deleted file mode 100644
index f6ecb91..0000000
--- a/Source/core/dom/StyledElement.cpp
+++ /dev/null
@@ -1,391 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- *           (C) 1999 Antti Koivisto (koivisto@kde.org)
- *           (C) 2001 Peter Kelly (pmk@post.com)
- *           (C) 2001 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2004, 2005, 2006, 2008, 2010 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-#include "core/dom/StyledElement.h"
-
-#include "CSSPropertyNames.h"
-#include "CSSValueKeywords.h"
-#include "HTMLNames.h"
-#include "core/css/CSSImageValue.h"
-#include "core/css/CSSParser.h"
-#include "core/css/CSSStyleSheet.h"
-#include "core/css/CSSValuePool.h"
-#include "core/css/PropertySetCSSStyleDeclaration.h"
-#include "core/css/StylePropertySet.h"
-#include "core/css/resolver/StyleResolver.h"
-#include "core/dom/Attribute.h"
-#include "core/dom/Document.h"
-#include "core/dom/ScriptableDocumentParser.h"
-#include "core/html/ClassList.h"
-#include "core/html/DOMTokenList.h"
-#include "core/html/parser/HTMLParserIdioms.h"
-#include "core/page/ContentSecurityPolicy.h"
-#include "core/platform/graphics/Color.h"
-#include <wtf/HashFunctions.h>
-#include <wtf/text/TextPosition.h>
-
-using namespace std;
-
-namespace WebCore {
-
-COMPILE_ASSERT(sizeof(StyledElement) == sizeof(Element), styledelement_should_remain_same_size_as_element);
-
-using namespace HTMLNames;
-
-struct PresentationAttributeCacheKey {
-    PresentationAttributeCacheKey() : tagName(0) { }
-    AtomicStringImpl* tagName;
-    // Only the values need refcounting.
-    Vector<pair<AtomicStringImpl*, AtomicString>, 3> attributesAndValues;
-};
-
-struct PresentationAttributeCacheEntry {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    PresentationAttributeCacheKey key;
-    RefPtr<StylePropertySet> value;
-};
-
-typedef HashMap<unsigned, OwnPtr<PresentationAttributeCacheEntry>, AlreadyHashed> PresentationAttributeCache;
-    
-static bool operator!=(const PresentationAttributeCacheKey& a, const PresentationAttributeCacheKey& b)
-{
-    if (a.tagName != b.tagName)
-        return true;
-    return a.attributesAndValues != b.attributesAndValues;
-}
-
-static PresentationAttributeCache& presentationAttributeCache()
-{
-    DEFINE_STATIC_LOCAL(PresentationAttributeCache, cache, ());
-    return cache;
-}
-
-class PresentationAttributeCacheCleaner {
-    WTF_MAKE_NONCOPYABLE(PresentationAttributeCacheCleaner); WTF_MAKE_FAST_ALLOCATED;
-public:
-    PresentationAttributeCacheCleaner()
-        : m_hitCount(0)
-        , m_cleanTimer(this, &PresentationAttributeCacheCleaner::cleanCache)
-    {
-    }
-
-    void didHitPresentationAttributeCache()
-    {
-        if (presentationAttributeCache().size() < minimumPresentationAttributeCacheSizeForCleaning)
-            return;
-
-        m_hitCount++;
-
-        if (!m_cleanTimer.isActive())
-            m_cleanTimer.startOneShot(presentationAttributeCacheCleanTimeInSeconds);
-     }
-
-private:
-    static const unsigned presentationAttributeCacheCleanTimeInSeconds = 60;
-    static const int minimumPresentationAttributeCacheSizeForCleaning = 100;
-    static const unsigned minimumPresentationAttributeCacheHitCountPerMinute = (100 * presentationAttributeCacheCleanTimeInSeconds) / 60;
-
-    void cleanCache(Timer<PresentationAttributeCacheCleaner>* timer)
-    {
-        ASSERT_UNUSED(timer, timer == &m_cleanTimer);
-        unsigned hitCount = m_hitCount;
-        m_hitCount = 0;
-        if (hitCount > minimumPresentationAttributeCacheHitCountPerMinute)
-            return;
-        presentationAttributeCache().clear();
-    }
-
-    unsigned m_hitCount;
-    Timer<PresentationAttributeCacheCleaner> m_cleanTimer;
-};
-
-static PresentationAttributeCacheCleaner& presentationAttributeCacheCleaner()
-{
-    DEFINE_STATIC_LOCAL(PresentationAttributeCacheCleaner, cleaner, ());
-    return cleaner;
-}
-
-void StyledElement::synchronizeStyleAttributeInternal() const
-{
-    ASSERT(elementData());
-    ASSERT(elementData()->m_styleAttributeIsDirty);
-    elementData()->m_styleAttributeIsDirty = false;
-    if (const StylePropertySet* inlineStyle = this->inlineStyle())
-        const_cast<StyledElement*>(this)->setSynchronizedLazyAttribute(styleAttr, inlineStyle->asText());
-}
-
-StyledElement::~StyledElement()
-{
-    if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
-        cssomWrapper->clearParentElement();
-}
-
-CSSStyleDeclaration* StyledElement::style()
-{
-    return ensureMutableInlineStyle()->ensureInlineCSSStyleDeclaration(this);
-}
-
-MutableStylePropertySet* StyledElement::ensureMutableInlineStyle()
-{
-    RefPtr<StylePropertySet>& inlineStyle = ensureUniqueElementData()->m_inlineStyle;
-    if (!inlineStyle)
-        inlineStyle = MutableStylePropertySet::create(strictToCSSParserMode(isHTMLElement() && !document()->inQuirksMode()));
-    else if (!inlineStyle->isMutable())
-        inlineStyle = inlineStyle->mutableCopy();
-    ASSERT(inlineStyle->isMutable());
-    return static_cast<MutableStylePropertySet*>(inlineStyle.get());
-}
-
-void StyledElement::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason reason)
-{
-    if (name == styleAttr)
-        styleAttributeChanged(newValue, reason);
-    else if (isPresentationAttribute(name)) {
-        elementData()->m_presentationAttributeStyleIsDirty = true;
-        setNeedsStyleRecalc(InlineStyleChange);
-    }
-
-    Element::attributeChanged(name, newValue, reason);
-}
-
-PropertySetCSSStyleDeclaration* StyledElement::inlineStyleCSSOMWrapper()
-{
-    if (!inlineStyle() || !inlineStyle()->hasCSSOMWrapper())
-        return 0;
-    PropertySetCSSStyleDeclaration* cssomWrapper = ensureMutableInlineStyle()->cssStyleDeclaration();
-    ASSERT(cssomWrapper && cssomWrapper->parentElement() == this);
-    return cssomWrapper;
-}
-
-inline void StyledElement::setInlineStyleFromString(const AtomicString& newStyleString)
-{
-    RefPtr<StylePropertySet>& inlineStyle = elementData()->m_inlineStyle;
-
-    // Avoid redundant work if we're using shared attribute data with already parsed inline style.
-    if (inlineStyle && !elementData()->isUnique())
-        return;
-
-    // We reconstruct the property set instead of mutating if there is no CSSOM wrapper.
-    // This makes wrapperless property sets immutable and so cacheable.
-    if (inlineStyle && !inlineStyle->isMutable())
-        inlineStyle.clear();
-
-    if (!inlineStyle)
-        inlineStyle = CSSParser::parseInlineStyleDeclaration(newStyleString, this);
-    else {
-        ASSERT(inlineStyle->isMutable());
-        static_pointer_cast<MutableStylePropertySet>(inlineStyle)->parseDeclaration(newStyleString, document()->elementSheet()->contents());
-    }
-}
-
-void StyledElement::styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason modificationReason)
-{
-    WTF::OrdinalNumber startLineNumber = WTF::OrdinalNumber::beforeFirst();
-    if (document() && document()->scriptableDocumentParser() && !document()->isInDocumentWrite())
-        startLineNumber = document()->scriptableDocumentParser()->lineNumber();
-
-    if (newStyleString.isNull()) {
-        if (PropertySetCSSStyleDeclaration* cssomWrapper = inlineStyleCSSOMWrapper())
-            cssomWrapper->clearParentElement();
-        ensureUniqueElementData()->m_inlineStyle.clear();
-    } else if (modificationReason == ModifiedByCloning || document()->contentSecurityPolicy()->allowInlineStyle(document()->url(), startLineNumber))
-        setInlineStyleFromString(newStyleString);
-
-    elementData()->m_styleAttributeIsDirty = false;
-
-    setNeedsStyleRecalc(InlineStyleChange);
-    InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
-}
-
-void StyledElement::inlineStyleChanged()
-{
-    setNeedsStyleRecalc(InlineStyleChange);
-    ASSERT(elementData());
-    elementData()->m_styleAttributeIsDirty = true;
-    InspectorInstrumentation::didInvalidateStyleAttr(document(), this);
-}
-    
-bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, CSSValueID identifier, bool important)
-{
-    ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
-    inlineStyleChanged();
-    return true;
-}
-
-bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, CSSPropertyID identifier, bool important)
-{
-    ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier), important);
-    inlineStyleChanged();
-    return true;
-}
-
-bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit, bool important)
-{
-    ensureMutableInlineStyle()->setProperty(propertyID, cssValuePool().createValue(value, unit), important);
-    inlineStyleChanged();
-    return true;
-}
-
-bool StyledElement::setInlineStyleProperty(CSSPropertyID propertyID, const String& value, bool important)
-{
-    bool changes = ensureMutableInlineStyle()->setProperty(propertyID, value, important, document()->elementSheet()->contents());
-    if (changes)
-        inlineStyleChanged();
-    return changes;
-}
-
-bool StyledElement::removeInlineStyleProperty(CSSPropertyID propertyID)
-{
-    if (!inlineStyle())
-        return false;
-    bool changes = ensureMutableInlineStyle()->removeProperty(propertyID);
-    if (changes)
-        inlineStyleChanged();
-    return changes;
-}
-
-void StyledElement::removeAllInlineStyleProperties()
-{
-    if (!inlineStyle() || inlineStyle()->isEmpty())
-        return;
-    ensureMutableInlineStyle()->clear();
-    inlineStyleChanged();
-}
-
-void StyledElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
-{
-    if (const StylePropertySet* inlineStyle = elementData() ? elementData()->inlineStyle() : 0)
-        inlineStyle->addSubresourceStyleURLs(urls, document()->elementSheet()->contents());
-}
-
-static inline bool attributeNameSort(const pair<AtomicStringImpl*, AtomicString>& p1, const pair<AtomicStringImpl*, AtomicString>& p2)
-{
-    // Sort based on the attribute name pointers. It doesn't matter what the order is as long as it is always the same. 
-    return p1.first < p2.first;
-}
-
-void StyledElement::makePresentationAttributeCacheKey(PresentationAttributeCacheKey& result) const
-{    
-    // FIXME: Enable for SVG.
-    if (namespaceURI() != xhtmlNamespaceURI)
-        return;
-    // Interpretation of the size attributes on <input> depends on the type attribute.
-    if (hasTagName(inputTag))
-        return;
-    unsigned size = attributeCount();
-    for (unsigned i = 0; i < size; ++i) {
-        const Attribute* attribute = attributeItem(i);
-        if (!isPresentationAttribute(attribute->name()))
-            continue;
-        if (!attribute->namespaceURI().isNull())
-            return;
-        // FIXME: Background URL may depend on the base URL and can't be shared. Disallow caching.
-        if (attribute->name() == backgroundAttr)
-            return;
-        result.attributesAndValues.append(make_pair(attribute->localName().impl(), attribute->value()));
-    }
-    if (result.attributesAndValues.isEmpty())
-        return;
-    // Attribute order doesn't matter. Sort for easy equality comparison.
-    std::sort(result.attributesAndValues.begin(), result.attributesAndValues.end(), attributeNameSort);
-    // The cache key is non-null when the tagName is set.
-    result.tagName = localName().impl();
-}
-
-static unsigned computePresentationAttributeCacheHash(const PresentationAttributeCacheKey& key)
-{
-    if (!key.tagName)
-        return 0;
-    ASSERT(key.attributesAndValues.size());
-    unsigned attributeHash = StringHasher::hashMemory(key.attributesAndValues.data(), key.attributesAndValues.size() * sizeof(key.attributesAndValues[0]));
-    return WTF::pairIntHash(key.tagName->existingHash(), attributeHash);
-}
-
-void StyledElement::rebuildPresentationAttributeStyle()
-{
-    PresentationAttributeCacheKey cacheKey;
-    makePresentationAttributeCacheKey(cacheKey);
-
-    unsigned cacheHash = computePresentationAttributeCacheHash(cacheKey);
-
-    PresentationAttributeCache::iterator cacheIterator;
-    if (cacheHash) {
-        cacheIterator = presentationAttributeCache().add(cacheHash, nullptr).iterator;
-        if (cacheIterator->value && cacheIterator->value->key != cacheKey)
-            cacheHash = 0;
-    } else
-        cacheIterator = presentationAttributeCache().end();
-
-    RefPtr<StylePropertySet> style;
-    if (cacheHash && cacheIterator->value) {
-        style = cacheIterator->value->value;
-        presentationAttributeCacheCleaner().didHitPresentationAttributeCache();
-    } else {
-        style = MutableStylePropertySet::create(isSVGElement() ? SVGAttributeMode : CSSQuirksMode);
-        unsigned size = attributeCount();
-        for (unsigned i = 0; i < size; ++i) {
-            const Attribute* attribute = attributeItem(i);
-            collectStyleForPresentationAttribute(attribute->name(), attribute->value(), static_cast<MutableStylePropertySet*>(style.get()));
-        }
-    }
-
-    // ShareableElementData doesn't store presentation attribute style, so make sure we have a UniqueElementData.
-    UniqueElementData* elementData = ensureUniqueElementData();
-
-    elementData->m_presentationAttributeStyleIsDirty = false;
-    elementData->m_presentationAttributeStyle = style->isEmpty() ? 0 : style;
-
-    if (!cacheHash || cacheIterator->value)
-        return;
-
-    OwnPtr<PresentationAttributeCacheEntry> newEntry = adoptPtr(new PresentationAttributeCacheEntry);
-    newEntry->key = cacheKey;
-    newEntry->value = style.release();
-
-    static const int presentationAttributeCacheMaximumSize = 4096;
-    if (presentationAttributeCache().size() > presentationAttributeCacheMaximumSize) {
-        // Start building from scratch if the cache ever gets big.
-        presentationAttributeCache().clear();
-        presentationAttributeCache().set(cacheHash, newEntry.release());
-    } else
-        cacheIterator->value = newEntry.release();
-}
-
-void StyledElement::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, CSSValueID identifier)
-{
-    style->setProperty(propertyID, cssValuePool().createIdentifierValue(identifier));
-}
-
-void StyledElement::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, double value, CSSPrimitiveValue::UnitTypes unit)
-{
-    style->setProperty(propertyID, cssValuePool().createValue(value, unit));
-}
-    
-void StyledElement::addPropertyToPresentationAttributeStyle(MutableStylePropertySet* style, CSSPropertyID propertyID, const String& value)
-{
-    style->setProperty(propertyID, value, false, document()->elementSheet()->contents());
-}
-
-}
diff --git a/Source/core/dom/StyledElement.h b/Source/core/dom/StyledElement.h
deleted file mode 100644
index a93efe2..0000000
--- a/Source/core/dom/StyledElement.h
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright (C) 1999 Lars Knoll (knoll@kde.org)
- *           (C) 1999 Antti Koivisto (koivisto@kde.org)
- *           (C) 2001 Peter Kelly (pmk@post.com)
- *           (C) 2001 Dirk Mueller (mueller@kde.org)
- * Copyright (C) 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- *
- */
-
-#ifndef StyledElement_h
-#define StyledElement_h
-
-#include "CSSPropertyNames.h"
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/dom/Element.h"
-
-namespace WebCore {
-
-class Attribute;
-class MutableStylePropertySet;
-class PropertySetCSSStyleDeclaration;
-class StylePropertySet;
-
-struct PresentationAttributeCacheKey;
-
-class StyledElement : public Element {
-public:
-    virtual ~StyledElement();
-
-    virtual const StylePropertySet* additionalPresentationAttributeStyle() { return 0; }
-    void invalidateStyleAttribute();
-
-    const StylePropertySet* inlineStyle() const { return elementData() ? elementData()->m_inlineStyle.get() : 0; }
-    
-    bool setInlineStyleProperty(CSSPropertyID, CSSValueID identifier, bool important = false);
-    bool setInlineStyleProperty(CSSPropertyID, CSSPropertyID identifier, bool important = false);
-    bool setInlineStyleProperty(CSSPropertyID, double value, CSSPrimitiveValue::UnitTypes, bool important = false);
-    bool setInlineStyleProperty(CSSPropertyID, const String& value, bool important = false);
-    bool removeInlineStyleProperty(CSSPropertyID);
-    void removeAllInlineStyleProperties();
-
-    void synchronizeStyleAttributeInternal() const;
-    
-    virtual CSSStyleDeclaration* style() OVERRIDE;
-
-    const StylePropertySet* presentationAttributeStyle();
-    virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) { }
-
-protected:
-    StyledElement(const QualifiedName& name, Document* document, ConstructionType type)
-        : Element(name, document, type)
-    {
-    }
-
-    virtual void attributeChanged(const QualifiedName&, const AtomicString&, AttributeModificationReason = ModifiedDirectly) OVERRIDE;
-
-    virtual bool isPresentationAttribute(const QualifiedName&) const { return false; }
-
-    void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, CSSValueID identifier);
-    void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, double value, CSSPrimitiveValue::UnitTypes);
-    void addPropertyToPresentationAttributeStyle(MutableStylePropertySet*, CSSPropertyID, const String& value);
-
-    virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
-
-private:
-    void styleAttributeChanged(const AtomicString& newStyleString, AttributeModificationReason);
-
-    void inlineStyleChanged();
-    PropertySetCSSStyleDeclaration* inlineStyleCSSOMWrapper();
-    void setInlineStyleFromString(const AtomicString&);
-    MutableStylePropertySet* ensureMutableInlineStyle();
-
-    void makePresentationAttributeCacheKey(PresentationAttributeCacheKey&) const;
-    void rebuildPresentationAttributeStyle();
-};
-
-inline void StyledElement::invalidateStyleAttribute()
-{
-    ASSERT(elementData());
-    elementData()->m_styleAttributeIsDirty = true;
-}
-
-inline const StylePropertySet* StyledElement::presentationAttributeStyle()
-{
-    if (!elementData())
-        return 0;
-    if (elementData()->m_presentationAttributeStyleIsDirty)
-        rebuildPresentationAttributeStyle();
-    return elementData()->presentationAttributeStyle();
-}
-
-} //namespace
-
-#endif
diff --git a/Source/core/dom/Text.cpp b/Source/core/dom/Text.cpp
index f5d58a3..c36409b 100644
--- a/Source/core/dom/Text.cpp
+++ b/Source/core/dom/Text.cpp
@@ -211,7 +211,8 @@
         return true;
 
     RenderObject* parent = context.parentRenderer();
-    if (parent->isTable() || parent->isTableRow() || parent->isTableSection() || parent->isRenderTableCol() || parent->isFrameSet())
+    if (parent->isTable() || parent->isTableRow() || parent->isTableSection() || parent->isRenderTableCol() || parent->isFrameSet()
+        || parent->isFlexibleBox() || parent->isRenderGrid())
         return false;
     
     if (context.style()->preserveNewline()) // pre/pre-wrap/pre-line always make renderers.
@@ -259,15 +260,15 @@
     NodeRenderingContext(this).createRendererForTextIfNeeded();
 }
 
-RenderText* Text::createTextRenderer(RenderArena* arena, RenderStyle* style)
+RenderText* Text::createTextRenderer(RenderStyle* style)
 {
     if (isSVGText(this) || isSVGShadowText(this))
-        return new (arena) RenderSVGInlineText(this, dataImpl());
+        return new (document()->renderArena()) RenderSVGInlineText(this, dataImpl());
 
     if (style->hasTextCombine())
-        return new (arena) RenderCombineText(this, dataImpl());
+        return new (document()->renderArena()) RenderCombineText(this, dataImpl());
 
-    return new (arena) RenderText(this, dataImpl());
+    return new (document()->renderArena()) RenderText(this, dataImpl());
 }
 
 void Text::attach(const AttachContext& context)
@@ -280,18 +281,13 @@
 {
     RenderText* renderer = toRenderText(this->renderer());
 
-    if (!renderer) {
+    if (renderer) {
+        if (change != NoChange || needsStyleRecalc())
+            renderer->setStyle(document()->styleResolver()->styleForText(this));
         if (needsStyleRecalc())
-            reattach();
-        clearNeedsStyleRecalc();
-        return;
-    }
-
-    if (needsStyleRecalc()) {
-        renderer->setStyle(document()->styleResolver()->styleForText(this));
-        renderer->setText(dataImpl());
-    } else if (change != NoChange) {
-        renderer->setStyle(document()->styleResolver()->styleForText(this));
+            renderer->setText(dataImpl());
+    } else if (needsStyleRecalc()) {
+        reattach();
     }
 
     clearNeedsStyleRecalc();
diff --git a/Source/core/dom/Text.h b/Source/core/dom/Text.h
index 3f33246..e4b3b1c 100644
--- a/Source/core/dom/Text.h
+++ b/Source/core/dom/Text.h
@@ -49,7 +49,7 @@
     void recalcTextStyle(StyleChange);
     void createTextRendererIfNeeded();
     bool textRendererIsNeeded(const NodeRenderingContext&);
-    RenderText* createTextRenderer(RenderArena*, RenderStyle*);
+    virtual RenderText* createTextRenderer(RenderStyle*);
     void updateTextRenderer(unsigned offsetOfReplacedData, unsigned lengthOfReplacedData);
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE FINAL;
diff --git a/Source/core/dom/TreeScope.cpp b/Source/core/dom/TreeScope.cpp
index 76e0aa2..2c447dc 100644
--- a/Source/core/dom/TreeScope.cpp
+++ b/Source/core/dom/TreeScope.cpp
@@ -47,9 +47,8 @@
 #include "core/page/Page.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderView.h"
-#include <wtf/text/AtomicString.h>
-#include <wtf/text/CString.h>
-#include <wtf/Vector.h>
+#include "wtf/Vector.h"
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/UserActionElementSet.h b/Source/core/dom/UserActionElementSet.h
index fa4d53f..9883262 100644
--- a/Source/core/dom/UserActionElementSet.h
+++ b/Source/core/dom/UserActionElementSet.h
@@ -27,11 +27,9 @@
 #ifndef UserActionElementSet_h
 #define UserActionElementSet_h
 
-#include <wtf/HashMap.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
+#include "wtf/HashMap.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/ViewportArguments.cpp b/Source/core/dom/ViewportArguments.cpp
index 331ac12..e0b346d 100644
--- a/Source/core/dom/ViewportArguments.cpp
+++ b/Source/core/dom/ViewportArguments.cpp
@@ -29,8 +29,7 @@
 #include "core/dom/ViewportArguments.h"
 
 #include "core/dom/Document.h"
-#include "core/platform/graphics/IntSize.h"
-#include <wtf/text/WTFString.h>
+#include "wtf/text/WTFString.h"
 
 using namespace std;
 
diff --git a/Source/core/dom/VisitedLinkState.h b/Source/core/dom/VisitedLinkState.h
index dc5338c..552e222 100644
--- a/Source/core/dom/VisitedLinkState.h
+++ b/Source/core/dom/VisitedLinkState.h
@@ -34,7 +34,6 @@
 #include "core/platform/LinkHash.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 #include "wtf/HashSet.h"
-#include "wtf/OwnPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/dom/WheelEvent.cpp b/Source/core/dom/WheelEvent.cpp
index a0a1ec6..2f430c3 100644
--- a/Source/core/dom/WheelEvent.cpp
+++ b/Source/core/dom/WheelEvent.cpp
@@ -27,8 +27,6 @@
 #include "core/dom/EventNames.h"
 #include "core/platform/PlatformWheelEvent.h"
 
-#include <wtf/MathExtras.h>
-
 namespace WebCore {
 
 WheelEventInit::WheelEventInit()
diff --git a/Source/core/dom/shadow/ContentDistributor.cpp b/Source/core/dom/shadow/ContentDistributor.cpp
index b9033b1..b3daf77 100644
--- a/Source/core/dom/shadow/ContentDistributor.cpp
+++ b/Source/core/dom/shadow/ContentDistributor.cpp
@@ -436,7 +436,7 @@
 {
     for (NodeInsertionPointMap::iterator i = m_nodeToInsertionPoint.begin(); i != m_nodeToInsertionPoint.end(); ++i) {
         if (i->value == insertionPoint)
-            const_cast<Node*>(i->key)->setNeedsStyleRecalc(SyntheticStyleChange);
+            const_cast<Node*>(i->key)->setNeedsStyleRecalc(InlineStyleChange);
     }
 }
 
diff --git a/Source/core/dom/shadow/ContentDistributor.h b/Source/core/dom/shadow/ContentDistributor.h
index c90049b..442dc41 100644
--- a/Source/core/dom/shadow/ContentDistributor.h
+++ b/Source/core/dom/shadow/ContentDistributor.h
@@ -34,7 +34,6 @@
 #include "core/dom/shadow/SelectRuleFeatureSet.h"
 #include "wtf/Forward.h"
 #include "wtf/HashMap.h"
-#include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
diff --git a/Source/core/dom/shadow/ContentSelectorQuery.h b/Source/core/dom/shadow/ContentSelectorQuery.h
index fd7cd82..b37008a 100644
--- a/Source/core/dom/shadow/ContentSelectorQuery.h
+++ b/Source/core/dom/shadow/ContentSelectorQuery.h
@@ -32,8 +32,6 @@
 #define ContentSelectorQuery_h
 
 #include "core/css/CSSSelectorList.h"
-#include "core/css/SelectorChecker.h"
-#include "core/dom/SelectorQuery.h"
 #include "wtf/Forward.h"
 #include "wtf/Vector.h"
 
diff --git a/Source/core/dom/shadow/ElementShadow.cpp b/Source/core/dom/shadow/ElementShadow.cpp
index 807aeab..2e988ee 100644
--- a/Source/core/dom/shadow/ElementShadow.cpp
+++ b/Source/core/dom/shadow/ElementShadow.cpp
@@ -72,21 +72,27 @@
     m_distributor.invalidateDistribution(shadowHost);
 }
 
-void ElementShadow::attach()
+void ElementShadow::attach(const Node::AttachContext& context)
 {
     ContentDistributor::ensureDistribution(host());
 
+    Node::AttachContext childrenContext(context);
+    childrenContext.resolvedStyle = 0;
+
     for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
         if (!root->attached())
-            root->attach();
+            root->attach(childrenContext);
     }
 }
 
-void ElementShadow::detach()
+void ElementShadow::detach(const Node::AttachContext& context)
 {
+    Node::AttachContext childrenContext(context);
+    childrenContext.resolvedStyle = 0;
+
     for (ShadowRoot* root = youngestShadowRoot(); root; root = root->olderShadowRoot()) {
         if (root->attached())
-            root->detach();
+            root->detach(childrenContext);
     }
 }
 
diff --git a/Source/core/dom/shadow/ElementShadow.h b/Source/core/dom/shadow/ElementShadow.h
index fc7c7b9..a3ce07e 100644
--- a/Source/core/dom/shadow/ElementShadow.h
+++ b/Source/core/dom/shadow/ElementShadow.h
@@ -27,13 +27,11 @@
 #ifndef ElementShadow_h
 #define ElementShadow_h
 
-#include "core/dom/ExceptionCode.h"
 #include "core/dom/shadow/ContentDistributor.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "wtf/DoublyLinkedList.h"
 #include "wtf/Noncopyable.h"
 #include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
@@ -58,8 +56,8 @@
 
     ShadowRoot* addShadowRoot(Element* shadowHost, ShadowRoot::ShadowRootType);
 
-    void attach();
-    void detach();
+    void attach(const Node::AttachContext&);
+    void detach(const Node::AttachContext&);
 
     bool childNeedsStyleRecalc() const;
     bool needsStyleRecalc() const;
diff --git a/Source/core/dom/shadow/InsertionPoint.h b/Source/core/dom/shadow/InsertionPoint.h
index 9348f23..44cd1f9 100644
--- a/Source/core/dom/shadow/InsertionPoint.h
+++ b/Source/core/dom/shadow/InsertionPoint.h
@@ -31,11 +31,9 @@
 #ifndef InsertionPoint_h
 #define InsertionPoint_h
 
-#include "HTMLNames.h"
 #include "core/css/CSSSelectorList.h"
 #include "core/dom/shadow/ContentDistributor.h"
 #include "core/dom/shadow/ElementShadow.h"
-#include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLElement.h"
 #include "wtf/Forward.h"
 
diff --git a/Source/core/dom/shadow/ShadowRoot.cpp b/Source/core/dom/shadow/ShadowRoot.cpp
index b3f02e9..52165d6 100644
--- a/Source/core/dom/shadow/ShadowRoot.cpp
+++ b/Source/core/dom/shadow/ShadowRoot.cpp
@@ -27,7 +27,6 @@
 #include "config.h"
 #include "core/dom/shadow/ShadowRoot.h"
 
-#include "RuntimeEnabledFeatures.h"
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Text.h"
 #include "core/dom/shadow/ContentDistributor.h"
diff --git a/Source/core/editing/ApplyStyleCommand.cpp b/Source/core/editing/ApplyStyleCommand.cpp
index 53ba1cd..d8810b1 100644
--- a/Source/core/editing/ApplyStyleCommand.cpp
+++ b/Source/core/editing/ApplyStyleCommand.cpp
@@ -66,7 +66,7 @@
     return elem->hasLocalName(spanAttr) && elem->getAttribute(classAttr) == styleSpanClassString();
 }
 
-static bool hasNoAttributeOrOnlyStyleAttribute(const StyledElement* element, ShouldStyleAttributeBeEmpty shouldStyleAttributeBeEmpty)
+static bool hasNoAttributeOrOnlyStyleAttribute(const Element* element, ShouldStyleAttributeBeEmpty shouldStyleAttributeBeEmpty)
 {
     if (!element->hasAttributes())
         return true;
@@ -501,7 +501,7 @@
         if (!n->isStyledElement())
             continue;
 
-        StyledElement* element = static_cast<StyledElement*>(n);
+        Element* element = toElement(n);
         int unicodeBidi = getIdentifierValue(CSSComputedStyleDeclaration::create(element).get(), CSSPropertyUnicodeBidi);
         if (!unicodeBidi || unicodeBidi == CSSValueNormal)
             continue;
@@ -1026,9 +1026,9 @@
     while (current && current != targetNode && current->contains(targetNode)) {
         NodeVector currentChildren;
         getChildNodes(current.get(), currentChildren);
-        RefPtr<StyledElement> styledElement;
+        RefPtr<Element> styledElement;
         if (current->isStyledElement() && isStyledInlineElementToRemove(toElement(current.get()))) {
-            styledElement = static_cast<StyledElement*>(current.get());
+            styledElement = toElement(current.get());
             elementsToPushDown.append(styledElement);
         }
 
@@ -1098,16 +1098,17 @@
     Position s = start.isNull() || start.isOrphan() ? pushDownStart : start;
     Position e = end.isNull() || end.isOrphan() ? pushDownEnd : end;
 
-    Node* node = start.deprecatedNode();
+    RefPtr<Node> node = start.deprecatedNode();
     while (node) {
         RefPtr<Node> next;
-        if (editingIgnoresContent(node)) {
+        if (editingIgnoresContent(node.get())) {
             ASSERT(node == end.deprecatedNode() || !node->contains(end.deprecatedNode()));
-            next = NodeTraversal::nextSkippingChildren(node);
-        } else
-            next = NodeTraversal::next(node);
-        if (node->isHTMLElement() && nodeFullySelected(node, start, end)) {
-            RefPtr<HTMLElement> elem = toHTMLElement(node);
+            next = NodeTraversal::nextSkippingChildren(node.get());
+        } else {
+            next = NodeTraversal::next(node.get());
+        }
+        if (node->isHTMLElement() && nodeFullySelected(node.get(), start, end)) {
+            RefPtr<HTMLElement> elem = toHTMLElement(node.get());
             RefPtr<Node> prev = NodeTraversal::previousPostOrder(elem.get());
             RefPtr<Node> next = NodeTraversal::next(elem.get());
             RefPtr<EditingStyle> styleToPushDown;
@@ -1141,7 +1142,7 @@
         }
         if (node == end.deprecatedNode())
             break;
-        node = next.get();
+        node = next;
     }
 
     updateStartEnd(s, e);
@@ -1309,8 +1310,8 @@
 
     Node* nextSibling = endNode->nextSibling();
     if (nextSibling && areIdenticalElements(endNode, nextSibling)) {
-        Element* nextElement = static_cast<Element *>(nextSibling);
-        Element* element = static_cast<Element *>(endNode);
+        Element* nextElement = toElement(nextSibling);
+        Element* element = toElement(endNode);
         Node* nextChild = nextElement->firstChild();
 
         mergeIdenticalElements(element, nextElement);
diff --git a/Source/core/editing/CompositeEditCommand.cpp b/Source/core/editing/CompositeEditCommand.cpp
index 11b3ed7..17d3111 100644
--- a/Source/core/editing/CompositeEditCommand.cpp
+++ b/Source/core/editing/CompositeEditCommand.cpp
@@ -64,7 +64,6 @@
 #include "core/rendering/InlineTextBox.h"
 #include "core/rendering/RenderBlock.h"
 #include "core/rendering/RenderText.h"
-#include <wtf/unicode/CharacterNames.h>
 
 using namespace std;
 
@@ -575,7 +574,7 @@
         applyCommandToComposite(DeleteSelectionCommand::create(selection, smartDelete, mergeBlocksAfterDelete, replace, expandForSpecialElements, sanitizeMarkup));
 }
 
-void CompositeEditCommand::removeCSSProperty(PassRefPtr<StyledElement> element, CSSPropertyID property)
+void CompositeEditCommand::removeCSSProperty(PassRefPtr<Element> element, CSSPropertyID property)
 {
     applyCommandToComposite(RemoveCSSPropertyCommand::create(document(), element, property));
 }
@@ -593,7 +592,7 @@
 static inline bool containsOnlyWhitespace(const String& text)
 {
     for (unsigned i = 0; i < text.length(); ++i) {
-        if (!isWhitespace(text.characters()[i]))
+        if (!isWhitespace(text[i]))
             return false;
     }
     
@@ -1000,7 +999,7 @@
         for (size_t i = ancestors.size(); i != 0; --i) {
             Node* item = ancestors[i - 1].get();
             RefPtr<Node> child = item->cloneNode(isTableElement(item));
-            appendNode(child, static_cast<Element *>(lastNode.get()));
+            appendNode(child, toElement(lastNode.get()));
             lastNode = child.release();
         }
     }
diff --git a/Source/core/editing/CompositeEditCommand.h b/Source/core/editing/CompositeEditCommand.h
index 88a64c2..7c48bd5 100644
--- a/Source/core/editing/CompositeEditCommand.h
+++ b/Source/core/editing/CompositeEditCommand.h
@@ -34,8 +34,8 @@
 namespace WebCore {
 
 class EditingStyle;
+class Element;
 class HTMLElement;
-class StyledElement;
 class Text;
 
 class EditCommandComposition : public UndoStep {
@@ -118,7 +118,7 @@
     void prepareWhitespaceAtPositionForSplit(Position&);
     bool canRebalance(const Position&) const;
     bool shouldRebalanceLeadingWhitespaceFor(const String&) const;
-    void removeCSSProperty(PassRefPtr<StyledElement>, CSSPropertyID);
+    void removeCSSProperty(PassRefPtr<Element>, CSSPropertyID);
     void removeNodeAttribute(PassRefPtr<Element>, const QualifiedName& attribute);
     void removeChildrenInRange(PassRefPtr<Node>, unsigned from, unsigned to);
     virtual void removeNode(PassRefPtr<Node>, ShouldAssumeContentIsAlwaysEditable = DoNotAssumeContentIsAlwaysEditable);
diff --git a/Source/core/editing/DeleteSelectionCommand.cpp b/Source/core/editing/DeleteSelectionCommand.cpp
index 868e60a..a01bb00 100644
--- a/Source/core/editing/DeleteSelectionCommand.cpp
+++ b/Source/core/editing/DeleteSelectionCommand.cpp
@@ -28,8 +28,6 @@
 
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
-#include "core/dom/DocumentFragment.h"
-#include "core/dom/DocumentMarkerController.h"
 #include "core/dom/Element.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/Text.h"
@@ -38,8 +36,6 @@
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/HTMLTextAreaElement.h"
-#include "core/page/EditorClient.h"
 #include "core/page/Frame.h"
 #include "core/rendering/RenderTableCell.h"
 
diff --git a/Source/core/editing/EditCommand.cpp b/Source/core/editing/EditCommand.cpp
index 01bd53e..2fac607 100644
--- a/Source/core/editing/EditCommand.cpp
+++ b/Source/core/editing/EditCommand.cpp
@@ -27,14 +27,9 @@
 #include "core/editing/EditCommand.h"
 
 #include "core/dom/Document.h"
-#include "core/dom/Element.h"
-#include "core/dom/EventNames.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/editing/CompositeEditCommand.h"
-#include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
-#include "core/editing/VisiblePosition.h"
-#include "core/editing/htmlediting.h"
 #include "core/page/Frame.h"
 
 namespace WebCore {
diff --git a/Source/core/editing/EditingStyle.cpp b/Source/core/editing/EditingStyle.cpp
index 9ee281c..59edb02 100644
--- a/Source/core/editing/EditingStyle.cpp
+++ b/Source/core/editing/EditingStyle.cpp
@@ -38,11 +38,11 @@
 #include "core/css/StylePropertySet.h"
 #include "core/css/StyleRule.h"
 #include "core/css/resolver/StyleResolver.h"
+#include "core/dom/Element.h"
 #include "core/dom/Node.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/Position.h"
 #include "core/dom/QualifiedName.h"
-#include "core/dom/StyledElement.h"
 #include "core/editing/ApplyStyleCommand.h"
 #include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
@@ -52,7 +52,6 @@
 #include "core/page/Frame.h"
 #include "core/page/RuntimeCSSEnabled.h"
 #include "core/rendering/style/RenderStyle.h"
-#include <wtf/HashSet.h>
 
 namespace WebCore {
 
@@ -716,7 +715,7 @@
     return state;
 }
 
-bool EditingStyle::conflictsWithInlineStyleOfElement(StyledElement* element, EditingStyle* extractedStyle, Vector<CSSPropertyID>* conflictingProperties) const
+bool EditingStyle::conflictsWithInlineStyleOfElement(Element* element, EditingStyle* extractedStyle, Vector<CSSPropertyID>* conflictingProperties) const
 {
     ASSERT(element);
     ASSERT(!conflictingProperties || conflictingProperties->isEmpty());
@@ -970,7 +969,7 @@
     mergeStyle(typingStyle->style(), OverrideValues);
 }
 
-void EditingStyle::mergeInlineStyleOfElement(StyledElement* element, CSSPropertyOverrideMode mode, PropertiesToInclude propertiesToInclude)
+void EditingStyle::mergeInlineStyleOfElement(Element* element, CSSPropertyOverrideMode mode, PropertiesToInclude propertiesToInclude)
 {
     ASSERT(element);
     if (!element->inlineStyle())
@@ -989,14 +988,14 @@
     }
 }
 
-static inline bool elementMatchesAndPropertyIsNotInInlineStyleDecl(const HTMLElementEquivalent* equivalent, const StyledElement* element,
+static inline bool elementMatchesAndPropertyIsNotInInlineStyleDecl(const HTMLElementEquivalent* equivalent, const Element* element,
     EditingStyle::CSSPropertyOverrideMode mode, StylePropertySet* style)
 {
     return equivalent->matches(element) && (!element->inlineStyle() || !equivalent->propertyExistsInStyle(element->inlineStyle()))
         && (mode == EditingStyle::OverrideValues || !equivalent->propertyExistsInStyle(style));
 }
 
-void EditingStyle::mergeInlineAndImplicitStyleOfElement(StyledElement* element, CSSPropertyOverrideMode mode, PropertiesToInclude propertiesToInclude)
+void EditingStyle::mergeInlineAndImplicitStyleOfElement(Element* element, CSSPropertyOverrideMode mode, PropertiesToInclude propertiesToInclude)
 {
     RefPtr<EditingStyle> styleFromRules = EditingStyle::create();
     styleFromRules->mergeStyleFromRulesForSerialization(element);
@@ -1042,7 +1041,7 @@
     // When not annotating for interchange, we only preserve inline style declarations.
     for (Node* node = context; node && !node->isDocumentNode(); node = node->parentNode()) {
         if (node->isStyledElement() && !isMailBlockquote(node)) {
-            wrappingStyle->mergeInlineAndImplicitStyleOfElement(static_cast<StyledElement*>(node), EditingStyle::DoNotOverrideValues,
+            wrappingStyle->mergeInlineAndImplicitStyleOfElement(toElement(node), EditingStyle::DoNotOverrideValues,
                 EditingStyle::EditingPropertiesInEffect);
         }
     }
@@ -1106,7 +1105,7 @@
     return style.release();
 }
 
-void EditingStyle::mergeStyleFromRules(StyledElement* element)
+void EditingStyle::mergeStyleFromRules(Element* element)
 {
     RefPtr<MutableStylePropertySet> styleFromMatchedRules = styleFromMatchedRulesForElement(element,
         StyleResolver::AuthorCSSRules | StyleResolver::CrossOriginCSSRules);
@@ -1119,7 +1118,7 @@
     m_mutableStyle = styleFromMatchedRules;
 }
 
-void EditingStyle::mergeStyleFromRulesForSerialization(StyledElement* element)
+void EditingStyle::mergeStyleFromRulesForSerialization(Element* element)
 {
     mergeStyleFromRules(element);
 
@@ -1154,7 +1153,7 @@
     styleToRemovePropertiesFrom->removePropertiesInSet(propertiesToRemove.data(), propertiesToRemove.size());
 }
 
-void EditingStyle::removeStyleFromRulesAndContext(StyledElement* element, Node* context)
+void EditingStyle::removeStyleFromRulesAndContext(Element* element, Node* context)
 {
     ASSERT(element);
     if (!m_mutableStyle)
diff --git a/Source/core/editing/EditingStyle.h b/Source/core/editing/EditingStyle.h
index 8f724c3..b56a7bc 100644
--- a/Source/core/editing/EditingStyle.h
+++ b/Source/core/editing/EditingStyle.h
@@ -57,7 +57,6 @@
 class QualifiedName;
 class RenderStyle;
 class StylePropertySet;
-class StyledElement;
 class VisibleSelection;
 
 class EditingStyle : public RefCounted<EditingStyle> {
@@ -117,8 +116,8 @@
     enum ShouldIgnoreTextOnlyProperties { IgnoreTextOnlyProperties, DoNotIgnoreTextOnlyProperties };
     TriState triStateOfStyle(EditingStyle*) const;
     TriState triStateOfStyle(const VisibleSelection&) const;
-    bool conflictsWithInlineStyleOfElement(StyledElement* element) const { return conflictsWithInlineStyleOfElement(element, 0, 0); }
-    bool conflictsWithInlineStyleOfElement(StyledElement* element, EditingStyle* extractedStyle, Vector<CSSPropertyID>& conflictingProperties) const
+    bool conflictsWithInlineStyleOfElement(Element* element) const { return conflictsWithInlineStyleOfElement(element, 0, 0); }
+    bool conflictsWithInlineStyleOfElement(Element* element, EditingStyle* extractedStyle, Vector<CSSPropertyID>& conflictingProperties) const
     {
         return conflictsWithInlineStyleOfElement(element, extractedStyle, &conflictingProperties);
     }
@@ -133,11 +132,11 @@
     void prepareToApplyAt(const Position&, ShouldPreserveWritingDirection = DoNotPreserveWritingDirection);
     void mergeTypingStyle(Document*);
     enum CSSPropertyOverrideMode { OverrideValues, DoNotOverrideValues };
-    void mergeInlineStyleOfElement(StyledElement*, CSSPropertyOverrideMode, PropertiesToInclude = AllProperties);
+    void mergeInlineStyleOfElement(Element*, CSSPropertyOverrideMode, PropertiesToInclude = AllProperties);
     static PassRefPtr<EditingStyle> wrappingStyleForSerialization(Node* context, bool shouldAnnotate);
-    void mergeStyleFromRules(StyledElement*);
-    void mergeStyleFromRulesForSerialization(StyledElement*);
-    void removeStyleFromRulesAndContext(StyledElement*, Node* context);
+    void mergeStyleFromRules(Element*);
+    void mergeStyleFromRulesForSerialization(Element*);
+    void removeStyleFromRulesAndContext(Element*, Node* context);
     void removePropertiesInElementDefaultStyle(Element*);
     void forceInline();
     int legacyFontSize(Document*) const;
@@ -161,8 +160,8 @@
     void replaceFontSizeByKeywordIfPossible(RenderStyle*, CSSComputedStyleDeclaration*);
     void extractFontSizeDelta();
     TriState triStateOfStyle(CSSStyleDeclaration* styleToCompare, ShouldIgnoreTextOnlyProperties) const;
-    bool conflictsWithInlineStyleOfElement(StyledElement*, EditingStyle* extractedStyle, Vector<CSSPropertyID>* conflictingProperties) const;
-    void mergeInlineAndImplicitStyleOfElement(StyledElement*, CSSPropertyOverrideMode, PropertiesToInclude);
+    bool conflictsWithInlineStyleOfElement(Element*, EditingStyle* extractedStyle, Vector<CSSPropertyID>* conflictingProperties) const;
+    void mergeInlineAndImplicitStyleOfElement(Element*, CSSPropertyOverrideMode, PropertiesToInclude);
     void mergeStyle(const StylePropertySet*, CSSPropertyOverrideMode);
 
     RefPtr<MutableStylePropertySet> m_mutableStyle;
diff --git a/Source/core/editing/Editor.cpp b/Source/core/editing/Editor.cpp
index 6138644..080a3f5 100644
--- a/Source/core/editing/Editor.cpp
+++ b/Source/core/editing/Editor.cpp
@@ -28,12 +28,10 @@
 #include "core/editing/Editor.h"
 
 #include "CSSPropertyNames.h"
-#include "CSSValueKeywords.h"
 #include "HTMLNames.h"
 #include "core/accessibility/AXObjectCache.h"
 #include "core/css/CSSComputedStyleDeclaration.h"
 #include "core/css/StylePropertySet.h"
-#include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Clipboard.h"
 #include "core/dom/ClipboardEvent.h"
 #include "core/dom/CompositionEvent.h"
@@ -47,9 +45,7 @@
 #include "core/dom/Text.h"
 #include "core/dom/TextEvent.h"
 #include "core/dom/UserTypingGestureIndicator.h"
-#include "core/dom/shadow/ShadowRoot.h"
 #include "core/editing/ApplyStyleCommand.h"
-#include "core/editing/CreateLinkCommand.h"
 #include "core/editing/DeleteSelectionCommand.h"
 #include "core/editing/IndentOutdentCommand.h"
 #include "core/editing/InsertListCommand.h"
@@ -59,15 +55,12 @@
 #include "core/editing/ReplaceSelectionCommand.h"
 #include "core/editing/SimplifyMarkupCommand.h"
 #include "core/editing/SpellChecker.h"
-#include "core/editing/SpellingCorrectionCommand.h"
 #include "core/editing/TextCheckingHelper.h"
 #include "core/editing/TextIterator.h"
 #include "core/editing/TypingCommand.h"
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
 #include "core/editing/markup.h"
-#include "core/html/HTMLFormControlElement.h"
-#include "core/html/HTMLFrameOwnerElement.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLTextAreaElement.h"
 #include "core/loader/cache/CachedResourceLoader.h"
@@ -75,22 +68,17 @@
 #include "core/page/EventHandler.h"
 #include "core/page/FocusController.h"
 #include "core/page/Frame.h"
-#include "core/page/FrameTree.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
 #include "core/platform/KillRing.h"
 #include "core/platform/Pasteboard.h"
 #include "core/platform/Sound.h"
-#include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/text/TextCheckerClient.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderBlock.h"
-#include "core/rendering/RenderPart.h"
 #include "core/rendering/RenderTextControl.h"
-#include <wtf/unicode/CharacterNames.h>
-#include <wtf/unicode/Unicode.h>
-#include <wtf/UnusedParam.h>
+#include "wtf/unicode/CharacterNames.h"
 
 namespace WebCore {
 
@@ -1259,7 +1247,13 @@
             // We should send a compositionstart event only when the given text is not empty because this
             // function doesn't create a composition node when the text is empty.
             if (!text.isEmpty()) {
-                target->dispatchEvent(CompositionEvent::create(eventNames().compositionstartEvent, m_frame->document()->domWindow(), text));
+                FrameSelection* selection = m_frame->selection();
+                String selectionText;
+                if (selection->isRange()) {
+                    RefPtr<Range> range = selection->toNormalizedRange();
+                    selectionText = plainText(range.get());
+                }
+                target->dispatchEvent(CompositionEvent::create(eventNames().compositionstartEvent, m_frame->document()->domWindow(), selectionText));
                 event = CompositionEvent::create(eventNames().compositionupdateEvent, m_frame->document()->domWindow(), text);
             }
         } else {
@@ -1509,7 +1503,7 @@
     int wordLength = word.length();
     int misspellingLocation = -1;
     int misspellingLength = 0;
-    textChecker()->checkSpellingOfString(word.characters(), wordLength, &misspellingLocation, &misspellingLength);
+    textChecker()->checkSpellingOfString(word.bloatedCharacters(), wordLength, &misspellingLocation, &misspellingLength);
 
     return misspellingLength == wordLength ? word : String();
 }
@@ -2127,7 +2121,7 @@
         return;
 
     // Mutate using the CSSOM wrapper so we get the same event behavior as a script.
-    CSSStyleDeclaration* style = static_cast<StyledElement*>(element)->style();
+    CSSStyleDeclaration* style = element->style();
     style->setPropertyInternal(CSSPropertyWordWrap, "break-word", false, IGNORE_EXCEPTION);
     style->setPropertyInternal(CSSPropertyWebkitLineBreak, "after-white-space", false, IGNORE_EXCEPTION);
 }
@@ -2355,4 +2349,10 @@
     return WebCore::unifiedTextCheckerEnabled(m_frame);
 }
 
+void Editor::toggleOverwriteModeEnabled()
+{
+    m_overwriteModeEnabled = !m_overwriteModeEnabled;
+    frame()->selection()->setShouldShowBlockCursor(m_overwriteModeEnabled);
+};
+
 } // namespace WebCore
diff --git a/Source/core/editing/Editor.h b/Source/core/editing/Editor.h
index b7bf689..5d70302 100644
--- a/Source/core/editing/Editor.h
+++ b/Source/core/editing/Editor.h
@@ -30,7 +30,6 @@
 #include "core/dom/DocumentMarker.h"
 #include "core/editing/EditAction.h"
 #include "core/editing/EditingBehavior.h"
-#include "core/editing/EditingStyle.h"
 #include "core/editing/EditorInsertAction.h"
 #include "core/editing/FindOptions.h"
 #include "core/editing/FrameSelection.h"
@@ -212,7 +211,7 @@
     void markAndReplaceFor(PassRefPtr<SpellCheckRequest>, const Vector<TextCheckingResult>&);
 
     bool isOverwriteModeEnabled() const { return m_overwriteModeEnabled; }
-    void toggleOverwriteModeEnabled() { m_overwriteModeEnabled = !m_overwriteModeEnabled; }
+    void toggleOverwriteModeEnabled();
 
     void markAllMisspellingsAndBadGrammarInRanges(TextCheckingTypeMask, Range* spellingRange, Range* grammarRange);
 
diff --git a/Source/core/editing/EditorCommand.cpp b/Source/core/editing/EditorCommand.cpp
index 5fcf7e2..95ee56b 100644
--- a/Source/core/editing/EditorCommand.cpp
+++ b/Source/core/editing/EditorCommand.cpp
@@ -799,12 +799,24 @@
     return true;
 }
 
+static bool executeMoveParagraphBackward(Frame* frame, Event*, EditorCommandSource, const String&)
+{
+    frame->selection()->modify(FrameSelection::AlterationMove, DirectionBackward, ParagraphGranularity, UserTriggered);
+    return true;
+}
+
 static bool executeMoveParagraphBackwardAndModifySelection(Frame* frame, Event*, EditorCommandSource, const String&)
 {
     frame->selection()->modify(FrameSelection::AlterationExtend, DirectionBackward, ParagraphGranularity, UserTriggered);
     return true;
 }
 
+static bool executeMoveParagraphForward(Frame* frame, Event*, EditorCommandSource, const String&)
+{
+    frame->selection()->modify(FrameSelection::AlterationMove, DirectionForward, ParagraphGranularity, UserTriggered);
+    return true;
+}
+
 static bool executeMoveParagraphForwardAndModifySelection(Frame* frame, Event*, EditorCommandSource, const String&)
 {
     frame->selection()->modify(FrameSelection::AlterationExtend, DirectionForward, ParagraphGranularity, UserTriggered);
@@ -1505,7 +1517,9 @@
         { "MovePageDownAndModifySelection", { executeMovePageDownAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
         { "MovePageUp", { executeMovePageUp, supportedFromMenuOrKeyBinding, enabledInEditableText, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
         { "MovePageUpAndModifySelection", { executeMovePageUpAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelection, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveParagraphBackward", { executeMoveParagraphBackward, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
         { "MoveParagraphBackwardAndModifySelection", { executeMoveParagraphBackwardAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
+        { "MoveParagraphForward", { executeMoveParagraphForward, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
         { "MoveParagraphForwardAndModifySelection", { executeMoveParagraphForwardAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
         { "MoveRight", { executeMoveRight, supportedFromMenuOrKeyBinding, enabledInEditableTextOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
         { "MoveRightAndModifySelection", { executeMoveRightAndModifySelection, supportedFromMenuOrKeyBinding, enabledVisibleSelectionOrCaretBrowsing, stateNone, valueNull, notTextInsertion, doNotAllowExecutionWhenDisabled } },
diff --git a/Source/core/editing/FrameSelection.cpp b/Source/core/editing/FrameSelection.cpp
index 229f473..44df81e 100644
--- a/Source/core/editing/FrameSelection.cpp
+++ b/Source/core/editing/FrameSelection.cpp
@@ -26,9 +26,9 @@
 #include "config.h"
 #include "core/editing/FrameSelection.h"
 
-#include <limits.h>
 #include <stdio.h>
 #include "HTMLNames.h"
+#include "core/accessibility/AXObjectCache.h"
 #include "core/css/StylePropertySet.h"
 #include "core/dom/CharacterData.h"
 #include "core/dom/Document.h"
@@ -63,7 +63,7 @@
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
 #include "core/rendering/RenderWidget.h"
-#include <wtf/text/CString.h>
+#include "wtf/text/CString.h"
 
 #define EDIT_DEBUG 0
 
@@ -111,6 +111,7 @@
     , m_caretPaint(true)
     , m_isCaretBlinkingSuspended(false)
     , m_focused(frame && frame->page() && frame->page()->focusController()->focusedFrame() == frame)
+    , m_shouldShowBlockCursor(false)
 {
     if (shouldAlwaysUseDirectionalSelection(m_frame))
         m_selection.setIsDirectional(true);
@@ -506,6 +507,11 @@
     return directionOfEnclosingBlock();
 }
 
+void FrameSelection::didChangeFocus()
+{
+    updateAppearance();
+}
+
 void FrameSelection::willBeModified(EAlteration alter, SelectionDirection direction)
 {
     if (alter != AlterationExtend)
@@ -1474,7 +1480,7 @@
 void FrameSelection::debugRenderer(RenderObject *r, bool selected) const
 {
     if (r->node()->isElementNode()) {
-        Element* element = static_cast<Element *>(r->node());
+        Element* element = toElement(r->node());
         fprintf(stderr, "%s%s\n", selected ? "==> " : "    ", element->localName().string().utf8().data());
     } else if (r->isText()) {
         RenderText* textRenderer = toRenderText(r);
@@ -1687,6 +1693,14 @@
     return textControl && textControl->hasTagName(inputTag) && toHTMLInputElement(textControl)->isPasswordField();
 }
 
+void FrameSelection::notifyAccessibilityForSelectionChange()
+{
+    if (m_selection.start().isNotNull() && m_selection.end().isNotNull()) {
+        if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache())
+            cache->selectionChanged(m_selection.start().containerNode());
+    }
+}
+
 void FrameSelection::focusedOrActiveStateChanged()
 {
     bool activeAndFocused = isFocusedAndActive();
@@ -1760,15 +1774,26 @@
 
 void FrameSelection::updateAppearance()
 {
-    bool caretRectChangedOrCleared = recomputeCaretRect();
+    // Paint a block cursor instead of a caret in overtype mode unless the caret is at the end of a line (in this case
+    // the FrameSelection will paint a blinking caret as usual).
+    VisiblePosition forwardPosition;
+    if (m_shouldShowBlockCursor && m_selection.isCaret()) {
+        forwardPosition = modifyExtendingForward(CharacterGranularity);
+        m_caretPaint = forwardPosition.isNull();
+    }
 
-    bool caretBrowsing = m_frame->settings() && m_frame->settings()->caretBrowsingEnabled();
-    bool shouldBlink = caretIsVisible() && isCaret() && (isContentEditable() || caretBrowsing);
+    bool caretRectChangedOrCleared = recomputeCaretRect();
+    bool shouldBlink = shouldBlinkCaret() && forwardPosition.isNull();
 
     // If the caret moved, stop the blink timer so we can restart with a
     // black caret in the new location.
-    if (caretRectChangedOrCleared || !shouldBlink || shouldStopBlinkingDueToTypingCommand(m_frame))
+    if (caretRectChangedOrCleared || !shouldBlink || shouldStopBlinkingDueToTypingCommand(m_frame)) {
         m_caretBlinkTimer.stop();
+        if (!shouldBlink && m_caretPaint) {
+            m_caretPaint = false;
+            invalidateCaretRect();
+        }
+    }
 
     // Start blinking with a black caret. Be sure not to restart if we're
     // already blinking in the right location.
@@ -1788,7 +1813,7 @@
 
     // Construct a new VisibleSolution, since m_selection is not necessarily valid, and the following steps
     // assume a valid selection. See <https://bugs.webkit.org/show_bug.cgi?id=69563> and <rdar://problem/10232866>.
-    VisibleSelection selection(m_selection.visibleStart(), m_selection.visibleEnd());
+    VisibleSelection selection(m_selection.visibleStart(), forwardPosition.isNotNull() ? forwardPosition : m_selection.visibleEnd());
 
     if (!selection.isRange()) {
         view->clearSelection();
@@ -1832,6 +1857,25 @@
     updateAppearance();
 }
 
+bool FrameSelection::shouldBlinkCaret() const
+{
+    if (!caretIsVisible() || !isCaret())
+        return false;
+
+    if (m_frame->settings() && m_frame->settings()->caretBrowsingEnabled())
+        return false;
+
+    Node* root = rootEditableElement();
+    if (!root)
+        return false;
+
+    Node* focusedNode = root->document()->focusedNode();
+    if (!focusedNode)
+        return false;
+
+    return focusedNode->containsIncludingShadowDOM(m_selection.start().anchorNode());
+}
+
 void FrameSelection::caretBlinkTimerFired(Timer<FrameSelection>*)
 {
     ASSERT(caretIsVisible());
@@ -1952,9 +1996,9 @@
     Element* element = start->isElementNode() ? toElement(start) : ElementTraversal::next(start);
     for (; element; element = ElementTraversal::next(element)) {
         if (element->hasTagName(formTag))
-            return static_cast<HTMLFormElement*>(element);
+            return toHTMLFormElement(element);
         if (element->isHTMLElement() && toHTMLElement(element)->isFormControlElement())
-            return static_cast<HTMLFormControlElement*>(element)->form();
+            return toHTMLFormControlElement(element)->form();
         if (element->hasTagName(frameTag) || element->hasTagName(iframeTag)) {
             Node* childDocument = static_cast<HTMLFrameElementBase*>(element)->contentDocument();
             if (HTMLFormElement* frameResult = scanForForm(childDocument))
@@ -1976,9 +2020,9 @@
     Node* node;
     for (node = start; node; node = node->parentNode()) {
         if (node->hasTagName(formTag))
-            return static_cast<HTMLFormElement*>(node);
+            return toHTMLFormElement(node);
         if (node->isHTMLElement() && toHTMLElement(node)->isFormControlElement())
-            return static_cast<HTMLFormControlElement*>(node)->form();
+            return toHTMLFormControlElement(node)->form();
     }
 
     // Try walking forward in the node tree to find a form element.
@@ -2048,6 +2092,15 @@
     return settings && settings->visualWordMovementEnabled();
 }
 
+void FrameSelection::setShouldShowBlockCursor(bool shouldShowBlockCursor)
+{
+    m_shouldShowBlockCursor = shouldShowBlockCursor;
+
+    m_frame->document()->updateLayoutIgnorePendingStylesheets();
+
+    updateAppearance();
+}
+
 #ifndef NDEBUG
 
 void FrameSelection::formatForDebugger(char* buffer, unsigned length) const
diff --git a/Source/core/editing/FrameSelection.h b/Source/core/editing/FrameSelection.h
index 119d04c..655be75 100644
--- a/Source/core/editing/FrameSelection.h
+++ b/Source/core/editing/FrameSelection.h
@@ -192,6 +192,7 @@
     IntRect absoluteCaretBounds();
     void setCaretRectNeedsUpdate() { CaretBase::setCaretRectNeedsUpdate(); }
 
+    void didChangeFocus();
     void willBeModified(EAlteration, SelectionDirection);
 
     bool isNone() const { return m_selection.isNone(); }
@@ -256,6 +257,9 @@
     void revealSelection(const ScrollAlignment& = ScrollAlignment::alignCenterIfNeeded, RevealExtentOption = DoNotRevealExtent);
     void setSelectionFromNone();
 
+    bool shouldShowBlockCursor() const { return m_shouldShowBlockCursor; }
+    void setShouldShowBlockCursor(bool);
+
 private:
     enum EPositionType { START, END, BASE, EXTENT };
 
@@ -288,6 +292,7 @@
     void setUseSecureKeyboardEntry(bool);
 
     void setCaretVisibility(CaretVisibility);
+    bool shouldBlinkCaret() const;
 
     bool dispatchSelectStart();
   
@@ -312,6 +317,7 @@
     bool m_caretPaint : 1;
     bool m_isCaretBlinkingSuspended : 1;
     bool m_focused : 1;
+    bool m_shouldShowBlockCursor : 1;
 };
 
 inline EditingStyle* FrameSelection::typingStyle() const
diff --git a/Source/core/editing/HTMLInterchange.cpp b/Source/core/editing/HTMLInterchange.cpp
index 5badb0e..27938e5 100644
--- a/Source/core/editing/HTMLInterchange.cpp
+++ b/Source/core/editing/HTMLInterchange.cpp
@@ -29,9 +29,8 @@
 #include "core/dom/Text.h"
 #include "core/editing/TextIterator.h"
 #include "core/rendering/RenderObject.h"
-#include <wtf/StdLibExtras.h>
-#include <wtf/text/StringBuilder.h>
-#include <wtf/unicode/CharacterNames.h>
+#include "wtf/text/StringBuilder.h"
+#include "wtf/unicode/CharacterNames.h"
 
 namespace WebCore {
 
diff --git a/Source/core/editing/IndentOutdentCommand.cpp b/Source/core/editing/IndentOutdentCommand.cpp
index d034cfa..348f012 100644
--- a/Source/core/editing/IndentOutdentCommand.cpp
+++ b/Source/core/editing/IndentOutdentCommand.cpp
@@ -33,7 +33,6 @@
 #include "core/editing/htmlediting.h"
 #include "core/html/HTMLElement.h"
 #include "core/rendering/RenderObject.h"
-#include <wtf/StdLibExtras.h>
 
 namespace WebCore {
 
diff --git a/Source/core/editing/InsertListCommand.cpp b/Source/core/editing/InsertListCommand.cpp
index 51a72e3..477f088 100644
--- a/Source/core/editing/InsertListCommand.cpp
+++ b/Source/core/editing/InsertListCommand.cpp
@@ -25,7 +25,6 @@
 
 #include "config.h"
 #include "HTMLNames.h"
-#include "core/dom/DocumentFragment.h"
 #include "core/dom/Element.h"
 #include "core/dom/ExceptionCodePlaceholder.h"
 #include "core/editing/InsertListCommand.h"
diff --git a/Source/core/editing/InsertTextCommand.cpp b/Source/core/editing/InsertTextCommand.cpp
index dcdf742..345ad9c 100644
--- a/Source/core/editing/InsertTextCommand.cpp
+++ b/Source/core/editing/InsertTextCommand.cpp
@@ -33,7 +33,6 @@
 #include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
 #include "core/page/Frame.h"
-#include <wtf/unicode/CharacterNames.h>
 
 namespace WebCore {
 
diff --git a/Source/core/editing/RemoveCSSPropertyCommand.cpp b/Source/core/editing/RemoveCSSPropertyCommand.cpp
index 8f69ff6..d94cf8a 100644
--- a/Source/core/editing/RemoveCSSPropertyCommand.cpp
+++ b/Source/core/editing/RemoveCSSPropertyCommand.cpp
@@ -28,13 +28,13 @@
 
 #include "core/css/CSSStyleDeclaration.h"
 #include "core/css/StylePropertySet.h"
+#include "core/dom/Element.h"
 #include "core/dom/ExceptionCodePlaceholder.h"
-#include "core/dom/StyledElement.h"
 #include <wtf/Assertions.h>
 
 namespace WebCore {
 
-RemoveCSSPropertyCommand::RemoveCSSPropertyCommand(Document* document, PassRefPtr<StyledElement> element, CSSPropertyID property)
+RemoveCSSPropertyCommand::RemoveCSSPropertyCommand(Document* document, PassRefPtr<Element> element, CSSPropertyID property)
     : SimpleEditCommand(document)
     , m_element(element)
     , m_property(property)
diff --git a/Source/core/editing/RemoveCSSPropertyCommand.h b/Source/core/editing/RemoveCSSPropertyCommand.h
index f6a5511..dea0f43 100644
--- a/Source/core/editing/RemoveCSSPropertyCommand.h
+++ b/Source/core/editing/RemoveCSSPropertyCommand.h
@@ -31,17 +31,17 @@
 
 namespace WebCore {
 
-class StyledElement;
+class Element;
 
 class RemoveCSSPropertyCommand : public SimpleEditCommand {
 public:
-    static PassRefPtr<RemoveCSSPropertyCommand> create(Document* document, PassRefPtr<StyledElement> element, CSSPropertyID property)
+    static PassRefPtr<RemoveCSSPropertyCommand> create(Document* document, PassRefPtr<Element> element, CSSPropertyID property)
     {
         return adoptRef(new RemoveCSSPropertyCommand(document, element, property));
     }
 
 private:
-    RemoveCSSPropertyCommand(Document*, PassRefPtr<StyledElement>, CSSPropertyID property);
+    RemoveCSSPropertyCommand(Document*, PassRefPtr<Element>, CSSPropertyID);
     ~RemoveCSSPropertyCommand();
 
     virtual void doApply() OVERRIDE;
@@ -51,7 +51,7 @@
     virtual void getNodesInCommand(HashSet<Node*>&) OVERRIDE;
 #endif
     
-    RefPtr<StyledElement> m_element;
+    RefPtr<Element> m_element;
     CSSPropertyID m_property;
     String m_oldValue;
     bool m_important;
diff --git a/Source/core/editing/ReplaceSelectionCommand.cpp b/Source/core/editing/ReplaceSelectionCommand.cpp
index a6f0892..0185e5e 100644
--- a/Source/core/editing/ReplaceSelectionCommand.cpp
+++ b/Source/core/editing/ReplaceSelectionCommand.cpp
@@ -82,9 +82,9 @@
     void removeNodePreservingChildren(PassRefPtr<Node>);
 
 private:
-    PassRefPtr<StyledElement> insertFragmentForTestRendering(Node* rootEditableNode);
+    PassRefPtr<Element> insertFragmentForTestRendering(Node* rootEditableNode);
     void removeUnrenderedNodes(Node*);
-    void restoreAndRemoveTestRenderingNodesToFragment(StyledElement*);
+    void restoreAndRemoveTestRenderingNodesToFragment(Element*);
     void removeInterchangeNodes(Node*);
     
     void insertNodeBefore(PassRefPtr<Node> node, Node* refNode);
@@ -98,8 +98,7 @@
 static bool isInterchangeNewlineNode(const Node *node)
 {
     DEFINE_STATIC_LOCAL(String, interchangeNewlineClassString, (AppleInterchangeNewline));
-    return node && node->hasTagName(brTag) && 
-           static_cast<const Element *>(node)->getAttribute(classAttr) == interchangeNewlineClassString;
+    return node && node->hasTagName(brTag) && toElement(node)->getAttribute(classAttr) == interchangeNewlineClassString;
 }
 
 static bool isInterchangeConvertedSpaceSpan(const Node *node)
@@ -163,7 +162,7 @@
         return;
     }
 
-    RefPtr<StyledElement> holder = insertFragmentForTestRendering(editableRoot.get());
+    RefPtr<Element> holder = insertFragmentForTestRendering(editableRoot.get());
     if (!holder) {
         removeInterchangeNodes(m_fragment.get());
         return;
@@ -244,9 +243,9 @@
     parent->insertBefore(node, refNode, ASSERT_NO_EXCEPTION);
 }
 
-PassRefPtr<StyledElement> ReplacementFragment::insertFragmentForTestRendering(Node* rootEditableElement)
+PassRefPtr<Element> ReplacementFragment::insertFragmentForTestRendering(Node* rootEditableElement)
 {
-    RefPtr<StyledElement> holder = createDefaultParagraphElement(m_document.get());
+    RefPtr<Element> holder = createDefaultParagraphElement(m_document.get());
 
     holder->appendChild(m_fragment, ASSERT_NO_EXCEPTION);
     rootEditableElement->appendChild(holder.get(), ASSERT_NO_EXCEPTION);
@@ -255,7 +254,7 @@
     return holder.release();
 }
 
-void ReplacementFragment::restoreAndRemoveTestRenderingNodesToFragment(StyledElement* holder)
+void ReplacementFragment::restoreAndRemoveTestRenderingNodesToFragment(Element* holder)
 {
     if (!holder)
         return;
@@ -475,7 +474,7 @@
         if (!node->isStyledElement())
             continue;
 
-        StyledElement* element = static_cast<StyledElement*>(node.get());
+        Element* element = toElement(node.get());
 
         const StylePropertySet* inlineStyle = element->inlineStyle();
         RefPtr<EditingStyle> newInlineStyle = EditingStyle::create(inlineStyle);
@@ -487,7 +486,7 @@
                 if (newInlineStyle->conflictsWithImplicitStyleOfElement(htmlElement)) {
                     // e.g. <b style="font-weight: normal;"> is converted to <span style="font-weight: normal;">
                     node = replaceElementWithSpanPreservingChildrenAndAttributes(htmlElement);
-                    element = static_cast<StyledElement*>(node.get());
+                    element = toElement(node.get());
                     insertedNodes.didReplaceNode(htmlElement, node.get());
                 } else if (newInlineStyle->extractConflictingImplicitStyleOfAttributes(htmlElement, EditingStyle::PreserveWritingDirection, 0, attributes,
                     EditingStyle::DoNotExtractMatchingStyle)) {
@@ -627,7 +626,7 @@
         }
 
         if (isHeaderElement(node.get())) {
-            if (HTMLElement* headerElement = static_cast<HTMLElement*>(highestEnclosingNodeOfType(positionInParentBeforeNode(node.get()), isHeaderElement)))
+            if (HTMLElement* headerElement = toHTMLElement(highestEnclosingNodeOfType(positionInParentBeforeNode(node.get()), isHeaderElement)))
                 moveNodeOutOfAncestor(node, headerElement);
         }
     }
@@ -638,6 +637,9 @@
     RefPtr<Node> node = prpNode;
     RefPtr<Node> ancestor = prpAncestor;
 
+    if (!ancestor->parentNode()->rendererIsEditable())
+        return;
+
     VisiblePosition positionAtEndOfNode = lastPositionInOrAfterNode(node.get());
     VisiblePosition lastPositionInParagraph = lastPositionInNode(ancestor.get());
     if (positionAtEndOfNode == lastPositionInParagraph) {
diff --git a/Source/core/editing/SmartReplaceICU.cpp b/Source/core/editing/SmartReplaceICU.cpp
index 8428054..fe46581 100644
--- a/Source/core/editing/SmartReplaceICU.cpp
+++ b/Source/core/editing/SmartReplaceICU.cpp
@@ -39,7 +39,7 @@
 
 static void addAllCodePoints(USet* smartSet, const String& string)
 {
-    const UChar* characters = string.characters();
+    const UChar* characters = string.bloatedCharacters();
     for (size_t i = 0; i < string.length(); i++)
         uset_add(smartSet, characters[i]);
 }
@@ -55,7 +55,7 @@
         // Whitespace and newline (kCFCharacterSetWhitespaceAndNewline)
         UErrorCode ec = U_ZERO_ERROR;
         String whitespaceAndNewline = ASCIILiteral("[[:WSpace:] [\\u000A\\u000B\\u000C\\u000D\\u0085]]");
-        smartSet = uset_openPattern(whitespaceAndNewline.characters(), whitespaceAndNewline.length(), &ec);
+        smartSet = uset_openPattern(whitespaceAndNewline.bloatedCharacters(), whitespaceAndNewline.length(), &ec);
         ASSERT(U_SUCCESS(ec));
 
         // CJK ranges
@@ -79,7 +79,7 @@
             // Punctuation (kCFCharacterSetPunctuation)
             UErrorCode ec = U_ZERO_ERROR;
             String punctuationClass = ASCIILiteral("[:P:]");
-            USet* icuPunct = uset_openPattern(punctuationClass.characters(), punctuationClass.length(), &ec);
+            USet* icuPunct = uset_openPattern(punctuationClass.bloatedCharacters(), punctuationClass.length(), &ec);
             ASSERT(U_SUCCESS(ec));
             uset_addAll(smartSet, icuPunct);
             uset_close(icuPunct);
diff --git a/Source/core/editing/SpellChecker.h b/Source/core/editing/SpellChecker.h
index b5d2484..a3f48d9 100644
--- a/Source/core/editing/SpellChecker.h
+++ b/Source/core/editing/SpellChecker.h
@@ -30,12 +30,11 @@
 #include "core/dom/Range.h"
 #include "core/platform/Timer.h"
 #include "core/platform/text/TextChecking.h"
-#include <wtf/Deque.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Vector.h>
+#include "wtf/Deque.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/editing/TextCheckingHelper.cpp b/Source/core/editing/TextCheckingHelper.cpp
index a4595f1..5cd787a 100644
--- a/Source/core/editing/TextCheckingHelper.cpp
+++ b/Source/core/editing/TextCheckingHelper.cpp
@@ -339,7 +339,7 @@
                 
                 Vector<TextCheckingResult> results;
                 TextCheckingTypeMask checkingTypes = checkGrammar ? (TextCheckingTypeSpelling | TextCheckingTypeGrammar) : TextCheckingTypeSpelling;
-                checkTextOfParagraph(m_client->textChecker(), paragraphString.characters(), paragraphString.length(), checkingTypes, results);
+                checkTextOfParagraph(m_client->textChecker(), paragraphString.bloatedCharacters(), paragraphString.length(), checkingTypes, results);
                 
                 for (unsigned i = 0; i < results.size(); i++) {
                     const TextCheckingResult* result = &results[i];
diff --git a/Source/core/editing/TextCheckingHelper.h b/Source/core/editing/TextCheckingHelper.h
index b38b45b..95ca2c5 100644
--- a/Source/core/editing/TextCheckingHelper.h
+++ b/Source/core/editing/TextCheckingHelper.h
@@ -45,7 +45,7 @@
 
     int textLength() const { return text().length(); }
     String textSubstring(unsigned pos, unsigned len = INT_MAX) const { return text().substring(pos, len); }
-    const UChar* textCharacters() const { return text().characters(); }
+    const UChar* textCharacters() const { return text().bloatedCharacters(); }
     UChar textCharAt(int index) const { return text()[static_cast<unsigned>(index)]; }
 
     bool isEmpty() const;
diff --git a/Source/core/editing/TextIterator.cpp b/Source/core/editing/TextIterator.cpp
index cf776be..7e90478 100644
--- a/Source/core/editing/TextIterator.cpp
+++ b/Source/core/editing/TextIterator.cpp
@@ -835,10 +835,10 @@
 
 static int collapsedSpaceLength(RenderText* renderer, int textEnd)
 {
-    const UChar* characters = renderer->text()->characters();
-    int length = renderer->text()->length();
+    const String& text = renderer->text();
+    int length = text.length();
     for (int i = textEnd; i < length; ++i) {
-        if (!renderer->style()->isCollapsibleWhiteSpace(characters[i]))
+        if (!renderer->style()->isCollapsibleWhiteSpace(text[i]))
             return i - textEnd;
     }
 
@@ -1249,9 +1249,9 @@
     ASSERT(m_positionStartOffset <= m_positionEndOffset);
 
     m_textLength = m_positionEndOffset - m_positionStartOffset;
-    m_textCharacters = text.characters() + (m_positionStartOffset - offsetInNode);
-    ASSERT(m_textCharacters >= text.characters());
-    RELEASE_ASSERT(m_textCharacters + m_textLength <= text.characters() + static_cast<int>(text.length()));
+    m_textCharacters = text.bloatedCharacters() + (m_positionStartOffset - offsetInNode);
+    ASSERT(m_textCharacters >= text.bloatedCharacters());
+    RELEASE_ASSERT(m_textCharacters + m_textLength <= text.bloatedCharacters() + static_cast<int>(text.length()));
 
     m_lastCharacter = text[m_positionEndOffset - 1];
 
@@ -1862,10 +1862,9 @@
 
 static inline bool containsKanaLetters(const String& pattern)
 {
-    const UChar* characters = pattern.characters();
     unsigned length = pattern.length();
     for (unsigned i = 0; i < length; ++i) {
-        if (isKanaLetter(characters[i]))
+        if (isKanaLetter(pattern[i]))
             return true;
     }
     return false;
@@ -1947,7 +1946,7 @@
 
     if ((m_options & AtWordStarts) && targetLength) {
         UChar32 targetFirstCharacter;
-        U16_GET(m_target.characters(), 0, 0, targetLength, targetFirstCharacter);
+        U16_GET(m_target.bloatedCharacters(), 0, 0, targetLength, targetFirstCharacter);
         // Characters in the separator category never really occur at the beginning of a word,
         // so if the target begins with such a character, we just ignore the AtWordStart option.
         if (isSeparator(targetFirstCharacter)) {
@@ -1971,12 +1970,12 @@
     }
 
     UErrorCode status = U_ZERO_ERROR;
-    usearch_setPattern(searcher, m_target.characters(), targetLength, &status);
+    usearch_setPattern(searcher, m_target.bloatedCharacters(), targetLength, &status);
     ASSERT(status == U_ZERO_ERROR);
 
     // The kana workaround requires a normalized copy of the target string.
     if (m_targetRequiresKanaWorkaround)
-        normalizeCharacters(m_target.characters(), m_target.length(), m_normalizedTarget);
+        normalizeCharacters(m_target.bloatedCharacters(), m_target.length(), m_normalizedTarget);
 }
 
 inline SearchBuffer::~SearchBuffer()
@@ -2313,9 +2312,9 @@
         return 0;
 
     size_t tailSpace = m_target.length() - m_cursor;
-    if (memcmp(&m_buffer[m_cursor], m_target.characters(), tailSpace * sizeof(UChar)) != 0)
+    if (memcmp(&m_buffer[m_cursor], m_target.bloatedCharacters(), tailSpace * sizeof(UChar)) != 0)
         return 0;
-    if (memcmp(&m_buffer[0], m_target.characters() + tailSpace, m_cursor * sizeof(UChar)) != 0)
+    if (memcmp(&m_buffer[0], m_target.bloatedCharacters() + tailSpace, m_cursor * sizeof(UChar)) != 0)
         return 0;
 
     start = length();
@@ -2485,19 +2484,16 @@
 String plainText(const Range* r, TextIteratorBehavior defaultBehavior, bool isDisplayString)
 {
     // The initial buffer size can be critical for performance: https://bugs.webkit.org/show_bug.cgi?id=81192
-    static const unsigned cMaxSegmentSize = 1 << 15;
+    static const unsigned initialCapacity = 1 << 15;
 
     unsigned bufferLength = 0;
     StringBuilder builder;
-    builder.reserveCapacity(cMaxSegmentSize);
+    builder.reserveCapacity(initialCapacity);
     TextIteratorBehavior behavior = defaultBehavior;
     if (!isDisplayString)
         behavior = static_cast<TextIteratorBehavior>(behavior | TextIteratorEmitsTextsWithoutTranscoding);
     
     for (TextIterator it(r, behavior); !it.atEnd(); it.advance()) {
-        if (builder.capacity() < builder.length() + it.length())
-            builder.reserveCapacity(builder.capacity() + cMaxSegmentSize);
-
         it.appendTextToStringBuilder(builder);
         bufferLength += it.length();
     }
diff --git a/Source/core/editing/TextIterator.h b/Source/core/editing/TextIterator.h
index 6f49502..0bc5c97 100644
--- a/Source/core/editing/TextIterator.h
+++ b/Source/core/editing/TextIterator.h
@@ -93,7 +93,7 @@
     void advance();
     
     int length() const { return m_textLength; }
-    const UChar* characters() const { return m_textCharacters ? m_textCharacters : m_text.characters() + startOffset(); }
+    const UChar* characters() const { return m_textCharacters ? m_textCharacters : m_text.bloatedCharacters() + startOffset(); }
     UChar characterAt(unsigned index) const;
     void appendTextToStringBuilder(StringBuilder&) const;
     
diff --git a/Source/core/editing/TypingCommand.cpp b/Source/core/editing/TypingCommand.cpp
index e544de0..7f04841 100644
--- a/Source/core/editing/TypingCommand.cpp
+++ b/Source/core/editing/TypingCommand.cpp
@@ -160,7 +160,7 @@
     ASSERT(frame);
 
     if (!text.isEmpty())
-        document->frame()->editor()->updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text.characters()[0]));
+        document->frame()->editor()->updateMarkersForWordsAffectedByEditing(isSpaceOrNewline(text[0]));
     
     insertText(document, text, frame->selection()->selection(), options, composition);
 }
diff --git a/Source/core/editing/VisiblePosition.cpp b/Source/core/editing/VisiblePosition.cpp
index fab43a4..df1efaa 100644
--- a/Source/core/editing/VisiblePosition.cpp
+++ b/Source/core/editing/VisiblePosition.cpp
@@ -587,10 +587,7 @@
     if (offset >= length)
         return 0;
 
-    UChar32 ch;
-    const UChar* characters = textNode->data().characters();
-    U16_NEXT(characters, offset, length, ch);
-    return ch;
+    return textNode->data().characterStartingAt(offset);
 }
 
 LayoutRect VisiblePosition::localCaretRect(RenderObject*& renderer) const
diff --git a/Source/core/editing/VisibleUnits.cpp b/Source/core/editing/VisibleUnits.cpp
index 689d495..5409467 100644
--- a/Source/core/editing/VisibleUnits.cpp
+++ b/Source/core/editing/VisibleUnits.cpp
@@ -20,7 +20,7 @@
  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
 #include "config.h"
@@ -40,7 +40,6 @@
 #include "core/rendering/InlineTextBox.h"
 #include "core/rendering/RenderBlock.h"
 #include "core/rendering/RenderObject.h"
-#include <wtf/unicode/Unicode.h>
 
 namespace WebCore {
 
@@ -63,7 +62,7 @@
 {
     if (!node)
         return 0;
-    
+
     bool editable = node->rendererIsEditable(editableType);
     node = node->nextLeafNode();
     while (node) {
@@ -89,7 +88,7 @@
 
         Position pos = previousNode->hasTagName(brTag) ? positionBeforeNode(previousNode) :
             createLegacyEditingPosition(previousNode, caretMaxOffset(previousNode));
-        
+
         if (pos.isCandidate())
             return pos;
 
@@ -111,7 +110,7 @@
 
         Position pos;
         pos = createLegacyEditingPosition(nextNode, caretMinOffset(nextNode));
-        
+
         if (pos.isCandidate())
             return pos;
 
@@ -129,7 +128,7 @@
 
     size_t size() const { return m_leafBoxes.size(); }
     const InlineBox* firstBox() const { return m_leafBoxes[0]; }
-    
+
 private:
     const Vector<InlineBox*>& collectBoxes(const RootInlineBox*);
     int boxIndexInLeaves(const InlineTextBox*) const;
@@ -293,14 +292,14 @@
     string.clear();
     if (previousBox) {
         previousBoxLength = previousBox->len();
-        string.append(previousBox->textRenderer()->text()->characters() + previousBox->start(), previousBoxLength); 
+        string.append(previousBox->textRenderer()->text()->bloatedCharacters() + previousBox->start(), previousBoxLength);
         len += previousBoxLength;
     }
-    string.append(textBox->textRenderer()->text()->characters() + textBox->start(), textBox->len());
+    string.append(textBox->textRenderer()->text()->bloatedCharacters() + textBox->start(), textBox->len());
     len += textBox->len();
 
     return wordBreakIterator(string.data(), len);
-} 
+}
 
 static TextBreakIterator* wordBreakIteratorForMaxOffsetBoundary(const VisiblePosition& visiblePosition, const InlineTextBox* textBox,
     bool& nextBoxInDifferentBlock, Vector<UChar, 1024>& string, CachedLogicallyOrderedLeafBoxes& leafBoxes)
@@ -312,15 +311,15 @@
 
     int len = 0;
     string.clear();
-    string.append(textBox->textRenderer()->text()->characters() + textBox->start(), textBox->len());
+    string.append(textBox->textRenderer()->text()->bloatedCharacters() + textBox->start(), textBox->len());
     len += textBox->len();
     if (nextBox) {
-        string.append(nextBox->textRenderer()->text()->characters() + nextBox->start(), nextBox->len()); 
+        string.append(nextBox->textRenderer()->text()->bloatedCharacters() + nextBox->start(), nextBox->len());
         len += nextBox->len();
     }
 
     return wordBreakIterator(string.data(), len);
-} 
+}
 
 static bool isLogicalStartOfWord(TextBreakIterator* iter, int position, bool hardLineBreak)
 {
@@ -341,7 +340,7 @@
 
 enum CursorMovementDirection { MoveLeft, MoveRight };
 
-static VisiblePosition visualWordPosition(const VisiblePosition& visiblePosition, CursorMovementDirection direction, 
+static VisiblePosition visualWordPosition(const VisiblePosition& visiblePosition, CursorMovementDirection direction,
     bool skipsSpaceWhenMovingRight)
 {
     if (visiblePosition.isNull())
@@ -356,14 +355,14 @@
     Vector<UChar, 1024> string;
 
     while (1) {
-        VisiblePosition adjacentCharacterPosition = direction == MoveRight ? current.right(true) : current.left(true); 
+        VisiblePosition adjacentCharacterPosition = direction == MoveRight ? current.right(true) : current.left(true);
         if (adjacentCharacterPosition == current || adjacentCharacterPosition.isNull())
             return VisiblePosition();
-    
+
         InlineBox* box;
         int offsetInBox;
         adjacentCharacterPosition.deepEquivalent().getInlineBoxAndOffset(UPSTREAM, box, offsetInBox);
-    
+
         if (!box)
             break;
         if (!box->isInlineTextBox()) {
@@ -382,7 +381,7 @@
         else if (offsetInBox == box->caretMaxOffset())
             iter = wordBreakIteratorForMaxOffsetBoundary(visiblePosition, textBox, nextBoxInDifferentBlock, string, leafBoxes);
         else if (movingIntoNewBox) {
-            iter = wordBreakIterator(textBox->textRenderer()->text()->characters() + textBox->start(), textBox->len());
+            iter = wordBreakIterator(textBox->textRenderer()->text()->bloatedCharacters() + textBox->start(), textBox->len());
             previouslyVisitedBox = box;
         }
 
@@ -402,11 +401,11 @@
         } else {
             bool logicalEndInRenderer = offsetInBox == static_cast<int>(textBox->start() + textBox->len()) && nextBoxInDifferentBlock;
             isWordBreak = islogicalEndOfWord(iter, offsetInIterator, logicalEndInRenderer);
-        }      
+        }
 
         if (isWordBreak)
             return adjacentCharacterPosition;
-    
+
         current = adjacentCharacterPosition;
     }
     return VisiblePosition();
@@ -416,7 +415,7 @@
 {
     VisiblePosition leftWordBreak = visualWordPosition(visiblePosition, MoveLeft, skipsSpaceWhenMovingRight);
     leftWordBreak = visiblePosition.honorEditingBoundaryAtOrBefore(leftWordBreak);
-    
+
     // FIXME: How should we handle a non-editable position?
     if (leftWordBreak.isNull() && isEditablePosition(visiblePosition.deepEquivalent())) {
         TextDirection blockDirection = directionOfEnclosingBlock(visiblePosition.deepEquivalent());
@@ -454,7 +453,7 @@
     Position start = createLegacyEditingPosition(boundary, 0).parentAnchoredEquivalent();
     Position end = pos.parentAnchoredEquivalent();
     RefPtr<Range> searchRange = Range::create(d);
-    
+
     Vector<UChar, 1024> string;
     unsigned suffixLength = 0;
 
@@ -489,13 +488,13 @@
     bool needMoreContext = false;
     while (!it.atEnd()) {
         // iterate to get chunks until the searchFunction returns a non-zero value.
-        if (!inTextSecurityMode) 
+        if (!inTextSecurityMode)
             string.prepend(it.characters(), it.length());
         else {
             // Treat bullets used in the text security mode as regular characters when looking for boundaries
             String iteratorString(it.characters(), it.length());
             iteratorString.fill('x');
-            string.prepend(iteratorString.characters(), iteratorString.length());
+            string.prepend(iteratorString.bloatedCharacters(), iteratorString.length());
         }
         next = searchFunction(string.data(), string.size(), string.size() - suffixLength, MayHaveMoreContext, needMoreContext);
         if (next)
@@ -569,7 +568,7 @@
             // Treat bullets used in the text security mode as regular characters when looking for boundaries
             String iteratorString(it.characters(), it.length());
             iteratorString.fill('x');
-            string.append(iteratorString.characters(), iteratorString.length());
+            string.append(iteratorString.bloatedCharacters(), iteratorString.length());
         }
         next = searchFunction(string.data(), string.size(), prefixLength, MayHaveMoreContext, needMoreContext);
         if (next != string.size())
@@ -582,7 +581,7 @@
         next = searchFunction(string.data(), string.size(), prefixLength, DontHaveMoreContext, needMoreContext);
         ASSERT(!needMoreContext);
     }
-    
+
     if (it.atEnd() && next == string.size()) {
         pos = it.range()->startPosition();
     } else if (next != prefixLength) {
@@ -591,7 +590,7 @@
         charIt.advance(next - prefixLength - 1);
         RefPtr<Range> characterRange = charIt.range();
         pos = characterRange->endPosition();
-        
+
         if (*charIt.characters() == '\n') {
             // FIXME: workaround for collapsed range (where only start position is correct) emitted for some emitted newlines (see rdar://5192593)
             VisiblePosition visPos = VisiblePosition(pos);
@@ -631,7 +630,7 @@
         // at paragraph end, the startofWord is the current position
         if (isEndOfParagraph(c))
             return c;
-        
+
         p = c.next();
         if (p.isNull())
             return c;
@@ -658,13 +657,13 @@
     if (side == LeftWordIfOnBoundary) {
         if (isStartOfParagraph(c))
             return c;
-            
+
         p = c.previous();
         if (p.isNull())
             return c;
     } else if (isEndOfParagraph(c))
         return c;
-    
+
     return nextBoundary(p, endWordBoundary);
 }
 
@@ -696,7 +695,7 @@
 
 VisiblePosition nextWordPosition(const VisiblePosition &c)
 {
-    VisiblePosition next = nextBoundary(c, nextWordPositionBoundary);    
+    VisiblePosition next = nextBoundary(c, nextWordPositionBoundary);
     return c.honorEditingBoundaryAtOrAfter(next);
 }
 
@@ -817,7 +816,7 @@
             endNode = endRenderer->nonPseudoNode();
             if (endNode)
                 break;
-            
+
             endBox = endBox->prevLeafChild();
         }
     }
@@ -833,7 +832,7 @@
         pos = Position(toText(endNode), endOffset);
     } else
         pos = positionAfterNode(endNode);
-    
+
     return VisiblePosition(pos, VP_UPSTREAM_IF_POSSIBLE);
 }
 
@@ -850,7 +849,7 @@
 
     if (mode == UseLogicalOrdering) {
         // Make sure the end of line is at the same line as the given input position. For a wrapping line, the logical end
-        // position for the not-last-2-lines might incorrectly hand back the logical beginning of the next line. 
+        // position for the not-last-2-lines might incorrectly hand back the logical beginning of the next line.
         // For example, <div contenteditable dir="rtl" style="line-break:before-white-space">abcdefg abcdefg abcdefg
         // a abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg abcdefg </div>
         // In this case, use the previous position of the computed logical end position.
@@ -865,18 +864,18 @@
         return c.honorEditingBoundaryAtOrAfter(visPos);
     }
 
-    // Make sure the end of line is at the same line as the given input position. Else use the previous position to 
-    // obtain end of line. This condition happens when the input position is before the space character at the end 
+    // Make sure the end of line is at the same line as the given input position. Else use the previous position to
+    // obtain end of line. This condition happens when the input position is before the space character at the end
     // of a soft-wrapped non-editable line. In this scenario, endPositionForLine would incorrectly hand back a position
     // in the next line instead. This fix is to account for the discrepancy between lines with webkit-line-break:after-white-space style
-    // versus lines without that style, which would break before a space by default. 
+    // versus lines without that style, which would break before a space by default.
     if (!inSameLine(c, visPos)) {
         visPos = c.previous();
         if (visPos.isNull())
             return VisiblePosition();
         visPos = endPositionForLine(visPos, UseInlineBoxOrdering);
     }
-    
+
     return c.honorEditingBoundaryAtOrAfter(visPos);
 }
 
@@ -927,9 +926,9 @@
 
     if (!node)
         return VisiblePosition();
-    
+
     node->document()->updateLayoutIgnorePendingStylesheets();
-    
+
     RenderObject* renderer = node->renderer();
     if (!renderer)
         return VisiblePosition();
@@ -955,7 +954,7 @@
                 return position;
         }
     }
-    
+
     if (root) {
         // FIXME: Can be wrong for multi-column layout and with transforms.
         IntPoint pointInLine = absoluteLineDirectionPointToLocalPointInBlock(root, lineDirectionPoint);
@@ -965,7 +964,7 @@
             return positionInParentBeforeNode(node);
         return renderer->positionForPoint(pointInLine);
     }
-    
+
     // Could not find a previous line. This means we must already be on the first line.
     // Move to the start of the content in this block, which effectively moves us
     // to the start of the line we're on.
@@ -982,7 +981,7 @@
 
     if (!node)
         return VisiblePosition();
-    
+
     node->document()->updateLayoutIgnorePendingStylesheets();
 
     RenderObject* renderer = node->renderer();
@@ -1013,7 +1012,7 @@
                 return position;
         }
     }
-    
+
     if (root) {
         // FIXME: Can be wrong for multi-column layout and with transforms.
         IntPoint pointInLine = absoluteLineDirectionPointToLocalPointInBlock(root, lineDirectionPoint);
@@ -1075,7 +1074,7 @@
 
 static unsigned nextSentencePositionBoundary(const UChar* characters, unsigned length, unsigned, BoundarySearchContextAvailability, bool&)
 {
-    // FIXME: This is identical to endSentenceBoundary. This isn't right, it needs to 
+    // FIXME: This is identical to endSentenceBoundary. This isn't right, it needs to
     // move to the equivlant position in the following sentence.
     TextBreakIterator* iterator = sentenceBreakIterator(characters, length);
     return textBreakFollowing(iterator, 0);
@@ -1083,7 +1082,7 @@
 
 VisiblePosition nextSentencePosition(const VisiblePosition &c)
 {
-    VisiblePosition next = nextBoundary(c, nextSentencePositionBoundary);    
+    VisiblePosition next = nextBoundary(c, nextSentencePositionBoundary);
     return c.honorEditingBoundaryAtOrAfter(next);
 }
 
@@ -1094,7 +1093,7 @@
 
     if (!startNode)
         return VisiblePosition();
-    
+
     if (isRenderedAsNonInlineTableImageOrHR(startNode))
         return positionBeforeNode(startNode);
 
@@ -1129,7 +1128,7 @@
             n = NodeTraversal::previousPostOrder(n, startBlock);
             continue;
         }
-        
+
         if (r->isBR() || isBlock(n))
             break;
 
@@ -1167,7 +1166,7 @@
 }
 
 VisiblePosition endOfParagraph(const VisiblePosition &c, EditingBoundaryCrossingRule boundaryCrossingRule)
-{    
+{
     if (c.isNull())
         return VisiblePosition();
 
@@ -1176,10 +1175,10 @@
 
     if (isRenderedAsNonInlineTableImageOrHR(startNode))
         return positionAfterNode(startNode);
-    
+
     Node* startBlock = enclosingBlock(startNode);
     Node* stayInsideBlock = startBlock;
-    
+
     Node* node = startNode;
     Node* highestRoot = highestEditableRoot(p);
     int offset = p.deprecatedEditingOffset();
@@ -1210,7 +1209,7 @@
             n = NodeTraversal::next(n, stayInsideBlock);
             continue;
         }
-        
+
         if (r->isBR() || isBlock(n))
             break;
 
@@ -1336,7 +1335,7 @@
 {
     if (!node || !node->document() || !node->document()->documentElement())
         return VisiblePosition();
-    
+
     return VisiblePosition(firstPositionInNode(node->document()->documentElement()), DOWNSTREAM);
 }
 
@@ -1349,7 +1348,7 @@
 {
     if (!node || !node->document() || !node->document()->documentElement())
         return VisiblePosition();
-    
+
     Element* doc = node->document()->documentElement();
     return VisiblePosition(lastPositionInNode(doc), DOWNSTREAM);
 }
diff --git a/Source/core/editing/VisibleUnits.h b/Source/core/editing/VisibleUnits.h
index 666b034..a4b914b 100644
--- a/Source/core/editing/VisibleUnits.h
+++ b/Source/core/editing/VisibleUnits.h
@@ -26,9 +26,7 @@
 #ifndef VisibleUnits_h
 #define VisibleUnits_h
 
-#include "core/editing/EditingBehaviorTypes.h"
 #include "core/editing/EditingBoundary.h"
-#include "core/platform/text/TextBreakIterator.h"
 #include "core/platform/text/TextDirection.h"
 
 namespace WebCore {
diff --git a/Source/core/editing/htmlediting.cpp b/Source/core/editing/htmlediting.cpp
index 9fcf246..e09f35a 100644
--- a/Source/core/editing/htmlediting.cpp
+++ b/Source/core/editing/htmlediting.cpp
@@ -895,7 +895,7 @@
 
 bool isTabSpanNode(const Node *node)
 {
-    return node && node->hasTagName(spanTag) && node->isElementNode() && static_cast<const Element *>(node)->getAttribute(classAttr) == AppleTabSpanClass;
+    return node && node->hasTagName(spanTag) && node->isElementNode() && toElement(node)->getAttribute(classAttr) == AppleTabSpanClass;
 }
 
 bool isTabSpanTextNode(const Node *node)
@@ -1007,7 +1007,7 @@
     if (!node || !node->hasTagName(blockquoteTag))
         return false;
         
-    return static_cast<const Element *>(node)->getAttribute("type") == "cite";
+    return toElement(node)->getAttribute("type") == "cite";
 }
 
 int caretMinOffset(const Node* n)
diff --git a/Source/core/editing/markup.cpp b/Source/core/editing/markup.cpp
index 2e35127..b16678e 100644
--- a/Source/core/editing/markup.cpp
+++ b/Source/core/editing/markup.cpp
@@ -32,19 +32,13 @@
 #include "CSSPropertyNames.h"
 #include "CSSValueKeywords.h"
 #include "HTMLNames.h"
-#include "XMLNSNames.h"
 #include "core/css/CSSPrimitiveValue.h"
-#include "core/css/CSSRule.h"
-#include "core/css/CSSRuleList.h"
-#include "core/css/CSSStyleRule.h"
 #include "core/css/CSSValue.h"
 #include "core/css/StylePropertySet.h"
-#include "core/css/resolver/StyleResolver.h"
 #include "core/dom/CDATASection.h"
 #include "core/dom/ChildListMutationScope.h"
 #include "core/dom/ContextFeatures.h"
 #include "core/dom/DocumentFragment.h"
-#include "core/dom/DocumentType.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/ExceptionCodePlaceholder.h"
 #include "core/dom/NodeTraversal.h"
@@ -59,13 +53,10 @@
 #include "core/html/HTMLElement.h"
 #include "core/html/HTMLTextFormControlElement.h"
 #include "core/page/Frame.h"
-#include "core/page/Settings.h"
-#include "core/rendering/RenderBlock.h"
 #include "core/rendering/RenderObject.h"
 #include "weborigin/KURL.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/text/StringBuilder.h"
-#include "wtf/unicode/CharacterNames.h"
 
 using namespace std;
 
@@ -308,8 +299,8 @@
         } else
             newInlineStyle = EditingStyle::create();
 
-        if (element->isStyledElement() && static_cast<StyledElement*>(element)->inlineStyle())
-            newInlineStyle->overrideWithStyle(static_cast<StyledElement*>(element)->inlineStyle());
+        if (element->isStyledElement() && element->inlineStyle())
+            newInlineStyle->overrideWithStyle(element->inlineStyle());
 
         if (shouldAnnotateOrForceInline) {
             if (shouldAnnotate())
diff --git a/Source/core/editing/markup.h b/Source/core/editing/markup.h
index 24795e2..0afcae9 100644
--- a/Source/core/editing/markup.h
+++ b/Source/core/editing/markup.h
@@ -26,7 +26,7 @@
 #ifndef markup_h
 #define markup_h
 
-#include "core/dom/FragmentScriptingPermission.h"
+#include "core/dom/ParserContentPolicy.h"
 #include "core/editing/HTMLInterchange.h"
 #include <wtf/Forward.h>
 #include <wtf/Vector.h>
diff --git a/Source/core/features.gypi b/Source/core/features.gypi
index ccf0e3c..3c0d1c1 100644
--- a/Source/core/features.gypi
+++ b/Source/core/features.gypi
@@ -38,11 +38,11 @@
       'ENABLE_CSS_REGIONS=1',
       'ENABLE_CUSTOM_SCHEME_HANDLER=0',
       'ENABLE_ENCRYPTED_MEDIA_V2=1',
-      'ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=<(enable_graphics_context_annotations)',
       'ENABLE_SVG_FONTS=1',
       'ENABLE_TOUCH_ICON_LOADING=<(enable_touch_icon_loading)',
       'ENABLE_XHR_TIMEOUT=0',
       'ENABLE_GDI_FONTS_ON_WINDOWS=1',
+      'ENABLE_PARTITION_ALLOC=1',
       # WTF_USE_DYNAMIC_ANNOTATIONS=1 may be defined in build/common.gypi
       # We can't define it here because it should be present only
       # in Debug or release_valgrind_build=1 builds.
@@ -50,10 +50,8 @@
     # We have to nest variables inside variables so that they can be overridden
     # through GYP_DEFINES.
     'variables': {
-      'enable_graphics_context_annotations%': 0,
       'enable_touch_icon_loading%' : 0,
     },
-    'enable_graphics_context_annotations%': '<(enable_graphics_context_annotations)',
     'conditions': [
       ['use_concatenated_impulse_responses==1', {
         # Use concatenated HRTF impulse responses
@@ -132,11 +130,6 @@
           'ENABLE_DEFAULT_RENDER_THEME=1',
         ],
       }],
-      ['OS!="win"', {
-        'feature_defines': [
-          'ENABLE_PARTITION_ALLOC=1',
-        ],
-      }],
     ],
   },
 }
diff --git a/Source/core/fileapi/Blob.cpp b/Source/core/fileapi/Blob.cpp
index b395271..f93b428 100644
--- a/Source/core/fileapi/Blob.cpp
+++ b/Source/core/fileapi/Blob.cpp
@@ -31,9 +31,9 @@
 #include "config.h"
 #include "core/fileapi/Blob.h"
 
+#include "core/fileapi/BlobRegistry.h"
 #include "core/fileapi/BlobURL.h"
 #include "core/fileapi/File.h"
-#include "core/fileapi/ThreadableBlobRegistry.h"
 
 namespace WebCore {
 
@@ -49,12 +49,12 @@
 void BlobURLRegistry::registerURL(SecurityOrigin* origin, const KURL& publicURL, URLRegistrable* blob)
 {
     ASSERT(&blob->registry() == this);
-    ThreadableBlobRegistry::registerBlobURL(origin, publicURL, static_cast<Blob*>(blob)->url());
+    BlobRegistry::registerBlobURL(origin, publicURL, static_cast<Blob*>(blob)->url());
 }
 
 void BlobURLRegistry::unregisterURL(const KURL& url)
 {
-    ThreadableBlobRegistry::unregisterBlobURL(url);
+    BlobRegistry::unregisterBlobURL(url);
 }
 
 URLRegistry& BlobURLRegistry::registry()
@@ -72,7 +72,7 @@
 
     // Create a new internal URL and register it with the provided blob data.
     m_internalURL = BlobURL::createInternalURL();
-    ThreadableBlobRegistry::registerBlobURL(m_internalURL, blobData.release());
+    BlobRegistry::registerBlobURL(m_internalURL, blobData.release());
 }
 
 Blob::Blob(PassOwnPtr<BlobData> blobData, long long size)
@@ -84,7 +84,7 @@
 
     // Create a new internal URL and register it with the provided blob data.
     m_internalURL = BlobURL::createInternalURL();
-    ThreadableBlobRegistry::registerBlobURL(m_internalURL, blobData);
+    BlobRegistry::registerBlobURL(m_internalURL, blobData);
 }
 
 Blob::Blob(const KURL& srcURL, const String& type, long long size)
@@ -95,12 +95,12 @@
 
     // Create a new internal URL and register it with the same blob data as the source URL.
     m_internalURL = BlobURL::createInternalURL();
-    ThreadableBlobRegistry::registerBlobURL(0, m_internalURL, srcURL);
+    BlobRegistry::registerBlobURL(0, m_internalURL, srcURL);
 }
 
 Blob::~Blob()
 {
-    ThreadableBlobRegistry::unregisterBlobURL(m_internalURL);
+    BlobRegistry::unregisterBlobURL(m_internalURL);
 }
 
 PassRefPtr<Blob> Blob::slice(long long start, long long end, const String& contentType) const
diff --git a/Source/core/fileapi/Blob.h b/Source/core/fileapi/Blob.h
index aca134e..958aa28 100644
--- a/Source/core/fileapi/Blob.h
+++ b/Source/core/fileapi/Blob.h
@@ -38,7 +38,6 @@
 #include "wtf/PassOwnPtr.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
diff --git a/Source/core/fileapi/Blob.idl b/Source/core/fileapi/Blob.idl
index 3f61283..8dddc35 100644
--- a/Source/core/fileapi/Blob.idl
+++ b/Source/core/fileapi/Blob.idl
@@ -29,7 +29,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     CustomToV8,
     CustomConstructor,
     CustomConstructor(sequence<any> blobParts, optional BlobPropertyBag options)
diff --git a/Source/core/fileapi/BlobBuilder.cpp b/Source/core/fileapi/BlobBuilder.cpp
index 4782929..039c8af 100644
--- a/Source/core/fileapi/BlobBuilder.cpp
+++ b/Source/core/fileapi/BlobBuilder.cpp
@@ -60,7 +60,7 @@
 
 void BlobBuilder::append(const String& text, const String& endingType)
 {
-    CString utf8Text = UTF8Encoding().encode(text.characters(), text.length(), WTF::EntitiesForUnencodables);
+    CString utf8Text = UTF8Encoding().encode(text, WTF::EntitiesForUnencodables);
 
     Vector<char>& buffer = getBuffer();
     size_t oldSize = buffer.size();
diff --git a/Source/core/fileapi/BlobBuilder.h b/Source/core/fileapi/BlobBuilder.h
index c9c75be..6e57f30 100644
--- a/Source/core/fileapi/BlobBuilder.h
+++ b/Source/core/fileapi/BlobBuilder.h
@@ -32,8 +32,7 @@
 #define BlobBuilder_h
 
 #include "core/platform/network/BlobData.h"
-#include <wtf/Forward.h>
-#include <wtf/RefCounted.h>
+#include "wtf/Forward.h"
 
 namespace WTF{
 class TextEncoding;
diff --git a/Source/core/fileapi/BlobRegistry.cpp b/Source/core/fileapi/BlobRegistry.cpp
new file mode 100644
index 0000000..1d825b5
--- /dev/null
+++ b/Source/core/fileapi/BlobRegistry.cpp
@@ -0,0 +1,257 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/fileapi/BlobRegistry.h"
+
+#include "core/fileapi/BlobURL.h"
+#include "core/platform/network/BlobData.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebBlobData.h"
+#include "public/platform/WebBlobRegistry.h"
+#include "public/platform/WebString.h"
+#include "public/platform/WebThreadSafeData.h"
+#include "weborigin/SecurityOrigin.h"
+#include "weborigin/SecurityOriginCache.h"
+#include "wtf/Assertions.h"
+#include "wtf/HashMap.h"
+#include "wtf/MainThread.h"
+#include "wtf/RefPtr.h"
+#include "wtf/ThreadSpecific.h"
+#include "wtf/text/StringHash.h"
+#include "wtf/text/WTFString.h"
+
+using WebKit::WebBlobData;
+using WebKit::WebBlobRegistry;
+using WebKit::WebThreadSafeData;
+using WTF::ThreadSpecific;
+
+namespace WebCore {
+
+class BlobOriginCache : public SecurityOriginCache {
+public:
+    BlobOriginCache();
+    virtual SecurityOrigin* cachedOrigin(const KURL&) OVERRIDE;
+};
+
+struct BlobRegistryContext {
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    BlobRegistryContext(const KURL& url, PassOwnPtr<BlobData> blobData)
+        : url(url.copy())
+        , blobData(blobData)
+    {
+        this->blobData->detachFromCurrentThread();
+    }
+
+    BlobRegistryContext(const KURL& url, const String& type)
+        : url(url.copy())
+        , type(type.isolatedCopy())
+    {
+    }
+
+    BlobRegistryContext(const KURL& url, const KURL& srcURL)
+        : url(url.copy())
+        , srcURL(srcURL.copy())
+    {
+    }
+
+    BlobRegistryContext(const KURL& url, PassRefPtr<RawData> streamData)
+        : url(url.copy())
+        , streamData(streamData)
+    {
+    }
+
+    BlobRegistryContext(const KURL& url)
+        : url(url.copy())
+    {
+    }
+
+    KURL url;
+    KURL srcURL;
+    OwnPtr<BlobData> blobData;
+    PassRefPtr<RawData> streamData;
+    String type;
+};
+
+static WebBlobRegistry* blobRegistry()
+{
+    ASSERT(isMainThread());
+    return WebKit::Platform::current()->blobRegistry();
+}
+
+typedef HashMap<String, RefPtr<SecurityOrigin> > BlobURLOriginMap;
+static ThreadSpecific<BlobURLOriginMap>& originMap()
+{
+    // We want to create the BlobOriginCache exactly once because it is shared by all the threads.
+    AtomicallyInitializedStatic(BlobOriginCache*, cache = new BlobOriginCache);
+
+    AtomicallyInitializedStatic(ThreadSpecific<BlobURLOriginMap>*, map = new ThreadSpecific<BlobURLOriginMap>);
+    return *map;
+}
+
+static void registerBlobURLTask(void* context)
+{
+    OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
+    if (WebBlobRegistry* registry = blobRegistry()) {
+        WebBlobData webBlobData(blobRegistryContext->blobData.release());
+        registry->registerBlobURL(blobRegistryContext->url, webBlobData);
+    }
+}
+
+void BlobRegistry::registerBlobURL(const KURL& url, PassOwnPtr<BlobData> blobData)
+{
+    if (isMainThread()) {
+        if (WebBlobRegistry* registry = blobRegistry()) {
+            WebBlobData webBlobData(blobData);
+            registry->registerBlobURL(url, webBlobData);
+        }
+    } else {
+        OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, blobData));
+        callOnMainThread(&registerBlobURLTask, context.leakPtr());
+    }
+}
+
+static void registerStreamURLTask(void* context)
+{
+    OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
+    if (WebBlobRegistry* registry = blobRegistry())
+        registry->registerStreamURL(blobRegistryContext->url, blobRegistryContext->type);
+}
+
+void BlobRegistry::registerStreamURL(const KURL& url, const String& type)
+{
+    if (isMainThread()) {
+        if (WebBlobRegistry* registry = blobRegistry())
+            registry->registerStreamURL(url, type);
+    } else {
+        OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, type));
+        callOnMainThread(&registerStreamURLTask, context.leakPtr());
+    }
+}
+
+static void registerBlobURLFromTask(void* context)
+{
+    OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
+    if (WebBlobRegistry* registry = blobRegistry())
+        registry->registerBlobURL(blobRegistryContext->url, blobRegistryContext->srcURL);
+}
+
+void BlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL)
+{
+    // If the blob URL contains null origin, as in the context with unique
+    // security origin or file URL, save the mapping between url and origin so
+    // that the origin can be retrived when doing security origin check.
+    if (origin && BlobURL::getOrigin(url) == "null")
+        originMap()->add(url.string(), origin);
+
+    if (isMainThread()) {
+        if (WebBlobRegistry* registry = blobRegistry())
+            registry->registerBlobURL(url, srcURL);
+    } else {
+        OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, srcURL));
+        callOnMainThread(&registerBlobURLFromTask, context.leakPtr());
+    }
+}
+
+static void addDataToStreamTask(void* context)
+{
+    OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
+    if (WebBlobRegistry* registry = blobRegistry()) {
+        WebThreadSafeData webThreadSafeData(blobRegistryContext->streamData);
+        registry->addDataToStream(blobRegistryContext->url, webThreadSafeData);
+    }
+}
+
+void BlobRegistry::addDataToStream(const KURL& url, PassRefPtr<RawData> streamData)
+{
+    if (isMainThread()) {
+        if (WebBlobRegistry* registry = blobRegistry()) {
+            WebThreadSafeData webThreadSafeData(streamData);
+            registry->addDataToStream(url, webThreadSafeData);
+        }
+    } else {
+        OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, streamData));
+        callOnMainThread(&addDataToStreamTask, context.leakPtr());
+    }
+}
+
+static void finalizeStreamTask(void* context)
+{
+    OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
+    if (WebBlobRegistry* registry = blobRegistry())
+        registry->finalizeStream(blobRegistryContext->url);
+}
+
+void BlobRegistry::finalizeStream(const KURL& url)
+{
+    if (isMainThread()) {
+        if (WebBlobRegistry* registry = blobRegistry())
+            registry->finalizeStream(url);
+    } else {
+        OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url));
+        callOnMainThread(&finalizeStreamTask, context.leakPtr());
+    }
+}
+
+static void unregisterBlobURLTask(void* context)
+{
+    OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
+    if (WebBlobRegistry* registry = blobRegistry())
+        registry->unregisterBlobURL(blobRegistryContext->url);
+}
+
+void BlobRegistry::unregisterBlobURL(const KURL& url)
+{
+    if (BlobURL::getOrigin(url) == "null")
+        originMap()->remove(url.string());
+
+    if (isMainThread()) {
+        if (WebBlobRegistry* registry = blobRegistry())
+            registry->unregisterBlobURL(url);
+    } else {
+        OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url));
+        callOnMainThread(&unregisterBlobURLTask, context.leakPtr());
+    }
+}
+
+BlobOriginCache::BlobOriginCache()
+{
+    SecurityOrigin::setCache(this);
+}
+
+SecurityOrigin* BlobOriginCache::cachedOrigin(const KURL& url)
+{
+    if (url.protocolIs("blob"))
+        return originMap()->get(url.string());
+    return 0;
+}
+
+} // namespace WebCore
diff --git a/Source/core/fileapi/ThreadableBlobRegistry.h b/Source/core/fileapi/BlobRegistry.h
similarity index 86%
rename from Source/core/fileapi/ThreadableBlobRegistry.h
rename to Source/core/fileapi/BlobRegistry.h
index a72b202..5bed50b 100644
--- a/Source/core/fileapi/ThreadableBlobRegistry.h
+++ b/Source/core/fileapi/BlobRegistry.h
@@ -28,9 +28,10 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ThreadableBlobRegistry_h
-#define ThreadableBlobRegistry_h
+#ifndef BlobRegistry_h
+#define BlobRegistry_h
 
+#include "wtf/Forward.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/PassRefPtr.h"
 
@@ -38,15 +39,19 @@
 
 class BlobData;
 class KURL;
+class RawData;
 class SecurityOrigin;
 
-class ThreadableBlobRegistry {
+class BlobRegistry {
 public:
     static void registerBlobURL(const KURL&, PassOwnPtr<BlobData>);
+    static void registerStreamURL(const KURL&, const String&);
     static void registerBlobURL(SecurityOrigin*, const KURL&, const KURL& srcURL);
+    static void addDataToStream(const KURL&, PassRefPtr<RawData>);
+    static void finalizeStream(const KURL&);
     static void unregisterBlobURL(const KURL&);
 };
 
 } // namespace WebCore
 
-#endif // ThreadableBlobRegistry_h
+#endif // BlobRegistry_h
diff --git a/Source/core/fileapi/File.h b/Source/core/fileapi/File.h
index 2bfa894..3234892 100644
--- a/Source/core/fileapi/File.h
+++ b/Source/core/fileapi/File.h
@@ -27,9 +27,8 @@
 #define File_h
 
 #include "core/fileapi/Blob.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/PassRefPtr.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/css/CSSStyleDeclaration.cpp b/Source/core/fileapi/FileError.cpp
similarity index 62%
copy from Source/core/css/CSSStyleDeclaration.cpp
copy to Source/core/fileapi/FileError.cpp
index 538e17e..671b309 100644
--- a/Source/core/css/CSSStyleDeclaration.cpp
+++ b/Source/core/fileapi/FileError.cpp
@@ -29,18 +29,43 @@
  */
 
 #include "config.h"
-#include "core/css/CSSStyleDeclaration.h"
-
-#include "core/css/CSSParser.h"
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/css/CSSStyleSheet.h"
-#include "core/css/CSSValue.h"
-#include "core/dom/Document.h"
-#include "core/dom/DocumentStyleSheetCollection.h"
-#include "core/dom/EventTarget.h"
-#include "core/html/HTMLStyleElement.h"
-#include "core/page/RuntimeCSSEnabled.h"
+#include "core/fileapi/FileError.h"
 
 namespace WebCore {
 
+ExceptionCode FileError::ErrorCodeToExceptionCode(ErrorCode code)
+{
+    switch (code) {
+    case OK:
+        return 0;
+    case NOT_FOUND_ERR:
+        return FSNotFoundError;
+    case SECURITY_ERR:
+        return FSSecurityError;
+    case ABORT_ERR:
+        return FSAbortError;
+    case NOT_READABLE_ERR:
+        return FSNotReadableError;
+    case ENCODING_ERR:
+        return FSEncodingError;
+    case NO_MODIFICATION_ALLOWED_ERR:
+        return FSNoModificationAllowedError;
+    case INVALID_STATE_ERR:
+        return FSInvalidStateError;
+    case SYNTAX_ERR:
+        return FSSyntaxError;
+    case INVALID_MODIFICATION_ERR:
+        return FSInvalidModificationError;
+    case QUOTA_EXCEEDED_ERR:
+        return FSQuotaExceededError;
+    case TYPE_MISMATCH_ERR:
+        return FSTypeMismatchError;
+    case PATH_EXISTS_ERR:
+        return FSPathExistsError;
+    default:
+        ASSERT_NOT_REACHED();
+        return 0;
+    }
+}
+
 } // namespace WebCore
diff --git a/Source/core/fileapi/FileError.h b/Source/core/fileapi/FileError.h
index 509e716..dc2c9c2 100644
--- a/Source/core/fileapi/FileError.h
+++ b/Source/core/fileapi/FileError.h
@@ -32,6 +32,7 @@
 #define FileError_h
 
 #include "bindings/v8/ScriptWrappable.h"
+#include "core/dom/ExceptionCode.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
 
@@ -58,6 +59,7 @@
     static PassRefPtr<FileError> create(ErrorCode code) { return adoptRef(new FileError(code)); }
 
     ErrorCode code() const { return m_code; }
+    static ExceptionCode ErrorCodeToExceptionCode(ErrorCode);
 
 private:
     FileError(ErrorCode code)
diff --git a/Source/core/fileapi/FileError.idl b/Source/core/fileapi/FileError.idl
index 46c910f..7e5542a 100644
--- a/Source/core/fileapi/FileError.idl
+++ b/Source/core/fileapi/FileError.idl
@@ -30,7 +30,6 @@
 
 [
 ] interface FileError {
-    // FIXME: Some of constant names are already defined in DOMException.h for Objective-C binding and we cannot have the same names here (they are translated into a enum in the same namespace).
     const unsigned short NOT_FOUND_ERR = 1;
     const unsigned short SECURITY_ERR = 2;
     const unsigned short ABORT_ERR = 3;
diff --git a/Source/core/fileapi/FileException.cpp b/Source/core/fileapi/FileException.cpp
deleted file mode 100644
index 07c496b..0000000
--- a/Source/core/fileapi/FileException.cpp
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/fileapi/FileException.h"
-
-namespace WebCore {
-
-static struct FileExceptionNameDescription {
-    const char* const name;
-    const char* const description;
-} fileExceptions[] = {
-    { "NOT_FOUND_ERR", "A requested file or directory could not be found at the time an operation was processed." },
-    { "SECURITY_ERR", "It was determined that certain files are unsafe for access within a Web application, or that too many calls are being made on file resources." },
-    { "ABORT_ERR", "An ongoing operation was aborted, typically with a call to abort()." },
-    { "NOT_READABLE_ERR", "The requested file could not be read, typically due to permission problems that have occurred after a reference to a file was acquired." },
-    { "ENCODING_ERR", "A URI supplied to the API was malformed, or the resulting Data URL has exceeded the URL length limitations for Data URLs." },
-    { "NO_MODIFICATION_ALLOWED_ERR", "An attempt was made to write to a file or directory which could not be modified due to the state of the underlying filesystem." },
-    { "INVALID_STATE_ERR", "An operation that depends on state cached in an interface object was made but the state had changed since it was read from disk." },
-    { "SYNTAX_ERR", "An invalid or unsupported argument was given, like an invalid line ending specifier." },
-    { "INVALID_MODIFICATION_ERR", "The modification request was illegal." },
-    { "QUOTA_EXCEEDED_ERR", "The operation failed because it would cause the application to exceed its storage quota." },
-    { "TYPE_MISMATCH_ERR", "The path supplied exists, but was not an entry of requested type." },
-    { "PATH_EXISTS_ERR", "An attempt was made to create a file or directory where an element already exists." }
-};
-
-bool FileException::initializeDescription(ExceptionCode ec, ExceptionCodeDescription* description)
-{
-    if (ec < FileExceptionOffset || ec > FileExceptionMax)
-        return false;
-
-    description->typeName = "DOM File";
-    description->code = ec - FileExceptionOffset;
-    description->type = FileExceptionType;
-
-    size_t tableSize = WTF_ARRAY_LENGTH(fileExceptions);
-    size_t tableIndex = ec - NOT_FOUND_ERR;
-
-    description->name = tableIndex < tableSize ? fileExceptions[tableIndex].name : 0;
-    description->description = tableIndex < tableSize ? fileExceptions[tableIndex].description : 0;
-
-    return true;
-}
-
-} // namespace WebCore
diff --git a/Source/core/fileapi/FileException.h b/Source/core/fileapi/FileException.h
deleted file mode 100644
index 7e6a95a..0000000
--- a/Source/core/fileapi/FileException.h
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef FileException_h
-#define FileException_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/ExceptionBase.h"
-
-namespace WebCore {
-
-class FileException : public ExceptionBase, public ScriptWrappable {
-public:
-    static PassRefPtr<FileException> create(const ExceptionCodeDescription& description)
-    {
-        return adoptRef(new FileException(description));
-    }
-
-    static const int FileExceptionOffset = 1100;
-    static const int FileExceptionMax = 1199;
-
-    enum FileExceptionCode {
-        NOT_FOUND_ERR = FileExceptionOffset + 1,
-        SECURITY_ERR = FileExceptionOffset + 2,
-        ABORT_ERR = FileExceptionOffset + 3,
-        NOT_READABLE_ERR = FileExceptionOffset + 4,
-        ENCODING_ERR = FileExceptionOffset + 5,
-        NO_MODIFICATION_ALLOWED_ERR = FileExceptionOffset + 6,
-        INVALID_STATE_ERR = FileExceptionOffset + 7,
-        SYNTAX_ERR = FileExceptionOffset + 8,
-        INVALID_MODIFICATION_ERR = FileExceptionOffset + 9,
-        QUOTA_EXCEEDED_ERR = FileExceptionOffset + 10,
-        TYPE_MISMATCH_ERR = FileExceptionOffset + 11,
-        PATH_EXISTS_ERR = FileExceptionOffset + 12,
-    };
-
-    static int ErrorCodeToExceptionCode(int errorCode)
-    {
-        if (!errorCode)
-            return 0;
-        return errorCode + FileExceptionOffset;
-    }
-
-    static bool initializeDescription(ExceptionCode, ExceptionCodeDescription*);
-
-private:
-    FileException(const ExceptionCodeDescription& description)
-        : ExceptionBase(description)
-    {
-        ScriptWrappable::init(this);
-    }
-};
-
-} // namespace WebCore
-
-#endif // FileException_h
diff --git a/Source/core/fileapi/FileException.idl b/Source/core/fileapi/FileException.idl
deleted file mode 100644
index c64d716..0000000
--- a/Source/core/fileapi/FileException.idl
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
-    NoInterfaceObject,
-    DoNotCheckConstants
-] exception FileException {
-
-    readonly attribute unsigned short   code;
-    readonly attribute DOMString        name;
-    readonly attribute DOMString        message;
-
-    // Override in a Mozilla compatible format
-    [NotEnumerable] DOMString toString();
-
-    // FileExceptionCode
-    const unsigned short NOT_FOUND_ERR = 1;
-    const unsigned short SECURITY_ERR = 2;
-    const unsigned short ABORT_ERR = 3;
-    const unsigned short NOT_READABLE_ERR = 4;
-    const unsigned short ENCODING_ERR = 5;
-    const unsigned short NO_MODIFICATION_ALLOWED_ERR = 6;
-    const unsigned short INVALID_STATE_ERR = 7;
-    const unsigned short SYNTAX_ERR = 8;
-    const unsigned short INVALID_MODIFICATION_ERR = 9;
-    const unsigned short QUOTA_EXCEEDED_ERR = 10;
-    const unsigned short TYPE_MISMATCH_ERR = 11;
-    const unsigned short PATH_EXISTS_ERR = 12;
-};
diff --git a/Source/core/fileapi/FileReader.cpp b/Source/core/fileapi/FileReader.cpp
index b8d01d7..bf29841 100644
--- a/Source/core/fileapi/FileReader.cpp
+++ b/Source/core/fileapi/FileReader.cpp
@@ -29,7 +29,6 @@
  */
 
 #include "config.h"
-
 #include "core/fileapi/FileReader.h"
 
 #include "core/dom/CrossThreadTask.h"
@@ -242,7 +241,7 @@
     unsetPendingActivity(this);
 }
 
-void FileReader::didFail(int errorCode)
+void FileReader::didFail(FileError::ErrorCode errorCode)
 {
     // If we're aborting, do not proceed with normal error handling since it is covered in aborting code.
     if (m_aborting)
diff --git a/Source/core/fileapi/FileReader.h b/Source/core/fileapi/FileReader.h
index f994f24..c8482fd 100644
--- a/Source/core/fileapi/FileReader.h
+++ b/Source/core/fileapi/FileReader.h
@@ -87,7 +87,7 @@
     virtual void didStartLoading();
     virtual void didReceiveData();
     virtual void didFinishLoading();
-    virtual void didFail(int errorCode);
+    virtual void didFail(FileError::ErrorCode);
 
     using RefCounted<FileReader>::ref;
     using RefCounted<FileReader>::deref;
diff --git a/Source/core/fileapi/FileReader.idl b/Source/core/fileapi/FileReader.idl
index a9bf2e5..d551b0f 100644
--- a/Source/core/fileapi/FileReader.idl
+++ b/Source/core/fileapi/FileReader.idl
@@ -30,7 +30,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     ActiveDOMObject,
     Constructor,
     ConstructorCallWith=ScriptExecutionContext,
diff --git a/Source/core/fileapi/FileReaderLoader.cpp b/Source/core/fileapi/FileReaderLoader.cpp
index f9d992e..e70634b 100644
--- a/Source/core/fileapi/FileReaderLoader.cpp
+++ b/Source/core/fileapi/FileReaderLoader.cpp
@@ -34,9 +34,9 @@
 
 #include "core/dom/ScriptExecutionContext.h"
 #include "core/fileapi/Blob.h"
+#include "core/fileapi/BlobRegistry.h"
 #include "core/fileapi/BlobURL.h"
 #include "core/fileapi/FileReaderLoaderClient.h"
-#include "core/fileapi/ThreadableBlobRegistry.h"
 #include "core/loader/TextResourceDecoder.h"
 #include "core/loader/ThreadableLoader.h"
 #include "core/platform/network/ResourceRequest.h"
@@ -65,7 +65,7 @@
     , m_hasRange(false)
     , m_rangeStart(0)
     , m_rangeEnd(0)
-    , m_errorCode(0)
+    , m_errorCode(FileError::OK)
 {
 }
 
@@ -73,7 +73,7 @@
 {
     terminate();
     if (!m_urlForReading.isEmpty())
-        ThreadableBlobRegistry::unregisterBlobURL(m_urlForReading);
+        BlobRegistry::unregisterBlobURL(m_urlForReading);
 }
 
 void FileReaderLoader::start(ScriptExecutionContext* scriptExecutionContext, Blob* blob)
@@ -84,7 +84,7 @@
         failed(FileError::SECURITY_ERR);
         return;
     }
-    ThreadableBlobRegistry::registerBlobURL(scriptExecutionContext->securityOrigin(), m_urlForReading, blob->url());
+    BlobRegistry::registerBlobURL(scriptExecutionContext->securityOrigin(), m_urlForReading, blob->url());
 
     // Construct and load the request.
     ResourceRequest request(m_urlForReading);
@@ -238,7 +238,7 @@
     failed(FileError::NOT_READABLE_ERR);
 }
 
-void FileReaderLoader::failed(int errorCode)
+void FileReaderLoader::failed(FileError::ErrorCode errorCode)
 {
     m_errorCode = errorCode;
     cleanup();
diff --git a/Source/core/fileapi/FileReaderLoader.h b/Source/core/fileapi/FileReaderLoader.h
index 28e1d03..c4b0291 100644
--- a/Source/core/fileapi/FileReaderLoader.h
+++ b/Source/core/fileapi/FileReaderLoader.h
@@ -76,7 +76,7 @@
 #endif // ENABLE(STREAM)
     unsigned bytesLoaded() const { return m_bytesLoaded; }
     unsigned totalBytes() const { return m_totalBytes; }
-    int errorCode() const { return m_errorCode; }
+    FileError::ErrorCode errorCode() const { return m_errorCode; }
 
     void setEncoding(const String&);
     void setDataType(const String& dataType) { m_dataType = dataType; }
@@ -87,7 +87,7 @@
 private:
     void terminate();
     void cleanup();
-    void failed(int errorCode);
+    void failed(FileError::ErrorCode);
     void convertToText();
     void convertToDataURL();
 
@@ -120,7 +120,7 @@
     unsigned m_rangeStart;
     unsigned m_rangeEnd;
 
-    int m_errorCode;
+    FileError::ErrorCode m_errorCode;
 };
 
 } // namespace WebCore
diff --git a/Source/core/fileapi/FileReaderLoaderClient.h b/Source/core/fileapi/FileReaderLoaderClient.h
index fde658b..32de162 100644
--- a/Source/core/fileapi/FileReaderLoaderClient.h
+++ b/Source/core/fileapi/FileReaderLoaderClient.h
@@ -31,6 +31,8 @@
 #ifndef FileReaderLoaderClient_h
 #define FileReaderLoaderClient_h
 
+#include "core/fileapi/FileError.h"
+
 namespace WebCore {
 
 class FileReaderLoaderClient {
@@ -40,7 +42,7 @@
     virtual void didStartLoading() = 0;
     virtual void didReceiveData() = 0;
     virtual void didFinishLoading() = 0;
-    virtual void didFail(int errorCode) = 0;
+    virtual void didFail(FileError::ErrorCode) = 0;
 };
 
 } // namespace WebCore
diff --git a/Source/core/fileapi/FileReaderSync.cpp b/Source/core/fileapi/FileReaderSync.cpp
index c2f5047..1cacad8 100644
--- a/Source/core/fileapi/FileReaderSync.cpp
+++ b/Source/core/fileapi/FileReaderSync.cpp
@@ -29,11 +29,10 @@
  */
 
 #include "config.h"
-
 #include "core/fileapi/FileReaderSync.h"
 
+#include "core/dom/ExceptionCode.h"
 #include "core/fileapi/Blob.h"
-#include "core/fileapi/FileException.h"
 #include "core/fileapi/FileReaderLoader.h"
 #include <wtf/ArrayBuffer.h>
 #include <wtf/PassRefPtr.h>
@@ -48,7 +47,7 @@
 PassRefPtr<ArrayBuffer> FileReaderSync::readAsArrayBuffer(ScriptExecutionContext* scriptExecutionContext, Blob* blob, ExceptionCode& ec)
 {
     if (!blob) {
-        ec = NOT_FOUND_ERR;
+        ec = FSNotFoundError;
         return 0;
     }
 
@@ -61,7 +60,7 @@
 String FileReaderSync::readAsBinaryString(ScriptExecutionContext* scriptExecutionContext, Blob* blob, ExceptionCode& ec)
 {
     if (!blob) {
-        ec = NOT_FOUND_ERR;
+        ec = FSNotFoundError;
         return String();
     }
 
@@ -73,7 +72,7 @@
 String FileReaderSync::readAsText(ScriptExecutionContext* scriptExecutionContext, Blob* blob, const String& encoding, ExceptionCode& ec)
 {
     if (!blob) {
-        ec = NOT_FOUND_ERR;
+        ec = FSNotFoundError;
         return String();
     }
 
@@ -86,7 +85,7 @@
 String FileReaderSync::readAsDataURL(ScriptExecutionContext* scriptExecutionContext, Blob* blob, ExceptionCode& ec)
 {
     if (!blob) {
-        ec = NOT_FOUND_ERR;
+        ec = FSNotFoundError;
         return String();
     }
 
@@ -99,7 +98,7 @@
 void FileReaderSync::startLoading(ScriptExecutionContext* scriptExecutionContext, FileReaderLoader& loader, Blob* blob, ExceptionCode& ec)
 {
     loader.start(scriptExecutionContext, blob);
-    ec = FileException::ErrorCodeToExceptionCode(loader.errorCode());
+    ec = FileError::ErrorCodeToExceptionCode(loader.errorCode());
 }
 
 } // namespace WebCore
diff --git a/Source/core/fileapi/FileReaderSync.idl b/Source/core/fileapi/FileReaderSync.idl
index 9bc21f8..4930687 100644
--- a/Source/core/fileapi/FileReaderSync.idl
+++ b/Source/core/fileapi/FileReaderSync.idl
@@ -29,7 +29,7 @@
  */
 
 [
-    GlobalContext=WorkerOnly,
+    GlobalContext=WorkerGlobalScope,
     Constructor
 ] interface FileReaderSync {
     [CallWith=ScriptExecutionContext, RaisesException] ArrayBuffer readAsArrayBuffer(Blob blob);
diff --git a/Source/core/css/CSSStyleDeclaration.cpp b/Source/core/fileapi/Stream.cpp
similarity index 63%
copy from Source/core/css/CSSStyleDeclaration.cpp
copy to Source/core/fileapi/Stream.cpp
index 538e17e..2400e2b 100644
--- a/Source/core/css/CSSStyleDeclaration.cpp
+++ b/Source/core/fileapi/Stream.cpp
@@ -29,18 +29,42 @@
  */
 
 #include "config.h"
-#include "core/css/CSSStyleDeclaration.h"
+#include "core/fileapi/Stream.h"
 
-#include "core/css/CSSParser.h"
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/css/CSSStyleSheet.h"
-#include "core/css/CSSValue.h"
-#include "core/dom/Document.h"
-#include "core/dom/DocumentStyleSheetCollection.h"
-#include "core/dom/EventTarget.h"
-#include "core/html/HTMLStyleElement.h"
-#include "core/page/RuntimeCSSEnabled.h"
+#include "core/fileapi/BlobRegistry.h"
+#include "core/fileapi/BlobURL.h"
+#include "core/platform/network/BlobData.h"
 
 namespace WebCore {
 
+Stream::Stream(const String& mediaType)
+    : m_mediaType(mediaType)
+    , m_isNeutered(false)
+{
+    ScriptWrappable::init(this);
+
+    // Create a new internal URL for a stream and register it with the provided
+    // media type.
+    m_internalURL = BlobURL::createInternalURL();
+    BlobRegistry::registerStreamURL(m_internalURL, m_mediaType);
+}
+
+void Stream::addData(const char* data, size_t len)
+{
+    RefPtr<RawData> buffer(RawData::create());
+    buffer->mutableData()->resize(len);
+    memcpy(buffer->mutableData()->data(), data, len);
+    BlobRegistry::addDataToStream(m_internalURL, buffer);
+}
+
+void Stream::finalize()
+{
+    BlobRegistry::finalizeStream(m_internalURL);
+}
+
+Stream::~Stream()
+{
+    BlobRegistry::unregisterBlobURL(m_internalURL);
+}
+
 } // namespace WebCore
diff --git a/Source/core/fileapi/Stream.h b/Source/core/fileapi/Stream.h
new file mode 100644
index 0000000..71d9d81
--- /dev/null
+++ b/Source/core/fileapi/Stream.h
@@ -0,0 +1,83 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef Stream_h
+#define Stream_h
+
+#include "bindings/v8/ScriptWrappable.h"
+#include "weborigin/KURL.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class Stream : public ScriptWrappable, public RefCounted<Stream> {
+public:
+    static PassRefPtr<Stream> create(const String& mediaType)
+    {
+        return adoptRef(new Stream(mediaType));
+    }
+
+    virtual ~Stream();
+
+    // Returns the internal URL referring to this stream.
+    const KURL& url() const { return m_internalURL; }
+    // Returns the media type of this stream.
+    const String& type() const { return m_mediaType; }
+
+    // Appends data to this stream.
+    void addData(const char* data, size_t len);
+    // Mark this stream finalized so that a reader of this stream is notified
+    // of EOF.
+    void finalize();
+
+    // Allow an external reader class to mark this object neutered so that they
+    // won't load the corresponding stream again. All stream objects are
+    // read-once for now.
+    void neuter() { m_isNeutered = true; }
+    bool isNeutered() const { return m_isNeutered; }
+
+protected:
+    explicit Stream(const String& mediaType);
+
+    // This is an internal URL referring to the blob data associated with this object. It serves
+    // as an identifier for this blob. The internal URL is never used to source the blob's content
+    // into an HTML or for FileRead'ing, public blob URLs must be used for those purposes.
+    KURL m_internalURL;
+
+    String m_mediaType;
+
+    bool m_isNeutered;
+};
+
+} // namespace WebCore
+
+#endif // Stream_h
diff --git a/Source/core/workers/DedicatedWorkerContext.idl b/Source/core/fileapi/Stream.idl
similarity index 77%
copy from Source/core/workers/DedicatedWorkerContext.idl
copy to Source/core/fileapi/Stream.idl
index 3f4f45c..7caf013 100644
--- a/Source/core/workers/DedicatedWorkerContext.idl
+++ b/Source/core/fileapi/Stream.idl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009, 2011 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,10 +28,16 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-[
-    NoInterfaceObject
-] interface DedicatedWorkerContext : WorkerContext {
-    [Custom, RaisesException] void postMessage(any message, optional Array messagePorts);
-    attribute EventListener onmessage;
-};
+// FIXME: close() method which is necessary for Stream building feature
+// is omitted for now. Add it when necessary.
+//
+// FIXME: Add a flag to indicate if this stream frees memory when read or not
+// (e.g. boolean isReadOnce()).
+//
+// FIXME: Make the Blob a subclass of the Stream.
 
+[
+    EnabledAtRuntime=stream
+] interface Stream {
+    readonly attribute DOMString type;
+};
diff --git a/Source/core/fileapi/ThreadableBlobRegistry.cpp b/Source/core/fileapi/ThreadableBlobRegistry.cpp
deleted file mode 100644
index bfb32cd..0000000
--- a/Source/core/fileapi/ThreadableBlobRegistry.cpp
+++ /dev/null
@@ -1,160 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/fileapi/ThreadableBlobRegistry.h"
-
-#include "core/fileapi/BlobURL.h"
-#include "core/platform/network/BlobData.h"
-#include "core/platform/network/BlobRegistry.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityOriginCache.h"
-#include "wtf/HashMap.h"
-#include "wtf/MainThread.h"
-#include "wtf/RefPtr.h"
-#include "wtf/ThreadSpecific.h"
-#include "wtf/text/StringHash.h"
-
-using WTF::ThreadSpecific;
-
-namespace WebCore {
-
-class BlobOriginCache : public SecurityOriginCache {
-public:
-    BlobOriginCache();
-    virtual SecurityOrigin* cachedOrigin(const KURL&) OVERRIDE;
-};
-
-struct BlobRegistryContext {
-    WTF_MAKE_FAST_ALLOCATED;
-public:
-    BlobRegistryContext(const KURL& url, PassOwnPtr<BlobData> blobData)
-        : url(url.copy())
-        , blobData(blobData)
-    {
-        this->blobData->detachFromCurrentThread();
-    }
-
-    BlobRegistryContext(const KURL& url, const KURL& srcURL)
-        : url(url.copy())
-        , srcURL(srcURL.copy())
-    {
-    }
-
-    BlobRegistryContext(const KURL& url)
-        : url(url.copy())
-    {
-    }
-
-    KURL url;
-    KURL srcURL;
-    OwnPtr<BlobData> blobData;
-};
-
-typedef HashMap<String, RefPtr<SecurityOrigin> > BlobURLOriginMap;
-static ThreadSpecific<BlobURLOriginMap>& originMap()
-{
-    // We want to create the BlobOriginCache exactly once because it is shared by all the threads.
-    AtomicallyInitializedStatic(BlobOriginCache*, cache = new BlobOriginCache);
-
-    AtomicallyInitializedStatic(ThreadSpecific<BlobURLOriginMap>*, map = new ThreadSpecific<BlobURLOriginMap>);
-    return *map;
-}
-
-static void registerBlobURLTask(void* context)
-{
-    OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
-    blobRegistry().registerBlobURL(blobRegistryContext->url, blobRegistryContext->blobData.release());
-}
-
-void ThreadableBlobRegistry::registerBlobURL(const KURL& url, PassOwnPtr<BlobData> blobData)
-{
-    if (isMainThread())
-        blobRegistry().registerBlobURL(url, blobData);
-    else {
-        OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, blobData));
-        callOnMainThread(&registerBlobURLTask, context.leakPtr());
-    }
-}
-
-static void registerBlobURLFromTask(void* context)
-{
-    OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
-    blobRegistry().registerBlobURL(blobRegistryContext->url, blobRegistryContext->srcURL);
-}
-
-void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin* origin, const KURL& url, const KURL& srcURL)
-{
-    // If the blob URL contains null origin, as in the context with unique
-    // security origin or file URL, save the mapping between url and origin so
-    // that the origin can be retrived when doing security origin check.
-    if (origin && BlobURL::getOrigin(url) == "null")
-        originMap()->add(url.string(), origin);
-
-    if (isMainThread())
-        blobRegistry().registerBlobURL(url, srcURL);
-    else {
-        OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url, srcURL));
-        callOnMainThread(&registerBlobURLFromTask, context.leakPtr());
-    }
-}
-
-static void unregisterBlobURLTask(void* context)
-{
-    OwnPtr<BlobRegistryContext> blobRegistryContext = adoptPtr(static_cast<BlobRegistryContext*>(context));
-    blobRegistry().unregisterBlobURL(blobRegistryContext->url);
-}
-
-void ThreadableBlobRegistry::unregisterBlobURL(const KURL& url)
-{
-    if (BlobURL::getOrigin(url) == "null")
-        originMap()->remove(url.string());
-
-    if (isMainThread())
-        blobRegistry().unregisterBlobURL(url);
-    else {
-        OwnPtr<BlobRegistryContext> context = adoptPtr(new BlobRegistryContext(url));
-        callOnMainThread(&unregisterBlobURLTask, context.leakPtr());
-    }
-}
-
-BlobOriginCache::BlobOriginCache()
-{
-    SecurityOrigin::setCache(this);
-}
-
-SecurityOrigin* BlobOriginCache::cachedOrigin(const KURL& url)
-{
-    if (url.protocolIs("blob"))
-        return originMap()->get(url.string());
-    return 0;
-}
-
-} // namespace WebCore
diff --git a/Source/core/history/HistoryItem.cpp b/Source/core/history/HistoryItem.cpp
index 7a062bf..f538b79 100644
--- a/Source/core/history/HistoryItem.cpp
+++ b/Source/core/history/HistoryItem.cpp
@@ -30,9 +30,8 @@
 #include "bindings/v8/SerializedScriptValue.h"
 #include "core/dom/Document.h"
 #include "core/platform/network/ResourceRequest.h"
-#include <wtf/CurrentTime.h>
-#include <wtf/MathExtras.h>
-#include <wtf/text/CString.h>
+#include "wtf/CurrentTime.h"
+#include "wtf/text/CString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/history/HistoryItem.h b/Source/core/history/HistoryItem.h
index aa49089..804e1e9 100644
--- a/Source/core/history/HistoryItem.h
+++ b/Source/core/history/HistoryItem.h
@@ -29,9 +29,8 @@
 
 #include "bindings/v8/SerializedScriptValue.h"
 #include "core/platform/graphics/IntPoint.h"
-#include <wtf/HashMap.h>
-#include <wtf/RefCounted.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/RefCounted.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/BaseButtonInputType.cpp b/Source/core/html/BaseButtonInputType.cpp
index 046f8b8..868e235 100644
--- a/Source/core/html/BaseButtonInputType.cpp
+++ b/Source/core/html/BaseButtonInputType.cpp
@@ -33,13 +33,48 @@
 #include "core/html/BaseButtonInputType.h"
 
 #include "HTMLNames.h"
+#include "core/dom/Text.h"
+#include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/rendering/RenderButton.h"
+#include "core/rendering/RenderTextFragment.h"
 
 namespace WebCore {
 
 using namespace HTMLNames;
 
+class NonSelectableText : public Text {
+    inline NonSelectableText(Document* document, const String& data)
+        : Text(document, data, CreateText)
+    {
+    }
+
+    virtual RenderText* createTextRenderer(RenderStyle*) OVERRIDE
+    {
+        return new (document()->renderArena()) RenderTextFragment(this, dataImpl());
+    }
+
+public:
+    static inline PassRefPtr<NonSelectableText> create(Document* document, const String& data)
+    {
+        return adoptRef(new NonSelectableText(document, data));
+    }
+};
+
+// ----------------------------
+
+void BaseButtonInputType::createShadowSubtree()
+{
+    ASSERT(element()->userAgentShadowRoot());
+    RefPtr<Text> text = NonSelectableText::create(element()->document(), element()->valueWithDefault());
+    element()->userAgentShadowRoot()->appendChild(text);
+}
+
+void BaseButtonInputType::valueAttributeChanged()
+{
+    toText(element()->userAgentShadowRoot()->firstChild())->setData(element()->valueWithDefault());
+}
+
 bool BaseButtonInputType::shouldSaveAndRestoreFormControlState() const
 {
     return false;
@@ -51,9 +86,9 @@
     return false;
 }
 
-RenderObject* BaseButtonInputType::createRenderer(RenderArena* arena, RenderStyle*) const
+RenderObject* BaseButtonInputType::createRenderer(RenderStyle*) const
 {
-    return new (arena) RenderButton(element());
+    return new (element()->document()->renderArena()) RenderButton(element());
 }
 
 bool BaseButtonInputType::storesValueSeparateFromAttribute()
diff --git a/Source/core/html/BaseButtonInputType.h b/Source/core/html/BaseButtonInputType.h
index 1549404..e006445 100644
--- a/Source/core/html/BaseButtonInputType.h
+++ b/Source/core/html/BaseButtonInputType.h
@@ -41,9 +41,11 @@
     BaseButtonInputType(HTMLInputElement* element) : BaseClickableWithKeyInputType(element) { }
 
 private:
+    virtual void createShadowSubtree() OVERRIDE;
+    virtual void valueAttributeChanged() OVERRIDE;
     virtual bool shouldSaveAndRestoreFormControlState() const OVERRIDE;
     virtual bool appendFormData(FormDataList&, bool) const OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) const OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) const OVERRIDE;
     virtual bool storesValueSeparateFromAttribute() OVERRIDE;
     virtual void setValue(const String&, bool, TextFieldEventBehavior) OVERRIDE;
 };
diff --git a/Source/core/html/BaseChooserOnlyDateAndTimeInputType.cpp b/Source/core/html/BaseChooserOnlyDateAndTimeInputType.cpp
index a8642eb..4682522 100644
--- a/Source/core/html/BaseChooserOnlyDateAndTimeInputType.cpp
+++ b/Source/core/html/BaseChooserOnlyDateAndTimeInputType.cpp
@@ -128,10 +128,5 @@
     BaseClickableWithKeyInputType::accessKeyAction(element(), sendMouseEvents);
 }
 
-bool BaseChooserOnlyDateAndTimeInputType::isMouseFocusable() const
-{
-    return element()->isFocusable();
-}
-
 }
 #endif
diff --git a/Source/core/html/BaseChooserOnlyDateAndTimeInputType.h b/Source/core/html/BaseChooserOnlyDateAndTimeInputType.h
index 645b2e2..245db8a 100644
--- a/Source/core/html/BaseChooserOnlyDateAndTimeInputType.h
+++ b/Source/core/html/BaseChooserOnlyDateAndTimeInputType.h
@@ -52,7 +52,6 @@
     virtual void handleKeypressEvent(KeyboardEvent*) OVERRIDE;
     virtual void handleKeyupEvent(KeyboardEvent*) OVERRIDE;
     virtual void accessKeyAction(bool sendMouseEvents) OVERRIDE;
-    virtual bool isMouseFocusable() const OVERRIDE;
 
     // DateTimeChooserClient functions:
     virtual void didChooseValue(const String&) OVERRIDE;
diff --git a/Source/core/html/BaseDateAndTimeInputType.cpp b/Source/core/html/BaseDateAndTimeInputType.cpp
index 52e3857..6013692 100644
--- a/Source/core/html/BaseDateAndTimeInputType.cpp
+++ b/Source/core/html/BaseDateAndTimeInputType.cpp
@@ -34,11 +34,10 @@
 #include <limits>
 #include "core/html/HTMLInputElement.h"
 #include "core/platform/text/PlatformLocale.h"
-#include <wtf/CurrentTime.h>
-#include <wtf/DateMath.h>
-#include <wtf/MathExtras.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/CurrentTime.h"
+#include "wtf/DateMath.h"
+#include "wtf/MathExtras.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -110,7 +109,7 @@
     DateComponents ignoredResult;
     if (!out)
         out = &ignoredResult;
-    return parseToDateComponentsInternal(source.characters(), source.length(), out);
+    return parseToDateComponentsInternal(source, out);
 }
 
 String BaseDateAndTimeInputType::serialize(const Decimal& value) const
@@ -175,4 +174,9 @@
     return element()->isRequired() && value.isEmpty();
 }
 
+bool BaseDateAndTimeInputType::shouldShowFocusRingOnMouseFocus() const
+{
+    return true;
+}
+
 } // namespace WebCore
diff --git a/Source/core/html/BaseDateAndTimeInputType.h b/Source/core/html/BaseDateAndTimeInputType.h
index e68495c..5416764 100644
--- a/Source/core/html/BaseDateAndTimeInputType.h
+++ b/Source/core/html/BaseDateAndTimeInputType.h
@@ -33,7 +33,6 @@
 
 #include "core/html/InputType.h"
 #include "core/platform/DateComponents.h"
-#include <wtf/unicode/Unicode.h>
 
 namespace WebCore {
 
@@ -50,7 +49,7 @@
     virtual String visibleValue() const OVERRIDE;
 
 private:
-    virtual bool parseToDateComponentsInternal(const UChar*, unsigned length, DateComponents*) const = 0;
+    virtual bool parseToDateComponentsInternal(const String&, DateComponents*) const = 0;
     virtual DateComponents::Type dateType() const = 0;
     virtual double valueAsDate() const OVERRIDE;
     virtual void setValueAsDate(double, ExceptionCode&) const OVERRIDE;
@@ -65,6 +64,7 @@
     virtual String localizeValue(const String&) const OVERRIDE;
     virtual bool supportsReadOnly() const OVERRIDE;
     virtual bool shouldRespectListAttribute() OVERRIDE;
+    virtual bool shouldShowFocusRingOnMouseFocus() const OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.cpp b/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.cpp
index fcf04bf..b15c0a4 100644
--- a/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.cpp
+++ b/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.cpp
@@ -153,6 +153,7 @@
     // We don't need to call blur(). This function is called when control
     // lost focus.
 
+    RefPtr<HTMLInputElement> protector(element());
     // Remove focus ring by CSS "focus" pseudo class.
     element()->setFocus(false);
 }
@@ -163,6 +164,7 @@
     // got focus.
 
     // Add focus ring by CSS "focus" pseudo class.
+    // FIXME: Setting the focus flag to non-focused element is too tricky.
     element()->setFocus(true);
 }
 
@@ -248,7 +250,7 @@
         return;
     DateComponents date;
     unsigned end;
-    if (date.parseDate(value.characters(), value.length(), 0, end) && end == value.length())
+    if (date.parseDate(value, 0, end) && end == value.length())
         edit->setOnlyYearMonthDay(date);
 }
 
@@ -368,7 +370,7 @@
     if (direction == FocusDirectionBackward) {
         if (element()->document()->page())
             element()->document()->page()->focusController()->advanceFocus(direction, 0);
-    } else if (direction == FocusDirectionNone) {
+    } else if (direction == FocusDirectionNone || direction == FocusDirectionMouse) {
         edit->focusByOwner(oldFocusedNode);
     } else
         edit->focusByOwner();
@@ -424,11 +426,6 @@
     return element()->isFocusable();
 }
 
-bool BaseMultipleFieldsDateAndTimeInputType::isMouseFocusable() const
-{
-    return element()->isFocusable();
-}
-
 AtomicString BaseMultipleFieldsDateAndTimeInputType::localeIdentifier() const
 {
     return element()->computeInheritedLanguage();
diff --git a/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.h b/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.h
index a6c4135..639dc04 100644
--- a/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.h
+++ b/Source/core/html/BaseMultipleFieldsDateAndTimeInputType.h
@@ -98,7 +98,6 @@
     virtual bool hasBadInput() const OVERRIDE;
     virtual bool hasCustomFocusLogic() const OVERRIDE FINAL;
     virtual bool isKeyboardFocusable(KeyboardEvent*) const OVERRIDE FINAL;
-    virtual bool isMouseFocusable() const OVERRIDE FINAL;
     virtual void minOrMaxAttributeChanged() OVERRIDE FINAL;
     virtual void readonlyAttributeChanged() OVERRIDE FINAL;
     virtual void requiredAttributeChanged() OVERRIDE FINAL;
diff --git a/Source/core/html/ClassList.cpp b/Source/core/html/ClassList.cpp
index 1865a12..c12b38a 100644
--- a/Source/core/html/ClassList.cpp
+++ b/Source/core/html/ClassList.cpp
@@ -26,7 +26,6 @@
 #include "core/html/ClassList.h"
 
 #include "core/dom/SpaceSplitString.h"
-#include <wtf/text/StringBuilder.h>
 
 namespace WebCore {
 
diff --git a/Source/core/html/ClassList.h b/Source/core/html/ClassList.h
index af032d2..ab5220a 100644
--- a/Source/core/html/ClassList.h
+++ b/Source/core/html/ClassList.h
@@ -29,9 +29,8 @@
 #include "core/dom/Element.h"
 #include "core/dom/SpaceSplitString.h"
 #include "core/html/DOMTokenList.h"
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/ColorInputType.cpp b/Source/core/html/ColorInputType.cpp
index 06abe9e..e6278d4 100644
--- a/Source/core/html/ColorInputType.cpp
+++ b/Source/core/html/ColorInputType.cpp
@@ -35,7 +35,6 @@
 #include "RuntimeEnabledFeatures.h"
 #include "bindings/v8/ScriptController.h"
 #include "core/dom/MouseEvent.h"
-#include "core/dom/shadow/ElementShadow.h"
 #include "core/dom/shadow/ShadowRoot.h"
 #include "core/html/HTMLDataListElement.h"
 #include "core/html/HTMLDivElement.h"
@@ -44,10 +43,9 @@
 #include "core/html/InputTypeNames.h"
 #include "core/page/Chrome.h"
 #include "core/platform/graphics/Color.h"
-#include "core/rendering/RenderObject.h"
 #include "core/rendering/RenderView.h"
-#include <wtf/PassOwnPtr.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/PassOwnPtr.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/DOMFormData.cpp b/Source/core/html/DOMFormData.cpp
index cf4cbc4..942f51f 100644
--- a/Source/core/html/DOMFormData.cpp
+++ b/Source/core/html/DOMFormData.cpp
@@ -32,7 +32,6 @@
 #include "core/html/DOMFormData.h"
 
 #include "core/fileapi/Blob.h"
-#include "core/html/HTMLFormControlElement.h"
 #include "core/html/HTMLFormElement.h"
 #include "wtf/text/TextEncoding.h"
 #include "wtf/text/WTFString.h"
diff --git a/Source/core/html/DOMSettableTokenList.h b/Source/core/html/DOMSettableTokenList.h
index 0b11920..caa1079 100644
--- a/Source/core/html/DOMSettableTokenList.h
+++ b/Source/core/html/DOMSettableTokenList.h
@@ -27,9 +27,8 @@
 
 #include "core/dom/SpaceSplitString.h"
 #include "core/html/DOMTokenList.h"
-#include <wtf/PassOwnPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/text/AtomicString.h>
+#include "wtf/RefCounted.h"
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/DOMURL.cpp b/Source/core/html/DOMURL.cpp
index 777fe23..6fe9ffa 100644
--- a/Source/core/html/DOMURL.cpp
+++ b/Source/core/html/DOMURL.cpp
@@ -37,7 +37,6 @@
 #include "modules/mediastream/MediaStream.h"
 #include "weborigin/KURL.h"
 #include "wtf/MainThread.h"
-#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/DateInputType.cpp b/Source/core/html/DateInputType.cpp
index 40ffc25..d53ec40 100644
--- a/Source/core/html/DateInputType.cpp
+++ b/Source/core/html/DateInputType.cpp
@@ -84,11 +84,11 @@
     return StepRange(stepBase, minimum, maximum, step, stepDescription);
 }
 
-bool DateInputType::parseToDateComponentsInternal(const UChar* characters, unsigned length, DateComponents* out) const
+bool DateInputType::parseToDateComponentsInternal(const String& string, DateComponents* out) const
 {
     ASSERT(out);
     unsigned end;
-    return out->parseDate(characters, length, 0, end) && end == length;
+    return out->parseDate(string, 0, end) && end == string.length();
 }
 
 bool DateInputType::setMillisecondToDateComponents(double value, DateComponents* date) const
diff --git a/Source/core/html/DateInputType.h b/Source/core/html/DateInputType.h
index 78575ee..3c25c9b 100644
--- a/Source/core/html/DateInputType.h
+++ b/Source/core/html/DateInputType.h
@@ -33,7 +33,6 @@
 
 #include "core/html/BaseChooserOnlyDateAndTimeInputType.h"
 #include "core/html/BaseMultipleFieldsDateAndTimeInputType.h"
-#include <wtf/RefPtr.h>
 
 namespace WebCore {
 
@@ -55,7 +54,7 @@
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual DateComponents::Type dateType() const OVERRIDE;
     virtual StepRange createStepRange(AnyStepHandling) const OVERRIDE;
-    virtual bool parseToDateComponentsInternal(const UChar*, unsigned length, DateComponents*) const OVERRIDE;
+    virtual bool parseToDateComponentsInternal(const String&, DateComponents*) const OVERRIDE;
     virtual bool setMillisecondToDateComponents(double, DateComponents*) const OVERRIDE;
     virtual bool isDateField() const OVERRIDE;
 
diff --git a/Source/core/html/DateTimeFieldsState.h b/Source/core/html/DateTimeFieldsState.h
index 2dd2195..3f6834e 100644
--- a/Source/core/html/DateTimeFieldsState.h
+++ b/Source/core/html/DateTimeFieldsState.h
@@ -27,7 +27,6 @@
 #define DateTimeFieldsState_h
 
 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
-#include <wtf/text/WTFString.h>
 
 namespace WebCore {
 
diff --git a/Source/core/html/DateTimeLocalInputType.cpp b/Source/core/html/DateTimeLocalInputType.cpp
index 7fb9e66..5edd420 100644
--- a/Source/core/html/DateTimeLocalInputType.cpp
+++ b/Source/core/html/DateTimeLocalInputType.cpp
@@ -35,14 +35,13 @@
 #include "core/html/HTMLInputElement.h"
 #include "core/html/InputTypeNames.h"
 #include "core/platform/DateComponents.h"
-#include <wtf/PassOwnPtr.h>
+#include "wtf/PassOwnPtr.h"
 
 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
 #include "core/html/DateTimeFieldsState.h"
 #include "core/platform/LocalizedStrings.h"
 #include "core/platform/text/PlatformLocale.h"
-#include <wtf/text/StringBuilder.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/text/WTFString.h"
 #endif
 
 namespace WebCore {
@@ -96,11 +95,11 @@
     return StepRange(stepBase, minimum, maximum, step, stepDescription);
 }
 
-bool DateTimeLocalInputType::parseToDateComponentsInternal(const UChar* characters, unsigned length, DateComponents* out) const
+bool DateTimeLocalInputType::parseToDateComponentsInternal(const String& string, DateComponents* out) const
 {
     ASSERT(out);
     unsigned end;
-    return out->parseDateTimeLocal(characters, length, 0, end) && end == length;
+    return out->parseDateTimeLocal(string, 0, end) && end == string.length();
 }
 
 bool DateTimeLocalInputType::setMillisecondToDateComponents(double value, DateComponents* date) const
diff --git a/Source/core/html/DateTimeLocalInputType.h b/Source/core/html/DateTimeLocalInputType.h
index e2e083e..5b89a78 100644
--- a/Source/core/html/DateTimeLocalInputType.h
+++ b/Source/core/html/DateTimeLocalInputType.h
@@ -54,7 +54,7 @@
     virtual double valueAsDate() const OVERRIDE;
     virtual void setValueAsDate(double, ExceptionCode&) const OVERRIDE;
     virtual StepRange createStepRange(AnyStepHandling) const;
-    virtual bool parseToDateComponentsInternal(const UChar*, unsigned length, DateComponents*) const OVERRIDE;
+    virtual bool parseToDateComponentsInternal(const String&, DateComponents*) const OVERRIDE;
     virtual bool setMillisecondToDateComponents(double, DateComponents*) const OVERRIDE;
     virtual bool isDateTimeLocalField() const OVERRIDE;
 
diff --git a/Source/core/html/EmailInputType.cpp b/Source/core/html/EmailInputType.cpp
index f8707a2..70a9d5d 100644
--- a/Source/core/html/EmailInputType.cpp
+++ b/Source/core/html/EmailInputType.cpp
@@ -58,7 +58,7 @@
 
     UErrorCode error = U_ZERO_ERROR;
     UChar domainNameBuffer[maximumDomainNameLength];
-    int32_t domainNameLength = uidna_IDNToASCII(address.characters() + atPosition + 1, address.length() - atPosition - 1, domainNameBuffer, WTF_ARRAY_LENGTH(domainNameBuffer), idnaConversionOption, 0, &error);
+    int32_t domainNameLength = uidna_IDNToASCII(address.bloatedCharacters() + atPosition + 1, address.length() - atPosition - 1, domainNameBuffer, WTF_ARRAY_LENGTH(domainNameBuffer), idnaConversionOption, 0, &error);
     if (error != U_ZERO_ERROR || domainNameLength <= 0)
         return address;
 
diff --git a/Source/core/html/FileInputType.cpp b/Source/core/html/FileInputType.cpp
index eac4fb4..50e4641 100644
--- a/Source/core/html/FileInputType.cpp
+++ b/Source/core/html/FileInputType.cpp
@@ -158,9 +158,9 @@
     event->setDefaultHandled();
 }
 
-RenderObject* FileInputType::createRenderer(RenderArena* arena, RenderStyle*) const
+RenderObject* FileInputType::createRenderer(RenderStyle*) const
 {
-    return new (arena) RenderFileUploadControl(element());
+    return new (element()->document()->renderArena()) RenderFileUploadControl(element());
 }
 
 bool FileInputType::canSetStringValue() const
diff --git a/Source/core/html/FileInputType.h b/Source/core/html/FileInputType.h
index 104fc84..2a5ce2e 100644
--- a/Source/core/html/FileInputType.h
+++ b/Source/core/html/FileInputType.h
@@ -56,7 +56,7 @@
     virtual bool valueMissing(const String&) const OVERRIDE;
     virtual String valueMissingText() const OVERRIDE;
     virtual void handleDOMActivateEvent(Event*) OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) const OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) const OVERRIDE;
     virtual bool canSetStringValue() const OVERRIDE;
     virtual bool canChangeFromAnotherType() const OVERRIDE;
     virtual FileList* files() OVERRIDE;
diff --git a/Source/core/html/FormAssociatedElement.cpp b/Source/core/html/FormAssociatedElement.cpp
index cfb6269..ff69e49 100644
--- a/Source/core/html/FormAssociatedElement.cpp
+++ b/Source/core/html/FormAssociatedElement.cpp
@@ -106,7 +106,7 @@
         HTMLFormElement* newForm = 0;
         Element* newFormCandidate = element->treeScope()->getElementById(formId);
         if (newFormCandidate && newFormCandidate->hasTagName(formTag))
-            newForm = static_cast<HTMLFormElement*>(newFormCandidate);
+            newForm = toHTMLFormElement(newFormCandidate);
         return newForm;
     }
 
diff --git a/Source/core/html/FormController.h b/Source/core/html/FormController.h
index d0b2f43..9276e79 100644
--- a/Source/core/html/FormController.h
+++ b/Source/core/html/FormController.h
@@ -23,11 +23,10 @@
 #define FormController_h
 
 #include "core/dom/CheckedRadioButtons.h"
-#include <wtf/Deque.h>
-#include <wtf/Forward.h>
-#include <wtf/ListHashSet.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/ListHashSet.h"
+#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/FormDataList.cpp b/Source/core/html/FormDataList.cpp
index aee7619..6096a23 100644
--- a/Source/core/html/FormDataList.cpp
+++ b/Source/core/html/FormDataList.cpp
@@ -30,15 +30,15 @@
 {
 }
 
-void FormDataList::appendString(const String& s)
+void FormDataList::appendString(const String& string)
 {
-    CString cstr = m_encoding.encode(s.characters(), s.length(), WTF::EntitiesForUnencodables);
-    m_items.append(normalizeLineEndingsToCRLF(cstr));
+    CString encodedString = m_encoding.encode(string, WTF::EntitiesForUnencodables);
+    m_items.append(normalizeLineEndingsToCRLF(encodedString));
 }
 
-void FormDataList::appendString(const CString& s)
+void FormDataList::appendString(const CString& string)
 {
-    m_items.append(s);
+    m_items.append(string);
 }
 
 void FormDataList::appendBlob(PassRefPtr<Blob> blob, const String& filename)
diff --git a/Source/core/html/HTMLAnchorElement.cpp b/Source/core/html/HTMLAnchorElement.cpp
index 05576d4..68b31d3 100644
--- a/Source/core/html/HTMLAnchorElement.cpp
+++ b/Source/core/html/HTMLAnchorElement.cpp
@@ -198,7 +198,7 @@
     RenderImage* renderer = toRenderImage(imageElement->renderer());
 
     // FIXME: This should probably pass true for useTransforms.
-    FloatPoint absolutePosition = renderer->absoluteToLocal(FloatPoint(static_cast<MouseEvent*>(event)->pageX(), static_cast<MouseEvent*>(event)->pageY()));
+    FloatPoint absolutePosition = renderer->absoluteToLocal(FloatPoint(toMouseEvent(event)->pageX(), toMouseEvent(event)->pageY()));
     int x = absolutePosition.x();
     int y = absolutePosition.y();
     url.append('?');
@@ -226,9 +226,9 @@
         if (rendererIsEditable()) {
             // This keeps track of the editable block that the selection was in (if it was in one) just before the link was clicked
             // for the LiveWhenNotFocused editable link behavior
-            if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && static_cast<MouseEvent*>(event)->button() != RightButton && document()->frame() && document()->frame()->selection()) {
+            if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() != RightButton && document()->frame() && document()->frame()->selection()) {
                 setRootEditableElementForSelectionOnMouseDown(document()->frame()->selection()->rootEditableElement());
-                m_wasShiftKeyDownOnMouseDown = static_cast<MouseEvent*>(event)->shiftKey();
+                m_wasShiftKeyDownOnMouseDown = toMouseEvent(event)->shiftKey();
             } else if (event->type() == eventNames().mouseoverEvent) {
                 // These are cleared on mouseover and not mouseout because their values are needed for drag events,
                 // but drag events happen after mouse out events.
@@ -588,7 +588,7 @@
 {
     if (!event->isMouseEvent())
         return NonMouseEvent;
-    return static_cast<MouseEvent*>(event)->shiftKey() ? MouseEventWithShiftKey : MouseEventWithoutShiftKey;
+    return toMouseEvent(event)->shiftKey() ? MouseEventWithShiftKey : MouseEventWithoutShiftKey;
 }
 
 bool HTMLAnchorElement::treatLinkAsLiveForEventType(EventType eventType) const
@@ -623,12 +623,12 @@
 
 bool isEnterKeyKeydownEvent(Event* event)
 {
-    return event->type() == eventNames().keydownEvent && event->isKeyboardEvent() && static_cast<KeyboardEvent*>(event)->keyIdentifier() == "Enter";
+    return event->type() == eventNames().keydownEvent && event->isKeyboardEvent() && toKeyboardEvent(event)->keyIdentifier() == "Enter";
 }
 
 bool isLinkClick(Event* event)
 {
-    return event->type() == eventNames().clickEvent && (!event->isMouseEvent() || static_cast<MouseEvent*>(event)->button() != RightButton);
+    return event->type() == eventNames().clickEvent && (!event->isMouseEvent() || toMouseEvent(event)->button() != RightButton);
 }
 
 bool HTMLAnchorElement::willRespondToMouseClickEvents()
@@ -705,7 +705,7 @@
         handleMouseOver(event);
     else if (event->type() == eventNames().mouseoutEvent)
         handleMouseOut(event);
-    else if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && static_cast<MouseEvent*>(event)->button() == LeftButton)
+    else if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton)
         handleLeftMouseDown(event);
     else if (event->type() == eventNames().gesturetapdownEvent)
         handleGestureTapDown(event);
diff --git a/Source/core/html/HTMLAppletElement.cpp b/Source/core/html/HTMLAppletElement.cpp
index d1ac02c..23bc61f 100644
--- a/Source/core/html/HTMLAppletElement.cpp
+++ b/Source/core/html/HTMLAppletElement.cpp
@@ -72,7 +72,7 @@
     return HTMLPlugInImageElement::rendererIsNeeded(context);
 }
 
-RenderObject* HTMLAppletElement::createRenderer(RenderArena*, RenderStyle* style)
+RenderObject* HTMLAppletElement::createRenderer(RenderStyle* style)
 {
     if (!canEmbedJava())
         return RenderObject::createObject(this, style);
diff --git a/Source/core/html/HTMLAppletElement.h b/Source/core/html/HTMLAppletElement.h
index affbc68..dd3ea7e 100644
--- a/Source/core/html/HTMLAppletElement.h
+++ b/Source/core/html/HTMLAppletElement.h
@@ -37,7 +37,7 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     
     virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     virtual RenderWidget* renderWidgetForJSBindings() const;
     virtual void updateWidget(PluginCreationOption) OVERRIDE;
diff --git a/Source/core/html/HTMLAreaElement.cpp b/Source/core/html/HTMLAreaElement.cpp
index f956d10..c298681 100644
--- a/Source/core/html/HTMLAreaElement.cpp
+++ b/Source/core/html/HTMLAreaElement.cpp
@@ -39,7 +39,6 @@
 
 inline HTMLAreaElement::HTMLAreaElement(const QualifiedName& tagName, Document* document)
     : HTMLAnchorElement(tagName, document)
-    , m_coordsLen(0)
     , m_lastSize(-1, -1)
     , m_shape(Unknown)
 {
@@ -65,7 +64,7 @@
             m_shape = Rect;
         invalidateCachedRegion();
     } else if (name == coordsAttr) {
-        m_coords = newCoordsArray(value.string(), m_coordsLen);
+        m_coords = parseHTMLAreaElementCoords(value.string());
         invalidateCachedRegion();
     } else if (name == altAttr || name == accesskeyAttr) {
         // Do nothing.
@@ -125,7 +124,7 @@
 
 Path HTMLAreaElement::getRegion(const LayoutSize& size) const
 {
-    if (!m_coords && m_shape != Default)
+    if (m_coords.isEmpty() && m_shape != Default)
         return Path();
 
     LayoutUnit width = size.width();
@@ -134,11 +133,11 @@
     // If element omits the shape attribute, select shape based on number of coordinates.
     Shape shape = m_shape;
     if (shape == Unknown) {
-        if (m_coordsLen == 3)
+        if (m_coords.size() == 3)
             shape = Circle;
-        else if (m_coordsLen == 4)
+        else if (m_coords.size() == 4)
             shape = Rect;
-        else if (m_coordsLen >= 6)
+        else if (m_coords.size() >= 6)
             shape = Poly;
     }
 
@@ -146,8 +145,8 @@
     RenderView* renderView = document()->renderView();
     switch (shape) {
         case Poly:
-            if (m_coordsLen >= 6) {
-                int numPoints = m_coordsLen / 2;
+            if (m_coords.size() >= 6) {
+                int numPoints = m_coords.size() / 2;
                 path.moveTo(FloatPoint(minimumValueForLength(m_coords[0], width, renderView), minimumValueForLength(m_coords[1], height, renderView)));
                 for (int i = 1; i < numPoints; ++i)
                     path.addLineTo(FloatPoint(minimumValueForLength(m_coords[i * 2], width, renderView), minimumValueForLength(m_coords[i * 2 + 1], height, renderView)));
@@ -155,14 +154,14 @@
             }
             break;
         case Circle:
-            if (m_coordsLen >= 3) {
+            if (m_coords.size() >= 3) {
                 Length radius = m_coords[2];
                 int r = min(minimumValueForLength(radius, width, renderView), minimumValueForLength(radius, height, renderView));
                 path.addEllipse(FloatRect(minimumValueForLength(m_coords[0], width, renderView) - r, minimumValueForLength(m_coords[1], height, renderView) - r, 2 * r, 2 * r));
             }
             break;
         case Rect:
-            if (m_coordsLen >= 4) {
+            if (m_coords.size() >= 4) {
                 int x0 = minimumValueForLength(m_coords[0], width, renderView);
                 int y0 = minimumValueForLength(m_coords[1], height, renderView);
                 int x1 = minimumValueForLength(m_coords[2], width, renderView);
diff --git a/Source/core/html/HTMLAreaElement.h b/Source/core/html/HTMLAreaElement.h
index 0d3099f..778e1e5 100644
--- a/Source/core/html/HTMLAreaElement.h
+++ b/Source/core/html/HTMLAreaElement.h
@@ -25,7 +25,6 @@
 
 #include "core/html/HTMLAnchorElement.h"
 #include "core/platform/graphics/LayoutRect.h"
-#include <wtf/OwnArrayPtr.h>
 
 namespace WebCore {
 
@@ -64,8 +63,7 @@
     void invalidateCachedRegion();
 
     OwnPtr<Path> m_region;
-    OwnArrayPtr<Length> m_coords;
-    int m_coordsLen;
+    Vector<Length> m_coords;
     LayoutSize m_lastSize;
     Shape m_shape;
 };
diff --git a/Source/core/html/HTMLAttributeNames.in b/Source/core/html/HTMLAttributeNames.in
index b4ce47a..1dfbd91 100644
--- a/Source/core/html/HTMLAttributeNames.in
+++ b/Source/core/html/HTMLAttributeNames.in
@@ -125,6 +125,7 @@
 id
 incremental
 indeterminate
+inputmode
 is
 ismap
 itemid
diff --git a/Source/core/html/HTMLBRElement.cpp b/Source/core/html/HTMLBRElement.cpp
index 54425a4..7113519 100644
--- a/Source/core/html/HTMLBRElement.cpp
+++ b/Source/core/html/HTMLBRElement.cpp
@@ -71,12 +71,12 @@
         HTMLElement::collectStyleForPresentationAttribute(name, value, style);
 }
 
-RenderObject* HTMLBRElement::createRenderer(RenderArena* arena, RenderStyle* style)
+RenderObject* HTMLBRElement::createRenderer(RenderStyle* style)
 {
-     if (style->hasContent())
+    if (style->hasContent())
         return RenderObject::createObject(this, style);
 
-     return new (arena) RenderBR(this);
+    return new (document()->renderArena()) RenderBR(this);
 }
 
 }
diff --git a/Source/core/html/HTMLBRElement.h b/Source/core/html/HTMLBRElement.h
index 7034507..8825e17 100644
--- a/Source/core/html/HTMLBRElement.h
+++ b/Source/core/html/HTMLBRElement.h
@@ -41,7 +41,7 @@
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 };
 
 } // namespace
diff --git a/Source/core/html/HTMLBodyElement.h b/Source/core/html/HTMLBodyElement.h
index fe7e259..a5941f7 100644
--- a/Source/core/html/HTMLBodyElement.h
+++ b/Source/core/html/HTMLBodyElement.h
@@ -93,6 +93,12 @@
     virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
 };
 
+inline HTMLBodyElement* toHTMLBodyElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::bodyTag));
+    return static_cast<HTMLBodyElement*>(node);
+}
+
 } //namespace
 
 #endif
diff --git a/Source/core/html/HTMLButtonElement.cpp b/Source/core/html/HTMLButtonElement.cpp
index 855af64..abbf43c 100644
--- a/Source/core/html/HTMLButtonElement.cpp
+++ b/Source/core/html/HTMLButtonElement.cpp
@@ -58,9 +58,9 @@
     setAttribute(typeAttr, type);
 }
 
-RenderObject* HTMLButtonElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* HTMLButtonElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderButton(this);
+    return new (document()->renderArena()) RenderButton(this);
 }
 
 const AtomicString& HTMLButtonElement::formControlType() const
@@ -125,13 +125,13 @@
     }
 
     if (event->isKeyboardEvent()) {
-        if (event->type() == eventNames().keydownEvent && static_cast<KeyboardEvent*>(event)->keyIdentifier() == "U+0020") {
+        if (event->type() == eventNames().keydownEvent && toKeyboardEvent(event)->keyIdentifier() == "U+0020") {
             setActive(true, true);
             // No setDefaultHandled() - IE dispatches a keypress in this case.
             return;
         }
         if (event->type() == eventNames().keypressEvent) {
-            switch (static_cast<KeyboardEvent*>(event)->charCode()) {
+            switch (toKeyboardEvent(event)->charCode()) {
                 case '\r':
                     dispatchSimulatedClick(event);
                     event->setDefaultHandled();
@@ -142,7 +142,7 @@
                     return;
             }
         }
-        if (event->type() == eventNames().keyupEvent && static_cast<KeyboardEvent*>(event)->keyIdentifier() == "U+0020") {
+        if (event->type() == eventNames().keyupEvent && toKeyboardEvent(event)->keyIdentifier() == "U+0020") {
             if (active())
                 dispatchSimulatedClick(event);
             event->setDefaultHandled();
diff --git a/Source/core/html/HTMLButtonElement.h b/Source/core/html/HTMLButtonElement.h
index 80c096d..37d545e 100644
--- a/Source/core/html/HTMLButtonElement.h
+++ b/Source/core/html/HTMLButtonElement.h
@@ -45,7 +45,7 @@
 
     virtual const AtomicString& formControlType() const;
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     // HTMLFormControlElement always creates one, but buttons don't need it.
     virtual bool alwaysCreateUserAgentShadowRoot() const OVERRIDE { return false; }
diff --git a/Source/core/html/HTMLCanvasElement.cpp b/Source/core/html/HTMLCanvasElement.cpp
index 2dba91d..bd0a8fa 100644
--- a/Source/core/html/HTMLCanvasElement.cpp
+++ b/Source/core/html/HTMLCanvasElement.cpp
@@ -29,7 +29,6 @@
 #include "core/html/HTMLCanvasElement.h"
 
 #include <math.h>
-#include <stdio.h>
 #include "HTMLNames.h"
 #include "bindings/v8/ScriptController.h"
 #include "core/dom/Document.h"
@@ -45,6 +44,7 @@
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/platform/graphics/ImageBuffer.h"
 #include "core/rendering/RenderHTMLCanvas.h"
+#include "wtf/MemoryInstrumentationHashSet.h"
 
 #include "core/html/canvas/WebGLContextAttributes.h"
 #include "core/html/canvas/WebGLRenderingContext.h"
@@ -76,6 +76,7 @@
     , m_originClean(true)
     , m_hasCreatedImageBuffer(false)
     , m_didClearImageBuffer(false)
+    , m_accelerationDisabled(false)
 {
     ASSERT(hasTagName(canvasTag));
     ScriptWrappable::init(this);
@@ -107,16 +108,16 @@
     HTMLElement::parseAttribute(name, value);
 }
 
-RenderObject* HTMLCanvasElement::createRenderer(RenderArena* arena, RenderStyle* style)
+RenderObject* HTMLCanvasElement::createRenderer(RenderStyle* style)
 {
     Frame* frame = document()->frame();
     if (frame && frame->script()->canExecuteScripts(NotAboutToExecuteScript)) {
         m_rendererIsCanvas = true;
-        return new (arena) RenderHTMLCanvas(this);
+        return new (document()->renderArena()) RenderHTMLCanvas(this);
     }
 
     m_rendererIsCanvas = false;
-    return HTMLElement::createRenderer(arena, style);
+    return HTMLElement::createRenderer(style);
 }
 
 void HTMLCanvasElement::attach(const AttachContext& context)
@@ -160,10 +161,8 @@
             return 0;
         if (!m_context) {
             m_context = CanvasRenderingContext2D::create(this, RuntimeEnabledFeatures::experimentalCanvasFeaturesEnabled() ? static_cast<Canvas2DContextAttributes*>(attrs) : 0, document()->inQuirksMode());
-            if (m_context) {
-                // Need to make sure a RenderLayer and compositing layer get created for the Canvas
-                setNeedsStyleRecalc(SyntheticStyleChange);
-            }
+            if (m_context)
+                setNeedsLayerUpdate();
         }
         return m_context.get();
     }
@@ -184,10 +183,8 @@
                 return 0;
             if (!m_context) {
                 m_context = WebGLRenderingContext::create(this, static_cast<WebGLContextAttributes*>(attrs));
-                if (m_context) {
-                    // Need to make sure a RenderLayer and compositing layer get created for the Canvas
-                    setNeedsStyleRecalc(SyntheticStyleChange);
-                }
+                if (m_context)
+                    setNeedsLayerUpdate();
             }
             return m_context.get();
         }
@@ -458,6 +455,9 @@
     if (m_context && !m_context->is2d())
         return false;
 
+    if (m_accelerationDisabled)
+        return false;
+
     Settings* settings = document()->settings();
     if (!settings || !settings->accelerated2dCanvasEnabled())
         return false;
@@ -472,7 +472,7 @@
     return true;
 }
 
-void HTMLCanvasElement::createImageBuffer() const
+void HTMLCanvasElement::createImageBuffer()
 {
     ASSERT(!m_imageBuffer);
 
@@ -499,17 +499,15 @@
     m_imageBuffer = ImageBuffer::create(size(), m_deviceScaleFactor, renderingMode, opacityMode);
     if (!m_imageBuffer)
         return;
-    m_imageBuffer->context()->setShadowsIgnoreTransforms(true);
     m_imageBuffer->context()->setImageInterpolationQuality(DefaultInterpolationQuality);
     if (document()->settings() && !document()->settings()->antialiased2dCanvasEnabled())
         m_imageBuffer->context()->setShouldAntialias(false);
     m_imageBuffer->context()->setStrokeThickness(1);
     m_contextStateSaver = adoptPtr(new GraphicsContextStateSaver(*m_imageBuffer->context()));
 
-    if (m_context && m_context->is2d()) {
-        // Recalculate compositing requirements if acceleration state changed.
-        const_cast<HTMLCanvasElement*>(this)->setNeedsStyleRecalc(SyntheticStyleChange);
-    }
+    // Recalculate compositing requirements if acceleration state changed.
+    if (m_context && m_context->is2d())
+        setNeedsLayerUpdate();
 }
 
 GraphicsContext* HTMLCanvasElement::drawingContext() const
@@ -528,7 +526,7 @@
 ImageBuffer* HTMLCanvasElement::buffer() const
 {
     if (!m_hasCreatedImageBuffer)
-        createImageBuffer();
+        const_cast<HTMLCanvasElement*>(this)->createImageBuffer();
     return m_imageBuffer.get();
 }
 
@@ -542,7 +540,7 @@
     return m_copiedImage.get();
 }
 
-void HTMLCanvasElement::clearImageBuffer() const
+void HTMLCanvasElement::clearImageBuffer()
 {
     ASSERT(m_hasCreatedImageBuffer);
     ASSERT(!m_didClearImageBuffer);
diff --git a/Source/core/html/HTMLCanvasElement.h b/Source/core/html/HTMLCanvasElement.h
index 781477b..34bccfb 100644
--- a/Source/core/html/HTMLCanvasElement.h
+++ b/Source/core/html/HTMLCanvasElement.h
@@ -73,6 +73,8 @@
 
     void setWidth(int);
     void setHeight(int);
+    void setAccelerationDisabled(bool accelerationDisabled) { m_accelerationDisabled = accelerationDisabled; }
+    bool accelerationDisabled() const { return m_accelerationDisabled; }
 
     void setSize(const IntSize& newSize)
     { 
@@ -137,7 +139,7 @@
     HTMLCanvasElement(const QualifiedName&, Document*);
 
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual bool areAuthorShadowsAllowed() const OVERRIDE { return false; }
 
@@ -145,8 +147,8 @@
 
     float targetDeviceScaleFactor() const;
 
-    void createImageBuffer() const;
-    void clearImageBuffer() const;
+    void createImageBuffer();
+    void clearImageBuffer();
 
     void setSurfaceSize(const IntSize&);
 
@@ -161,6 +163,7 @@
     bool m_rendererIsCanvas;
 
     bool m_ignoreReset;
+    bool m_accelerationDisabled;
     FloatRect m_dirtyRect;
 
     float m_deviceScaleFactor;
@@ -169,9 +172,9 @@
     // m_createdImageBuffer means we tried to malloc the buffer.  We didn't necessarily get it.
     mutable bool m_hasCreatedImageBuffer;
     mutable bool m_didClearImageBuffer;
-    mutable OwnPtr<ImageBuffer> m_imageBuffer;
+    OwnPtr<ImageBuffer> m_imageBuffer;
     mutable OwnPtr<GraphicsContextStateSaver> m_contextStateSaver;
-    
+
     mutable RefPtr<Image> m_presentedImage;
     mutable RefPtr<Image> m_copiedImage; // FIXME: This is temporary for platforms that have to copy the image buffer to render (and for CSSCanvasValue).
 };
diff --git a/Source/core/html/HTMLCollection.cpp b/Source/core/html/HTMLCollection.cpp
index b9aa6fb..2e74168 100644
--- a/Source/core/html/HTMLCollection.cpp
+++ b/Source/core/html/HTMLCollection.cpp
@@ -32,8 +32,6 @@
 #include "core/html/HTMLObjectElement.h"
 #include "core/html/HTMLOptionElement.h"
 
-#include <utility>
-
 namespace WebCore {
 
 using namespace HTMLNames;
@@ -205,7 +203,7 @@
         return element->hasLocalName(optionTag) && toHTMLOptionElement(element)->selected();
     case DataListOptions:
         if (element->hasLocalName(optionTag)) {
-            HTMLOptionElement* option = static_cast<HTMLOptionElement*>(element);
+            HTMLOptionElement* option = toHTMLOptionElement(element);
             if (!option->isDisabledFormControl() && !option->value().isEmpty())
                 return true;
         }
diff --git a/Source/core/html/HTMLCollection.h b/Source/core/html/HTMLCollection.h
index a971961..d76c61e 100644
--- a/Source/core/html/HTMLCollection.h
+++ b/Source/core/html/HTMLCollection.h
@@ -23,13 +23,11 @@
 #ifndef HTMLCollection_h
 #define HTMLCollection_h
 
-#include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/LiveNodeList.h"
 #include "core/html/CollectionType.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/HTMLDetailsElement.cpp b/Source/core/html/HTMLDetailsElement.cpp
index 1c5620f..4147245 100644
--- a/Source/core/html/HTMLDetailsElement.cpp
+++ b/Source/core/html/HTMLDetailsElement.cpp
@@ -55,9 +55,9 @@
     ScriptWrappable::init(this);
 }
 
-RenderObject* HTMLDetailsElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* HTMLDetailsElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderBlock(this);
+    return new (document()->renderArena()) RenderBlock(this);
 }
 
 void HTMLDetailsElement::didAddUserAgentShadowRoot(ShadowRoot* root)
diff --git a/Source/core/html/HTMLDetailsElement.h b/Source/core/html/HTMLDetailsElement.h
index 16d97c2..565bba9 100644
--- a/Source/core/html/HTMLDetailsElement.h
+++ b/Source/core/html/HTMLDetailsElement.h
@@ -35,7 +35,7 @@
 private:
     HTMLDetailsElement(const QualifiedName&, Document*);
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const OVERRIDE;
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
diff --git a/Source/core/html/HTMLDocument.cpp b/Source/core/html/HTMLDocument.cpp
index d157c4c..a9ceaf4 100644
--- a/Source/core/html/HTMLDocument.cpp
+++ b/Source/core/html/HTMLDocument.cpp
@@ -77,20 +77,6 @@
 {
 }
 
-int HTMLDocument::width()
-{
-    updateLayoutIgnorePendingStylesheets();
-    FrameView* frameView = view();
-    return frameView ? frameView->contentsWidth() : 0;
-}
-
-int HTMLDocument::height()
-{
-    updateLayoutIgnorePendingStylesheets();
-    FrameView* frameView = view();
-    return frameView ? frameView->contentsHeight() : 0;
-}
-
 String HTMLDocument::dir()
 {
     HTMLElement* b = body();
@@ -144,60 +130,48 @@
     return false;
 }
 
+inline HTMLBodyElement* HTMLDocument::bodyAsHTMLBodyElement() const
+{
+    HTMLElement* element = body();
+    return (element && element->hasTagName(bodyTag)) ? toHTMLBodyElement(element) : 0;
+}
+
 String HTMLDocument::bgColor()
 {
-    HTMLElement* b = body();
-    HTMLBodyElement* bodyElement = (b && b->hasTagName(bodyTag)) ? static_cast<HTMLBodyElement*>(b) : 0;
-
-    if (!bodyElement)
-        return String();
-    return bodyElement->bgColor();
+    if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement())
+        return bodyElement->bgColor();
+    return String();
 }
 
 void HTMLDocument::setBgColor(const String& value)
 {
-    HTMLElement* b = body();
-    HTMLBodyElement* bodyElement = (b && b->hasTagName(bodyTag)) ? static_cast<HTMLBodyElement*>(b) : 0;
-
-    if (bodyElement)
+    if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement())
         bodyElement->setBgColor(value);
 }
 
 String HTMLDocument::fgColor()
 {
-    HTMLElement* b = body();
-    HTMLBodyElement* bodyElement = (b && b->hasTagName(bodyTag)) ? static_cast<HTMLBodyElement*>(b) : 0;
-
-    if (!bodyElement)
-        return String();
-    return bodyElement->text();
+    if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement())
+        return bodyElement->text();
+    return String();
 }
 
 void HTMLDocument::setFgColor(const String& value)
 {
-    HTMLElement* b = body();
-    HTMLBodyElement* bodyElement = (b && b->hasTagName(bodyTag)) ? static_cast<HTMLBodyElement*>(b) : 0;
-
-    if (bodyElement)
+    if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement())
         bodyElement->setText(value);
 }
 
 String HTMLDocument::alinkColor()
 {
-    HTMLElement* b = body();
-    HTMLBodyElement* bodyElement = (b && b->hasTagName(bodyTag)) ? static_cast<HTMLBodyElement*>(b) : 0;
-
-    if (!bodyElement)
-        return String();
-    return bodyElement->aLink();
+    if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement())
+        return bodyElement->aLink();
+    return String();
 }
 
 void HTMLDocument::setAlinkColor(const String& value)
 {
-    HTMLElement* b = body();
-    HTMLBodyElement* bodyElement = (b && b->hasTagName(bodyTag)) ? static_cast<HTMLBodyElement*>(b) : 0;
-
-    if (bodyElement) {
+    if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement()) {
         // This check is a bit silly, but some benchmarks like to set the
         // document's link colors over and over to the same value and we
         // don't want to incur a style update each time.
@@ -208,20 +182,14 @@
 
 String HTMLDocument::linkColor()
 {
-    HTMLElement* b = body();
-    HTMLBodyElement* bodyElement = (b && b->hasTagName(bodyTag)) ? static_cast<HTMLBodyElement*>(b) : 0;
-
-    if (!bodyElement)
-        return String();
-    return bodyElement->link();
+    if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement())
+        return bodyElement->link();
+    return String();
 }
 
 void HTMLDocument::setLinkColor(const String& value)
 {
-    HTMLElement* b = body();
-    HTMLBodyElement* bodyElement = (b && b->hasTagName(bodyTag)) ? static_cast<HTMLBodyElement*>(b) : 0;
-
-    if (bodyElement) {
+    if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement()) {
         // This check is a bit silly, but some benchmarks like to set the
         // document's link colors over and over to the same value and we
         // don't want to incur a style update each time.
@@ -232,20 +200,14 @@
 
 String HTMLDocument::vlinkColor()
 {
-    HTMLElement* b = body();
-    HTMLBodyElement* bodyElement = (b && b->hasTagName(bodyTag)) ? static_cast<HTMLBodyElement*>(b) : 0;
-
-    if (!bodyElement)
-        return String();
-    return bodyElement->vLink();
+    if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement())
+        return bodyElement->vLink();
+    return String();
 }
 
 void HTMLDocument::setVlinkColor(const String& value)
 {
-    HTMLElement* b = body();
-    HTMLBodyElement* bodyElement = (b && b->hasTagName(bodyTag)) ? static_cast<HTMLBodyElement*>(b) : 0;
-
-    if (bodyElement) {
+    if (HTMLBodyElement* bodyElement = bodyAsHTMLBodyElement()) {
         // This check is a bit silly, but some benchmarks like to set the
         // document's link colors over and over to the same value and we
         // don't want to incur a style update each time.
diff --git a/Source/core/html/HTMLDocument.h b/Source/core/html/HTMLDocument.h
index 78f067a..82f46a3 100644
--- a/Source/core/html/HTMLDocument.h
+++ b/Source/core/html/HTMLDocument.h
@@ -25,12 +25,12 @@
 
 #include "core/dom/Document.h"
 #include "core/loader/cache/CachedResourceClient.h"
-#include <wtf/HashCountedSet.h>
-#include <wtf/text/AtomicStringHash.h>
+#include "wtf/HashCountedSet.h"
 
 namespace WebCore {
 
 class FrameView;
+class HTMLBodyElement;
 class HTMLElement;
 
 class HTMLDocument : public Document, public CachedResourceClient {
@@ -41,9 +41,6 @@
     }
     virtual ~HTMLDocument();
 
-    int width();
-    int height();
-
     String dir();
     void setDir(const String&);
 
@@ -80,6 +77,7 @@
     HTMLDocument(Frame*, const KURL&, DocumentClassFlags extendedDocumentClasses = DefaultDocumentClass);
 
 private:
+    HTMLBodyElement* bodyAsHTMLBodyElement() const;
     void addItemToMap(HashCountedSet<AtomicStringImpl*>&, const AtomicString&);
     void removeItemFromMap(HashCountedSet<AtomicStringImpl*>&, const AtomicString&);
 
diff --git a/Source/core/html/HTMLDocument.idl b/Source/core/html/HTMLDocument.idl
index 889f741..860900f 100644
--- a/Source/core/html/HTMLDocument.idl
+++ b/Source/core/html/HTMLDocument.idl
@@ -32,14 +32,12 @@
 
     // Extensions
 
-    [Replaceable] readonly attribute HTMLAllCollection all;
+    [Replaceable, ImplementedAs=allForBinding] readonly attribute HTMLAllCollection all;
 
     [DeprecateAs=DocumentClear] void clear();
 
-    readonly attribute long width;
-    readonly attribute long height;
-             [TreatNullAs=NullString] attribute DOMString dir;
-             [TreatNullAs=NullString] attribute DOMString designMode;
+    [TreatNullAs=NullString] attribute DOMString dir;
+    [TreatNullAs=NullString] attribute DOMString designMode;
     readonly attribute DOMString compatMode;
 
     readonly attribute Element activeElement;
diff --git a/Source/core/html/HTMLElement.cpp b/Source/core/html/HTMLElement.cpp
index 5953c68..44c6176 100644
--- a/Source/core/html/HTMLElement.cpp
+++ b/Source/core/html/HTMLElement.cpp
@@ -38,6 +38,7 @@
 #include "core/dom/EventListener.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/ExceptionCode.h"
+#include "core/dom/KeyboardEvent.h"
 #include "core/dom/NodeTraversal.h"
 #include "core/dom/Text.h"
 #include "core/editing/markup.h"
@@ -48,6 +49,7 @@
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/loader/FrameLoader.h"
 #include "core/page/Frame.h"
+#include "core/page/Settings.h"
 #include "core/rendering/RenderWordBreak.h"
 #include <wtf/StdLibExtras.h>
 #include <wtf/text/CString.h>
@@ -143,7 +145,7 @@
 {
     if (name == alignAttr || name == contenteditableAttr || name == hiddenAttr || name == langAttr || name.matches(XMLNames::langAttr) || name == draggableAttr || name == dirAttr)
         return true;
-    return StyledElement::isPresentationAttribute(name);
+    return Element::isPresentationAttribute(name);
 }
 
 void HTMLElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
@@ -187,7 +189,7 @@
         if (!fastHasAttribute(XMLNames::langAttr))
             mapLanguageAttributeToLocale(value, style);
     } else
-        StyledElement::collectStyleForPresentationAttribute(name, value, style);
+        Element::collectStyleForPresentationAttribute(name, value, style);
 }
 
 AtomicString HTMLElement::eventNameForAttributeName(const QualifiedName& attrName) const
@@ -277,7 +279,7 @@
 void HTMLElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
     if (isIdAttributeName(name) || name == classAttr || name == styleAttr)
-        return StyledElement::parseAttribute(name, value);
+        return Element::parseAttribute(name, value);
 
     if (name == dirAttr)
         dirAttributeChanged(value);
@@ -598,6 +600,23 @@
     return false;
 }
 
+bool HTMLElement::supportsSpatialNavigationFocus() const
+{
+    // This function checks whether the element satisfies the extended criteria
+    // for the element to be focusable, introduced by spatial navigation feature,
+    // i.e. checks if click or keyboard event handler is specified.
+    // This is the way to make it possible to navigate to (focus) elements
+    // which web designer meant for being active (made them respond to click events).
+
+    if (!document()->settings() || !document()->settings()->spatialNavigationEnabled())
+        return false;
+    EventTarget* target = const_cast<HTMLElement*>(this);
+    return target->hasEventListeners(eventNames().clickEvent)
+        || target->hasEventListeners(eventNames().keydownEvent)
+        || target->hasEventListeners(eventNames().keypressEvent)
+        || target->hasEventListeners(eventNames().keyupEvent);
+}
+
 bool HTMLElement::supportsFocus() const
 {
     // FIXME: supportsFocus() can be called when layout is not up to date.
@@ -605,7 +624,8 @@
     // But supportsFocus must return true when the element is editable, or else
     // it won't be focusable. Furthermore, supportsFocus cannot just return true
     // always or else tabIndex() will change for all HTML elements.
-    return Element::supportsFocus() || (rendererIsEditable() && parentNode() && !parentNode()->rendererIsEditable());
+    return Element::supportsFocus() || (rendererIsEditable() && parentNode() && !parentNode()->rendererIsEditable())
+        || supportsSpatialNavigationFocus();
 }
 
 String HTMLElement::contentEditable() const
@@ -732,13 +752,13 @@
         if (frame && frame->loader()->subframeLoader()->allowPlugins(NotAboutToInstantiatePlugin))
             return false;
     }
-    return StyledElement::rendererIsNeeded(context);
+    return Element::rendererIsNeeded(context);
 }
 
-RenderObject* HTMLElement::createRenderer(RenderArena* arena, RenderStyle* style)
+RenderObject* HTMLElement::createRenderer(RenderStyle* style)
 {
     if (hasLocalName(wbrTag))
-        return new (arena) RenderWordBreak(this);
+        return new (document()->renderArena()) RenderWordBreak(this);
     return RenderObject::createObject(this, style);
 }
 
@@ -746,7 +766,7 @@
 {
     for (ContainerNode* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode()) {
         if (ancestor->hasTagName(formTag))
-            return static_cast<HTMLFormElement*>(ancestor);
+            return toHTMLFormElement(ancestor);
     }
     return 0;
 }
@@ -786,7 +806,7 @@
 
 void HTMLElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
 {
-    StyledElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
+    Element::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
     adjustDirectionalityIfNeededAfterChildrenChanged(beforeChange, childCountDelta);
 }
 
@@ -1029,6 +1049,28 @@
     style->setProperty(propertyID, cssValuePool().createColorValue(parsedColor.rgb()));
 }
 
+void HTMLElement::defaultEventHandler(Event* event)
+{
+    if (event->type() == eventNames().keypressEvent && event->isKeyboardEvent()) {
+        handleKeypressEvent(toKeyboardEvent(event));
+        if (event->defaultHandled())
+            return;
+    }
+
+    Element::defaultEventHandler(event);
+}
+
+void HTMLElement::handleKeypressEvent(KeyboardEvent* event)
+{
+    if (!document()->settings() || !document()->settings()->spatialNavigationEnabled() || !supportsFocus())
+        return;
+    int charCode = event->charCode();
+    if (charCode == '\r' || charCode == ' ') {
+        dispatchSimulatedClick(event);
+        event->setDefaultHandled();
+    }
+}
+
 } // namespace WebCore
 
 #ifndef NDEBUG
diff --git a/Source/core/html/HTMLElement.h b/Source/core/html/HTMLElement.h
index 3f93fc2..4918a7a 100644
--- a/Source/core/html/HTMLElement.h
+++ b/Source/core/html/HTMLElement.h
@@ -23,7 +23,7 @@
 #ifndef HTMLElement_h
 #define HTMLElement_h
 
-#include "core/dom/StyledElement.h"
+#include "core/dom/Element.h"
 
 namespace WebCore {
 
@@ -37,7 +37,7 @@
     TranslateAttributeInherit
 };
 
-class HTMLElement : public StyledElement {
+class HTMLElement : public Element {
 public:
     static PassRefPtr<HTMLElement> create(const QualifiedName& tagName, Document*);
 
@@ -79,7 +79,7 @@
     bool ieForbidsInsertHTML() const;
 
     virtual bool rendererIsNeeded(const NodeRenderingContext&);
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     HTMLFormElement* form() const { return virtualForm(); }
 
@@ -92,6 +92,8 @@
 
     virtual bool isLabelable() const { return false; }
 
+    virtual void defaultEventHandler(Event*) OVERRIDE;
+
 protected:
     HTMLElement(const QualifiedName& tagName, Document*, ConstructionType);
 
@@ -127,6 +129,9 @@
     TranslateAttributeMode translateAttributeMode() const;
 
     AtomicString eventNameForAttributeName(const QualifiedName& attrName) const;
+
+    void handleKeypressEvent(KeyboardEvent*);
+    bool supportsSpatialNavigationFocus() const;
 };
 
 inline HTMLElement* toHTMLElement(Node* node)
@@ -145,7 +150,7 @@
 void toHTMLElement(const HTMLElement*);
 
 inline HTMLElement::HTMLElement(const QualifiedName& tagName, Document* document, ConstructionType type = CreateHTMLElement)
-    : StyledElement(tagName, document, type)
+    : Element(tagName, document, type)
 {
     ASSERT(tagName.localName().impl());
     ScriptWrappable::init(this);
diff --git a/Source/core/html/HTMLEmbedElement.cpp b/Source/core/html/HTMLEmbedElement.cpp
index 909f822..6aabaf2 100644
--- a/Source/core/html/HTMLEmbedElement.cpp
+++ b/Source/core/html/HTMLEmbedElement.cpp
@@ -27,17 +27,13 @@
 #include "CSSPropertyNames.h"
 #include "HTMLNames.h"
 #include "core/dom/Attribute.h"
-#include "core/html/HTMLDocument.h"
 #include "core/html/HTMLImageLoader.h"
 #include "core/html/HTMLObjectElement.h"
 #include "core/html/PluginDocument.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/DocumentLoader.h"
 #include "core/loader/FrameLoader.h"
 #include "core/page/Frame.h"
-#include "core/page/Settings.h"
 #include "core/rendering/RenderEmbeddedObject.h"
-#include "core/rendering/RenderImage.h"
 #include "core/rendering/RenderWidget.h"
 
 namespace WebCore {
diff --git a/Source/core/html/HTMLFieldSetElement.cpp b/Source/core/html/HTMLFieldSetElement.cpp
index d441041..21a386b 100644
--- a/Source/core/html/HTMLFieldSetElement.cpp
+++ b/Source/core/html/HTMLFieldSetElement.cpp
@@ -54,7 +54,7 @@
 {
     for (Element* element = ElementTraversal::firstWithin(base); element; element = ElementTraversal::next(element, base)) {
         if (element->isFormControlElement())
-            static_cast<HTMLFormControlElement*>(element)->ancestorDisabledStateWasChanged();
+            toHTMLFormControlElement(element)->ancestorDisabledStateWasChanged();
     }
 }
 
@@ -85,9 +85,9 @@
     return fieldset;
 }
 
-RenderObject* HTMLFieldSetElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* HTMLFieldSetElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderFieldset(this);
+    return new (document()->renderArena()) RenderFieldset(this);
 }
 
 HTMLLegendElement* HTMLFieldSetElement::legend() const
@@ -123,7 +123,7 @@
         if (!element->isFormControlElement())
             continue;
 
-        m_associatedElements.append(static_cast<HTMLFormControlElement*>(element));
+        m_associatedElements.append(toHTMLFormControlElement(element));
     }
 }
 
diff --git a/Source/core/html/HTMLFieldSetElement.h b/Source/core/html/HTMLFieldSetElement.h
index 587f2fe..c63444f 100644
--- a/Source/core/html/HTMLFieldSetElement.h
+++ b/Source/core/html/HTMLFieldSetElement.h
@@ -25,7 +25,6 @@
 #define HTMLFieldSetElement_h
 
 #include "core/html/HTMLFormControlElement.h"
-#include <wtf/OwnPtr.h>
 
 namespace WebCore {
 
@@ -50,7 +49,7 @@
 
     virtual bool isEnumeratable() const { return true; }
     virtual bool supportsFocus() const;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual const AtomicString& formControlType() const;
     virtual bool recalcWillValidate() const { return false; }
     virtual void childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta) OVERRIDE;
diff --git a/Source/core/html/HTMLFormControlElement.cpp b/Source/core/html/HTMLFormControlElement.cpp
index 48056cb..6fc0026 100644
--- a/Source/core/html/HTMLFormControlElement.cpp
+++ b/Source/core/html/HTMLFormControlElement.cpp
@@ -55,6 +55,7 @@
     , m_willValidate(true)
     , m_isValid(true)
     , m_wasChangedSinceLastFormControlChangeEvent(false)
+    , m_wasFocusedByMouse(false)
     , m_hasAutofocused(false)
 {
     setForm(form ? form : findFormAncestor());
@@ -316,14 +317,39 @@
 
 bool HTMLFormControlElement::isKeyboardFocusable(KeyboardEvent*) const
 {
-    return isFocusable() && document()->frame();
+    // Skip tabIndex check in a parent class.
+    return isFocusable();
 }
 
-bool HTMLFormControlElement::isMouseFocusable() const
+bool HTMLFormControlElement::shouldShowFocusRingOnMouseFocus() const
 {
     return false;
 }
 
+void HTMLFormControlElement::dispatchFocusEvent(PassRefPtr<Node> oldFocusedNode, FocusDirection direction)
+{
+    m_wasFocusedByMouse = direction == FocusDirectionMouse;
+    HTMLElement::dispatchFocusEvent(oldFocusedNode, direction);
+}
+
+bool HTMLFormControlElement::shouldHaveFocusAppearance() const
+{
+    ASSERT(focused());
+    return shouldShowFocusRingOnMouseFocus() || !m_wasFocusedByMouse;
+}
+
+void HTMLFormControlElement::willCallDefaultEventHandler(const Event& event)
+{
+    if (!event.isKeyboardEvent() || event.type() != eventNames().keydownEvent)
+        return;
+    if (!m_wasFocusedByMouse)
+        return;
+    m_wasFocusedByMouse = false;
+    if (renderer())
+        renderer()->repaint();
+}
+
+
 short HTMLFormControlElement::tabIndex() const
 {
     // Skip the supportsFocus check in HTMLElement.
@@ -396,10 +422,12 @@
         m_validationMessage->requestToHideMessage();
 }
 
-bool HTMLFormControlElement::checkValidity(Vector<RefPtr<FormAssociatedElement> >* unhandledInvalidControls)
+bool HTMLFormControlElement::checkValidity(Vector<RefPtr<FormAssociatedElement> >* unhandledInvalidControls, CheckValidityDispatchEvents dispatchEvents)
 {
     if (!willValidate() || isValidFormControlElement())
         return true;
+    if (dispatchEvents == CheckValidityDispatchEventsNone)
+        return false;
     // An event handler can deref this object.
     RefPtr<HTMLFormControlElement> protector(this);
     RefPtr<Document> originalDocument(document());
@@ -460,7 +488,7 @@
 {
     for (; node; node = node->parentNode()) {
         if (node->isElementNode() && toElement(node)->isFormControlElement())
-            return static_cast<HTMLFormControlElement*>(node);
+            return toHTMLFormControlElement(node);
     }
     return 0;
 }
diff --git a/Source/core/html/HTMLFormControlElement.h b/Source/core/html/HTMLFormControlElement.h
index 7edb7bd..6d0a644 100644
--- a/Source/core/html/HTMLFormControlElement.h
+++ b/Source/core/html/HTMLFormControlElement.h
@@ -84,10 +84,12 @@
     virtual bool isActivatedSubmit() const { return false; }
     virtual void setActivatedSubmit(bool) { }
 
+    enum CheckValidityDispatchEvents { CheckValidityDispatchEventsAllowed, CheckValidityDispatchEventsNone };
+
     virtual bool willValidate() const;
     void updateVisibleValidationMessage();
     void hideVisibleValidationMessage();
-    bool checkValidity(Vector<RefPtr<FormAssociatedElement> >* unhandledInvalidControls = 0);
+    bool checkValidity(Vector<RefPtr<FormAssociatedElement> >* unhandledInvalidControls = 0, CheckValidityDispatchEvents = CheckValidityDispatchEventsAllowed);
     // This must be called when a validation constraint or control value is changed.
     void setNeedsValidityCheck();
     virtual void setCustomValidity(const String&) OVERRIDE;
@@ -119,7 +121,10 @@
     virtual bool supportsFocus() const OVERRIDE;
     virtual bool rendererIsFocusable() const OVERRIDE;
     virtual bool isKeyboardFocusable(KeyboardEvent*) const;
-    virtual bool isMouseFocusable() const;
+    virtual bool shouldShowFocusRingOnMouseFocus() const;
+    virtual bool shouldHaveFocusAppearance() const OVERRIDE;
+    virtual void dispatchFocusEvent(PassRefPtr<Node> oldFocusedNode, FocusDirection) OVERRIDE;
+    virtual void willCallDefaultEventHandler(const Event&) OVERRIDE;
 
     virtual void didRecalcStyle(StyleChange) OVERRIDE;
 
@@ -165,10 +170,22 @@
     bool m_isValid : 1;
 
     bool m_wasChangedSinceLastFormControlChangeEvent : 1;
-
+    bool m_wasFocusedByMouse : 1;
     bool m_hasAutofocused : 1;
 };
 
+inline HTMLFormControlElement* toHTMLFormControlElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->isElementNode() && toElement(node)->isFormControlElement()));
+    return static_cast<HTMLFormControlElement*>(node);
+}
+
+inline HTMLFormControlElement* toHTMLFormControlElement(FormAssociatedElement* control)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!control || control->isFormControlElement());
+    return static_cast<HTMLFormControlElement*>(control);
+}
+
 } // namespace
 
 #endif
diff --git a/Source/core/html/HTMLFormControlsCollection.cpp b/Source/core/html/HTMLFormControlsCollection.cpp
index ac6fca4..f1f06aa 100644
--- a/Source/core/html/HTMLFormControlsCollection.cpp
+++ b/Source/core/html/HTMLFormControlsCollection.cpp
@@ -56,15 +56,14 @@
     ASSERT(ownerNode());
     ASSERT(ownerNode()->hasTagName(formTag) || ownerNode()->hasTagName(fieldsetTag));
     if (ownerNode()->hasTagName(formTag))
-        return static_cast<HTMLFormElement*>(ownerNode())->associatedElements();
+        return toHTMLFormElement(ownerNode())->associatedElements();
     return static_cast<HTMLFieldSetElement*>(ownerNode())->associatedElements();
 }
 
 const Vector<HTMLImageElement*>& HTMLFormControlsCollection::formImageElements() const
 {
     ASSERT(ownerNode());
-    ASSERT(ownerNode()->hasTagName(formTag));
-    return static_cast<HTMLFormElement*>(ownerNode())->imageElements();
+    return toHTMLFormElement(ownerNode())->imageElements();
 }
 
 Element* HTMLFormControlsCollection::virtualItemAfter(unsigned& offset, Element* previousItem) const
diff --git a/Source/core/html/HTMLFormElement.cpp b/Source/core/html/HTMLFormElement.cpp
index 633d4b9..e9988d1 100644
--- a/Source/core/html/HTMLFormElement.cpp
+++ b/Source/core/html/HTMLFormElement.cpp
@@ -37,25 +37,14 @@
 #include "core/dom/NamedNodesCollection.h"
 #include "core/dom/NodeRenderingContext.h"
 #include "core/dom/NodeTraversal.h"
-#include "core/fileapi/FileList.h"
-#include "core/html/DOMFormData.h"
 #include "core/html/FormController.h"
-#include "core/html/FormDataList.h"
 #include "core/html/HTMLCollection.h"
-#include "core/html/HTMLDocument.h"
 #include "core/html/HTMLImageElement.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/ValidityState.h"
 #include "core/loader/FormState.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/page/DOMWindow.h"
 #include "core/page/Frame.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/FileSystem.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "core/platform/network/FormData.h"
 #include "core/rendering/RenderTextControl.h"
 
 using namespace std;
@@ -186,13 +175,13 @@
         FormAssociatedElement* formAssociatedElement = m_associatedElements[i];
         if (!formAssociatedElement->isFormControlElement())
             continue;
-        HTMLFormControlElement* formElement = static_cast<HTMLFormControlElement*>(formAssociatedElement);
-        if (formElement->isSuccessfulSubmitButton()) {
-            if (formElement->renderer()) {
-                formElement->dispatchSimulatedClick(event);
+        HTMLFormControlElement* control = toHTMLFormControlElement(formAssociatedElement);
+        if (control->isSuccessfulSubmitButton()) {
+            if (control->renderer()) {
+                control->dispatchSimulatedClick(event);
                 return;
             }
-        } else if (formElement->canTriggerImplicitSubmission())
+        } else if (control->canTriggerImplicitSubmission())
             ++submissionTriggerCount;
     }
     if (fromImplicitSubmissionTrigger && submissionTriggerCount == 1)
@@ -203,7 +192,7 @@
 {
     for (Node* node = event->target()->toNode(); node; node = node->parentNode()) {
         if (node->isElementNode() && toElement(node)->isFormControlElement())
-            return static_cast<HTMLFormControlElement*>(node);
+            return toHTMLFormControlElement(node);
     }
     return 0;
 }
@@ -220,11 +209,11 @@
 
     for (unsigned i = 0; i < m_associatedElements.size(); ++i) {
         if (m_associatedElements[i]->isFormControlElement())
-            static_cast<HTMLFormControlElement*>(m_associatedElements[i])->hideVisibleValidationMessage();
+            toHTMLFormControlElement(m_associatedElements[i])->hideVisibleValidationMessage();
     }
 
     Vector<RefPtr<FormAssociatedElement> > unhandledInvalidControls;
-    if (!checkInvalidControlsAndCollectUnhandled(unhandledInvalidControls))
+    if (!checkInvalidControlsAndCollectUnhandled(&unhandledInvalidControls))
         return true;
     // Because the form has invalid controls, we abort the form submission and
     // show a validation message on a focusable form control.
@@ -242,7 +231,7 @@
             unhandled->scrollIntoViewIfNeeded(false);
             unhandled->focus();
             if (unhandled->isFormControlElement())
-                static_cast<HTMLFormControlElement*>(unhandled)->updateVisibleValidationMessage();
+                toHTMLFormControlElement(unhandled)->updateVisibleValidationMessage();
             break;
         }
     }
@@ -344,7 +333,7 @@
         if (!associatedElement->isFormControlElement())
             continue;
         if (needButtonActivation) {
-            HTMLFormControlElement* control = static_cast<HTMLFormControlElement*>(associatedElement);
+            HTMLFormControlElement* control = toHTMLFormControlElement(associatedElement);
             if (control->isActivatedSubmit())
                 needButtonActivation = false;
             else if (firstSuccessfulSubmitButton == 0 && control->isSuccessfulSubmitButton())
@@ -379,7 +368,7 @@
 
     for (unsigned i = 0; i < m_associatedElements.size(); ++i) {
         if (m_associatedElements[i]->isFormControlElement())
-            static_cast<HTMLFormControlElement*>(m_associatedElements[i])->reset();
+            toHTMLFormControlElement(m_associatedElements[i])->reset();
     }
 
     m_isInResetFunction = false;
@@ -625,7 +614,7 @@
     for (unsigned i = 0; i < m_associatedElements.size(); ++i) {
         if (!m_associatedElements[i]->isFormControlElement())
             continue;
-        HTMLFormControlElement* control = static_cast<HTMLFormControlElement*>(m_associatedElements[i]);
+        HTMLFormControlElement* control = toHTMLFormControlElement(m_associatedElements[i]);
         if (control->isSuccessfulSubmitButton())
             return control;
     }
@@ -636,10 +625,15 @@
 bool HTMLFormElement::checkValidity()
 {
     Vector<RefPtr<FormAssociatedElement> > controls;
-    return !checkInvalidControlsAndCollectUnhandled(controls);
+    return !checkInvalidControlsAndCollectUnhandled(&controls);
 }
 
-bool HTMLFormElement::checkInvalidControlsAndCollectUnhandled(Vector<RefPtr<FormAssociatedElement> >& unhandledInvalidControls)
+bool HTMLFormElement::checkValidityWithoutDispatchingEvents()
+{
+    return !checkInvalidControlsAndCollectUnhandled(0, HTMLFormControlElement::CheckValidityDispatchEventsNone);
+}
+
+bool HTMLFormElement::checkInvalidControlsAndCollectUnhandled(Vector<RefPtr<FormAssociatedElement> >* unhandledInvalidControls, HTMLFormControlElement::CheckValidityDispatchEvents dispatchEvents)
 {
     RefPtr<HTMLFormElement> protector(this);
     // Copy m_associatedElements because event handlers called from
@@ -651,22 +645,22 @@
     bool hasInvalidControls = false;
     for (unsigned i = 0; i < elements.size(); ++i) {
         if (elements[i]->form() == this && elements[i]->isFormControlElement()) {
-            HTMLFormControlElement* control = static_cast<HTMLFormControlElement*>(elements[i].get());
-            if (!control->checkValidity(&unhandledInvalidControls) && control->form() == this)
+            HTMLFormControlElement* control = toHTMLFormControlElement(elements[i].get());
+            if (!control->checkValidity(unhandledInvalidControls, dispatchEvents) && control->form() == this)
                 hasInvalidControls = true;
         }
     }
     return hasInvalidControls;
 }
 
-HTMLFormControlElement* HTMLFormElement::elementForAlias(const AtomicString& alias)
+Node* HTMLFormElement::elementForAlias(const AtomicString& alias)
 {
     if (alias.isEmpty() || !m_elementAliases)
         return 0;
     return m_elementAliases->get(alias.impl());
 }
 
-void HTMLFormElement::addElementAlias(HTMLFormControlElement* element, const AtomicString& alias)
+void HTMLFormElement::addElementAlias(Node* element, const AtomicString& alias)
 {
     if (alias.isEmpty())
         return;
@@ -679,7 +673,7 @@
 {
     elements()->namedItems(name, namedItems);
 
-    HTMLFormControlElement* aliasElement = elementForAlias(name);
+    Node* aliasElement = elementForAlias(name);
     if (aliasElement) {
         if (namedItems.find(aliasElement) == notFound) {
             // We have seen it before but it is gone now. Still, we need to return it.
@@ -688,7 +682,7 @@
         }
     }
     if (namedItems.size() && namedItems.first() != aliasElement)
-        addElementAlias(static_cast<HTMLFormControlElement*>(namedItems.first().get()), name);
+        addElementAlias(namedItems.first().get(), name);
 }
 
 bool HTMLFormElement::shouldAutocomplete() const
diff --git a/Source/core/html/HTMLFormElement.h b/Source/core/html/HTMLFormElement.h
index dc0b527..d745ea2 100644
--- a/Source/core/html/HTMLFormElement.h
+++ b/Source/core/html/HTMLFormElement.h
@@ -26,6 +26,7 @@
 
 #include "core/dom/CheckedRadioButtons.h"
 #include "core/html/HTMLElement.h"
+#include "core/html/HTMLFormControlElement.h"
 #include "core/loader/FormState.h"
 #include "core/loader/FormSubmission.h"
 #include <wtf/OwnPtr.h>
@@ -100,6 +101,7 @@
     HTMLFormControlElement* defaultButton() const;
 
     bool checkValidity();
+    bool checkValidityWithoutDispatchingEvents();
 
     enum AutocompleteResult {
         AutocompleteResultSuccess,
@@ -114,8 +116,8 @@
     DEFINE_ATTRIBUTE_EVENT_LISTENER(autocomplete);
     DEFINE_ATTRIBUTE_EVENT_LISTENER(autocompleteerror);
 
-    HTMLFormControlElement* elementForAlias(const AtomicString&);
-    void addElementAlias(HTMLFormControlElement*, const AtomicString& alias);
+    Node* elementForAlias(const AtomicString&);
+    void addElementAlias(Node*, const AtomicString& alias);
 
     CheckedRadioButtons& checkedRadioButtons() { return m_checkedRadioButtons; }
 
@@ -153,9 +155,9 @@
     // Validates each of the controls, and stores controls of which 'invalid'
     // event was not canceled to the specified vector. Returns true if there
     // are any invalid controls in this form.
-    bool checkInvalidControlsAndCollectUnhandled(Vector<RefPtr<FormAssociatedElement> >&);
+    bool checkInvalidControlsAndCollectUnhandled(Vector<RefPtr<FormAssociatedElement> >*, HTMLFormControlElement::CheckValidityDispatchEvents = HTMLFormControlElement::CheckValidityDispatchEventsAllowed);
 
-    typedef HashMap<RefPtr<AtomicStringImpl>, RefPtr<HTMLFormControlElement> > AliasMap;
+    typedef HashMap<RefPtr<AtomicStringImpl>, RefPtr<Node> > AliasMap;
 
     FormSubmission::Attributes m_attributes;
     OwnPtr<AliasMap> m_elementAliases;
@@ -181,6 +183,12 @@
     Timer<HTMLFormElement> m_requestAutocompleteTimer;
 };
 
+inline HTMLFormElement* toHTMLFormElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::formTag));
+    return static_cast<HTMLFormElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif // HTMLFormElement_h
diff --git a/Source/core/html/HTMLFrameElement.cpp b/Source/core/html/HTMLFrameElement.cpp
index c8e3d5d..f3ade9c 100644
--- a/Source/core/html/HTMLFrameElement.cpp
+++ b/Source/core/html/HTMLFrameElement.cpp
@@ -52,9 +52,9 @@
     return isURLAllowed();
 }
 
-RenderObject* HTMLFrameElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* HTMLFrameElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderFrame(this);
+    return new (document()->renderArena()) RenderFrame(this);
 }
 
 static inline HTMLFrameSetElement* containingFrameSetElement(Node* node)
diff --git a/Source/core/html/HTMLFrameElement.h b/Source/core/html/HTMLFrameElement.h
index 04e0fea..087d7ab 100644
--- a/Source/core/html/HTMLFrameElement.h
+++ b/Source/core/html/HTMLFrameElement.h
@@ -42,7 +42,7 @@
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
 
     virtual bool rendererIsNeeded(const NodeRenderingContext&);
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
diff --git a/Source/core/html/HTMLFrameElementBase.cpp b/Source/core/html/HTMLFrameElementBase.cpp
index 602adbe..892878e 100644
--- a/Source/core/html/HTMLFrameElementBase.cpp
+++ b/Source/core/html/HTMLFrameElementBase.cpp
@@ -109,7 +109,7 @@
     } else if (name == scrollingAttr) {
         // Auto and yes both simply mean "allow scrolling." No means "don't allow scrolling."
         if (equalIgnoringCase(value, "auto") || equalIgnoringCase(value, "yes"))
-            m_scrolling = document()->frameElementsShouldIgnoreScrolling() ? ScrollbarAlwaysOff : ScrollbarAuto;
+            m_scrolling = ScrollbarAuto;
         else if (equalIgnoringCase(value, "no"))
             m_scrolling = ScrollbarAlwaysOff;
         // FIXME: If we are already attached, this has no effect.
diff --git a/Source/core/html/HTMLFrameOwnerElement.h b/Source/core/html/HTMLFrameOwnerElement.h
index e6e16b5..21c5c95 100644
--- a/Source/core/html/HTMLFrameOwnerElement.h
+++ b/Source/core/html/HTMLFrameOwnerElement.h
@@ -22,7 +22,6 @@
 #define HTMLFrameOwnerElement_h
 
 #include "core/html/HTMLElement.h"
-#include "core/loader/FrameLoaderTypes.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/HTMLFrameSetElement.cpp b/Source/core/html/HTMLFrameSetElement.cpp
index 1a273fa..6ae06a4 100644
--- a/Source/core/html/HTMLFrameSetElement.cpp
+++ b/Source/core/html/HTMLFrameSetElement.cpp
@@ -45,8 +45,6 @@
 
 HTMLFrameSetElement::HTMLFrameSetElement(const QualifiedName& tagName, Document* document)
     : HTMLElement(tagName, document)
-    , m_totalRows(1)
-    , m_totalCols(1)
     , m_border(6)
     , m_borderSet(false)
     , m_borderColorSet(false)
@@ -83,12 +81,12 @@
 {
     if (name == rowsAttr) {
         if (!value.isNull()) {
-            m_rowLengths = newLengthArray(value.string(), m_totalRows);
+            m_rowLengths = parseFrameSetListOfDimensions(value.string());
             setNeedsStyleRecalc();
         }
     } else if (name == colsAttr) {
         if (!value.isNull()) {
-            m_colLengths = newLengthArray(value.string(), m_totalCols);
+            m_colLengths = parseFrameSetListOfDimensions(value.string());
             setNeedsStyleRecalc();
         }
     } else if (name == frameborderAttr) {
@@ -156,12 +154,12 @@
     return context.style()->isStyleAvailable();
 }
 
-RenderObject *HTMLFrameSetElement::createRenderer(RenderArena *arena, RenderStyle *style)
+RenderObject* HTMLFrameSetElement::createRenderer(RenderStyle *style)
 {
     if (style->hasContent())
         return RenderObject::createObject(this, style);
     
-    return new (arena) RenderFrameSet(this);
+    return new (document()->renderArena()) RenderFrameSet(this);
 }
 
 void HTMLFrameSetElement::attach(const AttachContext& context)
@@ -191,7 +189,7 @@
 void HTMLFrameSetElement::defaultEventHandler(Event* evt)
 {
     if (evt->isMouseEvent() && !m_noresize && renderer() && renderer()->isFrameSet()) {
-        if (toRenderFrameSet(renderer())->userResize(static_cast<MouseEvent*>(evt))) {
+        if (toRenderFrameSet(renderer())->userResize(toMouseEvent(evt))) {
             evt->setDefaultHandled();
             return;
         }
diff --git a/Source/core/html/HTMLFrameSetElement.h b/Source/core/html/HTMLFrameSetElement.h
index 1a2ce49..912b397 100644
--- a/Source/core/html/HTMLFrameSetElement.h
+++ b/Source/core/html/HTMLFrameSetElement.h
@@ -25,7 +25,6 @@
 #define HTMLFrameSetElement_h
 
 #include "core/html/HTMLElement.h"
-#include <wtf/OwnArrayPtr.h>
 
 namespace WebCore {
 
@@ -36,14 +35,14 @@
     bool hasFrameBorder() const { return m_frameborder; }
     bool noResize() const { return m_noresize; }
 
-    int totalRows() const { return m_totalRows; }
-    int totalCols() const { return m_totalCols; }
+    size_t totalRows() const { return std::max<size_t>(1, m_rowLengths.size()); }
+    size_t totalCols() const { return std::max<size_t>(1, m_colLengths.size()); }
     int border() const { return hasFrameBorder() ? m_border : 0; }
 
     bool hasBorderColor() const { return m_borderColorSet; }
 
-    const Length* rowLengths() const { return m_rowLengths.get(); }
-    const Length* colLengths() const { return m_colLengths.get(); }
+    const Vector<Length>& rowLengths() const { return m_rowLengths; }
+    const Vector<Length>& colLengths() const { return m_colLengths; }
 
     DOMWindow* anonymousNamedGetter(const AtomicString&);
 
@@ -75,18 +74,15 @@
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual bool rendererIsNeeded(const NodeRenderingContext&);
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     virtual void defaultEventHandler(Event*);
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void willRecalcStyle(StyleChange) OVERRIDE;
 
-    OwnArrayPtr<Length> m_rowLengths;
-    OwnArrayPtr<Length> m_colLengths;
-
-    int m_totalRows;
-    int m_totalCols;
+    Vector<Length> m_rowLengths;
+    Vector<Length> m_colLengths;
 
     int m_border;
     bool m_borderSet;
diff --git a/Source/core/html/HTMLIFrameElement.cpp b/Source/core/html/HTMLIFrameElement.cpp
index 8a5314b..239bc50 100644
--- a/Source/core/html/HTMLIFrameElement.cpp
+++ b/Source/core/html/HTMLIFrameElement.cpp
@@ -30,7 +30,6 @@
 #include "core/dom/NodeRenderingContext.h"
 #include "core/html/HTMLDocument.h"
 #include "core/rendering/RenderIFrame.h"
-#include <wtf/text/TextPosition.h>
 
 namespace WebCore {
 
@@ -103,9 +102,9 @@
     return isURLAllowed() && context.style()->display() != NONE;
 }
 
-RenderObject* HTMLIFrameElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* HTMLIFrameElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderIFrame(this);
+    return new (document()->renderArena()) RenderIFrame(this);
 }
 
 Node::InsertionNotificationRequest HTMLIFrameElement::insertedInto(ContainerNode* insertionPoint)
diff --git a/Source/core/html/HTMLIFrameElement.h b/Source/core/html/HTMLIFrameElement.h
index c4b935e..ac821c2 100644
--- a/Source/core/html/HTMLIFrameElement.h
+++ b/Source/core/html/HTMLIFrameElement.h
@@ -45,7 +45,7 @@
     virtual void removedFrom(ContainerNode*) OVERRIDE;
 
     virtual bool rendererIsNeeded(const NodeRenderingContext&);
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     virtual void didRecalcStyle(StyleChange) OVERRIDE;
 
diff --git a/Source/core/html/HTMLImageElement.cpp b/Source/core/html/HTMLImageElement.cpp
index 7c8ccad..90c15f7 100644
--- a/Source/core/html/HTMLImageElement.cpp
+++ b/Source/core/html/HTMLImageElement.cpp
@@ -138,12 +138,12 @@
     return alt;
 }
 
-RenderObject* HTMLImageElement::createRenderer(RenderArena* arena, RenderStyle* style)
+RenderObject* HTMLImageElement::createRenderer(RenderStyle* style)
 {
     if (style->hasContent())
         return RenderObject::createObject(this, style);
 
-    RenderImage* image = new (arena) RenderImage(this);
+    RenderImage* image = new (document()->renderArena()) RenderImage(this);
     image->setImageResource(RenderImageResource::create());
     return image;
 }
@@ -176,15 +176,11 @@
 
 Node::InsertionNotificationRequest HTMLImageElement::insertedInto(ContainerNode* insertionPoint)
 {
+    // m_form can be non-null if it was set in constructor.
     if (!m_form) {
-        // m_form can be non-null if it was set in constructor.
-        for (ContainerNode* ancestor = parentNode(); ancestor; ancestor = ancestor->parentNode()) {
-            if (ancestor->hasTagName(formTag)) {
-                m_form = static_cast<HTMLFormElement*>(ancestor);
-                m_form->registerImgElement(this);
-                break;
-            }
-        }
+        m_form = findFormAncestor();
+        if (m_form)
+            m_form->registerImgElement(this);
     }
 
     // If we have been inserted from a renderer-less document,
diff --git a/Source/core/html/HTMLImageElement.h b/Source/core/html/HTMLImageElement.h
index e7b45c7..d0186c4 100644
--- a/Source/core/html/HTMLImageElement.h
+++ b/Source/core/html/HTMLImageElement.h
@@ -91,7 +91,7 @@
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
 
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     virtual bool canStartSelection() const;
 
diff --git a/Source/core/html/HTMLImportsController.cpp b/Source/core/html/HTMLImportsController.cpp
index 7202664..3f59c55 100644
--- a/Source/core/html/HTMLImportsController.cpp
+++ b/Source/core/html/HTMLImportsController.cpp
@@ -32,8 +32,6 @@
 #include "core/html/HTMLImportsController.h"
 
 #include "core/dom/Document.h"
-#include "core/dom/DocumentType.h"
-#include "core/dom/Range.h"
 #include "core/html/HTMLDocument.h"
 #include "core/html/HTMLLinkElement.h"
 #include "core/loader/cache/CachedResourceLoader.h"
@@ -49,19 +47,100 @@
 
 LinkImport::LinkImport(HTMLLinkElement* owner)
     : LinkResource(owner)
-    , m_controller(0)
-    , m_ofSameLocation(0)
-    , m_state(StatePreparing)
 {
 }
 
 LinkImport::~LinkImport()
 {
+}
+
+Document* LinkImport::importedDocument() const
+{
+    if (!m_loader)
+        return 0;
+    return m_loader->importedDocument();
+}
+
+void LinkImport::process()
+{
+    if (m_loader)
+        return;
+    if (!m_owner)
+        return;
+
+    // FIXME(morrita): Should take care of sub-imports whose document doesn't have frame.
+    if (!m_owner->document()->frame() && !m_owner->document()->imports())
+        return;
+
+    LinkRequestBuilder builder(m_owner);
+    if (!builder.isValid())
+        return;
+
+    HTMLImportsController* controller = m_owner->document()->imports();
+    if (!controller) {
+        ASSERT(m_owner->document()->frame()); // The document should be the master.
+        m_owner->document()->setImports(HTMLImportsController::create(m_owner->document()));
+        controller = m_owner->document()->imports();
+    }
+
+    if (RefPtr<HTMLImportLoader> found = controller->findLinkFor(builder.url())) {
+        m_loader = found;
+        return;
+    }
+
+    CachedResourceRequest request = builder.build(true);
+    CachedResourceHandle<CachedScript> resource = controller->cachedResourceLoader()->requestScript(request);
+    if (!resource)
+        return;
+
+    m_loader = HTMLImportLoader::create(controller, builder.url(), resource);
+}
+
+void LinkImport::ownerRemoved()
+{
+    m_owner = 0;
+    m_loader.clear();
+}
+
+
+PassRefPtr<HTMLImportLoader> HTMLImportLoader::create(HTMLImportsController* controller, const KURL& url, const CachedResourceHandle<CachedScript>& resource)
+{
+    RefPtr<HTMLImportLoader> loader = adoptRef(new HTMLImportLoader(controller, url, resource));
+    controller->addImport(loader);
+    return loader;
+}
+
+HTMLImportLoader::HTMLImportLoader(HTMLImportsController* controller, const KURL& url, const CachedResourceHandle<CachedScript>& resource)
+    : m_controller(controller)
+    , m_state(StateLoading)
+    , m_resource(resource)
+    , m_url(url)
+{
+    m_resource->addClient(this);
+}
+
+HTMLImportLoader::~HTMLImportLoader()
+{
     if (m_resource)
         m_resource->removeClient(this);
 }
 
-LinkImport::State LinkImport::finish()
+void HTMLImportLoader::notifyFinished(CachedResource*)
+{
+    setState(finish());
+}
+
+void HTMLImportLoader::setState(State state)
+{
+    if (m_state == state)
+        return;
+    m_state = state;
+
+    if ((m_state == StateReady  || m_state == StateError) && m_controller)
+        m_controller->didLoad();
+}
+
+HTMLImportLoader::State HTMLImportLoader::finish()
 {
     if (!m_controller)
         return StateError;
@@ -78,94 +157,29 @@
 
     // FIXME(morrita): This should be done in incremental way.
     m_importedDocument = HTMLDocument::create(0, m_resource->response().url());
+    m_importedDocument->setImports(m_controller);
     m_importedDocument->setContent(m_resource->script());
 
     return StateReady;
 }
 
-void LinkImport::notifyFinished(CachedResource*)
+Document* HTMLImportLoader::importedDocument() const
 {
-    setState(finish());
-}
-
-void LinkImport::setState(State state)
-{
-    if (m_state == state)
-        return;
-    m_state = state;
-
-    if ((m_state == StateReady  || m_state == StateError)
-        && m_controller)
-        m_controller->didLoad();
-}
-
-LinkImport::State LinkImport::startRequest()
-{
-    ASSERT(m_owner);
-    ASSERT(m_state == StatePreparing);
-
-    // FIXME(morrita): Should take care of sub-imports whose document doesn't have frame.
-    if (!m_owner->document()->frame())
-        return StateError;
-
-    LinkRequestBuilder builder(m_owner);
-    if (!builder.isValid())
-        return StateError;
-
-    m_controller = m_owner->document()->ensureImports();
-    if (RefPtr<LinkImport> found = m_controller->findLinkFor(builder.url())) {
-        m_ofSameLocation = found.get();
-        return StateReady;
-    }
-
-    CachedResourceRequest request = builder.build(true);
-    m_resource = m_owner->document()->cachedResourceLoader()->requestScript(request);
-    if (!m_resource)
-        return StateError;
-
-    m_resource->addClient(this);
-    m_url = builder.url();
-    m_controller->addImport(this);
-
-    return StateStarted;
-}
-
-Document* LinkImport::importedDocument() const
-{
-    if (!m_owner)
-        return 0;
     if (m_state != StateReady)
         return 0;
-
-    if (m_ofSameLocation) {
-        ASSERT(!m_importedDocument);
-        return m_ofSameLocation->importedDocument();
-    }
-
     return m_importedDocument.get();
 }
 
-void LinkImport::process()
-{
-    if (StatePreparing != m_state)
-        return;
-    setState(startRequest());
-}
-
-void LinkImport::ownerRemoved()
-{
-    m_owner = 0;
-}
-
-void LinkImport::importDestroyed()
+void HTMLImportLoader::importDestroyed()
 {
     m_controller = 0;
     m_importedDocument.clear();
 }
 
-PassOwnPtr<HTMLImportsController> HTMLImportsController::create(Document* master)
+
+PassRefPtr<HTMLImportsController> HTMLImportsController::create(Document* master)
 {
-    return adoptPtr(new HTMLImportsController(master));
+    return adoptRef(new HTMLImportsController(master));
 }
 
 HTMLImportsController::HTMLImportsController(Document* master)
@@ -179,7 +193,7 @@
         m_imports[i]->importDestroyed();
 }
 
-void HTMLImportsController::addImport(PassRefPtr<LinkImport> link)
+void HTMLImportsController::addImport(PassRefPtr<HTMLImportLoader> link)
 {
     ASSERT(!link->url().isEmpty() && link->url().isValid());
     m_imports.append(link);
@@ -196,10 +210,10 @@
         m_master->didLoadAllImports();
 }
 
-PassRefPtr<LinkImport> HTMLImportsController::findLinkFor(const KURL& url) const
+PassRefPtr<HTMLImportLoader> HTMLImportsController::findLinkFor(const KURL& url) const
 {
     for (size_t i = 0; i < m_imports.size(); ++i) {
-        if (m_imports[i]->url() == url)
+        if (equalIgnoringFragmentIdentifier(m_imports[i]->url(), url))
             return m_imports[i];
     }
 
@@ -211,6 +225,11 @@
     return m_master->securityOrigin();
 }
 
+CachedResourceLoader* HTMLImportsController::cachedResourceLoader() const
+{
+    return m_master->cachedResourceLoader();
+}
+
 bool HTMLImportsController::haveLoaded() const
 {
     for (size_t i = 0; i < m_imports.size(); ++i) {
diff --git a/Source/core/html/HTMLImportsController.h b/Source/core/html/HTMLImportsController.h
index 5bf13be..fd1ecc3 100644
--- a/Source/core/html/HTMLImportsController.h
+++ b/Source/core/html/HTMLImportsController.h
@@ -40,21 +40,16 @@
 
 namespace WebCore {
 
-class DocumentFragment;
+class CachedResourceLoader;
+class HTMLImportLoader;
 class HTMLImportsController;
 
 //
 // A LinkResource subclasss used for @rel=import.
 //
-class LinkImport : public LinkResource, CachedResourceClient {
+class LinkImport : public LinkResource {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    enum State {
-        StatePreparing,
-        StateStarted,
-        StateError,
-        StateReady
-    };
 
     static PassRefPtr<LinkImport> create(HTMLLinkElement* owner);
 
@@ -67,48 +62,67 @@
     virtual void ownerRemoved() OVERRIDE;
 
     Document* importedDocument() const;
+
+private:
+    RefPtr<HTMLImportLoader> m_loader;
+};
+
+
+class HTMLImportLoader : public RefCounted<HTMLImportLoader>, public CachedResourceClient {
+public:
+    enum State {
+        StateLoading,
+        StateError,
+        StateReady
+    };
+
+    static PassRefPtr<HTMLImportLoader> create(HTMLImportsController*, const KURL&, const CachedResourceHandle<CachedScript>&);
+    virtual ~HTMLImportLoader();
+
+    Document* importedDocument() const;
     const KURL& url() const { return m_url; }
+
     void importDestroyed();
     bool isDone() const { return m_state == StateReady || m_state == StateError; }
 
 private:
-    State startRequest();
-    State finish();
-    void setState(State);
+    HTMLImportLoader(HTMLImportsController*, const KURL&, const CachedResourceHandle<CachedScript>&);
 
     // CachedResourceClient
     virtual void notifyFinished(CachedResource*) OVERRIDE;
 
+    State finish();
+    void setState(State);
+
     HTMLImportsController* m_controller;
-    LinkImport* m_ofSameLocation;
-    KURL m_url;
     State m_state;
+    KURL m_url;
     CachedResourceHandle<CachedScript> m_resource;
     RefPtr<Document> m_importedDocument;
 };
 
 
-class HTMLImportsController {
+class HTMLImportsController : public RefCounted<HTMLImportsController> {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<HTMLImportsController> create(Document*);
+    static PassRefPtr<HTMLImportsController> create(Document*);
 
     explicit HTMLImportsController(Document*);
     virtual ~HTMLImportsController();
 
-    void addImport(PassRefPtr<LinkImport>);
+    void addImport(PassRefPtr<HTMLImportLoader>);
     void showSecurityErrorMessage(const String&);
-    PassRefPtr<LinkImport> findLinkFor(const KURL&) const;
+    PassRefPtr<HTMLImportLoader> findLinkFor(const KURL&) const;
     SecurityOrigin* securityOrigin() const;
+    CachedResourceLoader* cachedResourceLoader() const;
     bool haveLoaded() const;
     void didLoad();
 
 private:
-
     Document* m_master;
 
     // List of import which has been loaded or being loaded.
-    typedef Vector<RefPtr<LinkImport> > ImportList;
+    typedef Vector<RefPtr<HTMLImportLoader> > ImportList;
     ImportList m_imports;
 };
 
diff --git a/Source/core/html/HTMLInputElement.cpp b/Source/core/html/HTMLInputElement.cpp
index 60b8a17..de999dd 100644
--- a/Source/core/html/HTMLInputElement.cpp
+++ b/Source/core/html/HTMLInputElement.cpp
@@ -30,7 +30,6 @@
 #include "core/html/HTMLInputElement.h"
 
 #include "CSSPropertyNames.h"
-#include "CSSValueKeywords.h"
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "bindings/v8/ScriptEventListener.h"
@@ -68,11 +67,9 @@
 #include "core/platform/Language.h"
 #include "core/platform/LocalizedStrings.h"
 #include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/text/PlatformLocale.h"
 #include "core/rendering/RenderTextControlSingleLine.h"
 #include "core/rendering/RenderTheme.h"
-#include <wtf/MathExtras.h>
-#include <wtf/StdLibExtras.h>
+#include "wtf/MathExtras.h"
 
 using namespace std;
 
@@ -368,9 +365,9 @@
     return m_inputType->isKeyboardFocusable(event);
 }
 
-bool HTMLInputElement::isMouseFocusable() const
+bool HTMLInputElement::shouldShowFocusRingOnMouseFocus() const
 {
-    return m_inputType->isMouseFocusable();
+    return m_inputType->shouldShowFocusRingOnMouseFocus();
 }
 
 bool HTMLInputElement::isTextFormControlKeyboardFocusable(KeyboardEvent* event) const
@@ -378,11 +375,6 @@
     return HTMLTextFormControlElement::isKeyboardFocusable(event);
 }
 
-bool HTMLInputElement::isTextFormControlMouseFocusable() const
-{
-    return HTMLTextFormControlElement::isMouseFocusable();
-}
-
 void HTMLInputElement::updateFocusAppearance(bool restorePreviousSelection)
 {
     if (isTextField()) {
@@ -500,9 +492,9 @@
     }
 
     if (wasAttached) {
-        attach();
+        lazyAttach();
         if (document()->focusedNode() == this)
-            updateFocusAppearance(true);
+            document()->updateFocusAppearanceSoon(true /* restore selection */);
     }
 
     if (ElementShadow* elementShadow = shadowOfParentForDistribution(this))
@@ -768,23 +760,15 @@
     }
 #if ENABLE(INPUT_SPEECH)
     else if (name == webkitspeechAttr) {
-        if (m_inputType->shouldRespectSpeechAttribute() && RuntimeEnabledFeatures::speechInputEnabled()) {
+        if (RuntimeEnabledFeatures::speechInputEnabled() && m_inputType->shouldRespectSpeechAttribute()) {
             // This renderer and its children have quite different layouts and
             // styles depending on whether the speech button is visible or
             // not. So we reset the whole thing and recreate to get the right
             // styles and layout.
-            if (attached()) {
-                m_inputType->destroyShadowSubtree();
-                detach();
-                m_inputType->createShadowSubtree();
-                if (!attached())
-                    attach();
-            } else {
-                m_inputType->destroyShadowSubtree();
-                m_inputType->createShadowSubtree();
-            }
+            m_inputType->destroyShadowSubtree();
+            lazyReattachIfAttached();
+            m_inputType->createShadowSubtree();
             setFormControlValueMatchesRenderer(false);
-            setNeedsStyleRecalc();
         }
         UseCounter::count(document(), UseCounter::PrefixedSpeechAttribute);
     } else if (name == onwebkitspeechchangeAttr)
@@ -816,9 +800,9 @@
     return m_inputType->rendererIsNeeded() && HTMLTextFormControlElement::rendererIsNeeded(context);
 }
 
-RenderObject* HTMLInputElement::createRenderer(RenderArena* arena, RenderStyle* style)
+RenderObject* HTMLInputElement::createRenderer(RenderStyle* style)
 {
-    return m_inputType->createRenderer(arena, style);
+    return m_inputType->createRenderer(style);
 }
 
 void HTMLInputElement::attach(const AttachContext& context)
@@ -1138,7 +1122,7 @@
     }
     if (event->type() != eventNames().clickEvent)
         return 0;
-    if (!event->isMouseEvent() || static_cast<MouseEvent*>(event)->button() != LeftButton)
+    if (!event->isMouseEvent() || toMouseEvent(event)->button() != LeftButton)
         return 0;
     // FIXME: Check whether there are any cases where this actually ends up leaking.
     return m_inputType->willDispatchClick().leakPtr();
@@ -1154,8 +1138,8 @@
 
 void HTMLInputElement::defaultEventHandler(Event* evt)
 {
-    if (evt->isMouseEvent() && evt->type() == eventNames().clickEvent && static_cast<MouseEvent*>(evt)->button() == LeftButton) {
-        m_inputType->handleClickEvent(static_cast<MouseEvent*>(evt));
+    if (evt->isMouseEvent() && evt->type() == eventNames().clickEvent && toMouseEvent(evt)->button() == LeftButton) {
+        m_inputType->handleClickEvent(toMouseEvent(evt));
         if (evt->defaultHandled())
             return;
     }
@@ -1167,7 +1151,7 @@
     }
 
     if (evt->isKeyboardEvent() && evt->type() == eventNames().keydownEvent) {
-        m_inputType->handleKeydownEvent(static_cast<KeyboardEvent*>(evt));
+        m_inputType->handleKeydownEvent(toKeyboardEvent(evt));
         if (evt->defaultHandled())
             return;
     }
@@ -1194,13 +1178,13 @@
     // Use key press event here since sending simulated mouse events
     // on key down blocks the proper sending of the key press event.
     if (evt->isKeyboardEvent() && evt->type() == eventNames().keypressEvent) {
-        m_inputType->handleKeypressEvent(static_cast<KeyboardEvent*>(evt));
+        m_inputType->handleKeypressEvent(toKeyboardEvent(evt));
         if (evt->defaultHandled())
             return;
     }
 
     if (evt->isKeyboardEvent() && evt->type() == eventNames().keyupEvent) {
-        m_inputType->handleKeyupEvent(static_cast<KeyboardEvent*>(evt));
+        m_inputType->handleKeyupEvent(toKeyboardEvent(evt));
         if (evt->defaultHandled())
             return;
     }
@@ -1226,7 +1210,7 @@
         m_inputType->handleBeforeTextInsertedEvent(static_cast<BeforeTextInsertedEvent*>(evt));
 
     if (evt->isMouseEvent() && evt->type() == eventNames().mousedownEvent) {
-        m_inputType->handleMouseDownEvent(static_cast<MouseEvent*>(evt));
+        m_inputType->handleMouseDownEvent(toMouseEvent(evt));
         if (evt->defaultHandled())
             return;
     }
diff --git a/Source/core/html/HTMLInputElement.h b/Source/core/html/HTMLInputElement.h
index 6b887b0..80fc77d 100644
--- a/Source/core/html/HTMLInputElement.h
+++ b/Source/core/html/HTMLInputElement.h
@@ -186,7 +186,7 @@
     void setSelectionRangeForBinding(int start, int end, const String& direction, ExceptionCode&);
 
     virtual bool rendererIsNeeded(const NodeRenderingContext&);
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
 
     // FIXME: For isActivatedSubmit and setActivatedSubmit, we should use the NVI-idiom here by making
@@ -250,7 +250,6 @@
     // Functions for InputType classes.
     void setValueInternal(const String&, TextFieldEventBehavior);
     bool isTextFormControlKeyboardFocusable(KeyboardEvent*) const;
-    bool isTextFormControlMouseFocusable() const;
     bool valueAttributeWasUpdatedAfterParsing() const { return m_valueAttributeWasUpdatedAfterParsing; }
 
     void cacheSelectionInResponseToSetValue(int caretOffset) { cacheSelection(caretOffset, caretOffset, SelectionHasNoDirection); }
@@ -314,7 +313,7 @@
 
     virtual bool hasCustomFocusLogic() const OVERRIDE;
     virtual bool isKeyboardFocusable(KeyboardEvent*) const;
-    virtual bool isMouseFocusable() const;
+    virtual bool shouldShowFocusRingOnMouseFocus() const OVERRIDE;
     virtual bool isEnumeratable() const;
     virtual bool supportLabels() const OVERRIDE;
     virtual void updateFocusAppearance(bool restorePreviousSelection);
diff --git a/Source/core/html/HTMLInputElement.idl b/Source/core/html/HTMLInputElement.idl
index 00e4a1e..42d3347 100644
--- a/Source/core/html/HTMLInputElement.idl
+++ b/Source/core/html/HTMLInputElement.idl
@@ -57,6 +57,7 @@
     [TreatNullAs=NullString, SetterRaisesException] attribute DOMString value;
     [SetterRaisesException] attribute Date valueAsDate;
     [SetterRaisesException] attribute double valueAsNumber;
+    [EnabledAtRuntime=inputModeAttribute, Reflect] attribute DOMString inputMode;
 
     [RaisesException] void stepUp(optional long n);
     [RaisesException] void stepDown(optional long n);
diff --git a/Source/core/html/HTMLKeygenElement.cpp b/Source/core/html/HTMLKeygenElement.cpp
index abc62c9..30a8deb 100644
--- a/Source/core/html/HTMLKeygenElement.cpp
+++ b/Source/core/html/HTMLKeygenElement.cpp
@@ -118,7 +118,7 @@
 
 void HTMLKeygenElement::reset()
 {
-    static_cast<HTMLFormControlElement*>(shadowSelect())->reset();
+    shadowSelect()->reset();
 }
 
 bool HTMLKeygenElement::shouldSaveAndRestoreFormControlState() const
diff --git a/Source/core/html/HTMLLabelElement.cpp b/Source/core/html/HTMLLabelElement.cpp
index c543eca..44ac76d 100644
--- a/Source/core/html/HTMLLabelElement.cpp
+++ b/Source/core/html/HTMLLabelElement.cpp
@@ -35,20 +35,13 @@
 
 using namespace HTMLNames;
 
-static LabelableElement* nodeAsLabelableElement(Node* node)
+static bool supportsLabels(Element* element)
 {
-    if (!node || !node->isHTMLElement())
-        return 0;
-    
-    HTMLElement* element = static_cast<HTMLElement*>(node);
-    if (!element->isLabelable())
-        return 0;
-
-    LabelableElement* labelableElement = static_cast<LabelableElement*>(element);
-    if (!labelableElement->supportLabels())
-        return 0;
-
-    return labelableElement;
+    if (!element || !element->isHTMLElement())
+        return false;
+    if (!toHTMLElement(element)->isLabelable())
+        return false;
+    return toLabelableElement(element)->supportLabels();
 }
 
 inline HTMLLabelElement::HTMLLabelElement(const QualifiedName& tagName, Document* document)
@@ -78,15 +71,19 @@
         // the form element must be "labelable form-associated element".
         Element* element = this;
         while ((element = ElementTraversal::next(element, this))) {
-            if (LabelableElement* labelableElement = nodeAsLabelableElement(element))
-                return labelableElement;
+            if (!supportsLabels(element))
+                continue;
+            return toLabelableElement(element);
         }
         return 0;
     }
-    
-    // Find the first element whose id is controlId. If it is found and it is a labelable form control,
-    // return it, otherwise return 0.
-    return nodeAsLabelableElement(treeScope()->getElementById(controlId));
+
+    if (Element* element = treeScope()->getElementById(controlId)) {
+        if (supportsLabels(element))
+            return toLabelableElement(element);
+    }
+
+    return 0;
 }
 
 HTMLFormElement* HTMLLabelElement::form() const
@@ -137,6 +134,7 @@
         // Click the corresponding control.
         element->dispatchSimulatedClick(evt);
 
+        document()->updateLayoutIgnorePendingStylesheets();
         if (element->isMouseFocusable())
             element->focus();
 
diff --git a/Source/core/html/HTMLLegendElement.cpp b/Source/core/html/HTMLLegendElement.cpp
index 15e8b1d..d73f0cc 100644
--- a/Source/core/html/HTMLLegendElement.cpp
+++ b/Source/core/html/HTMLLegendElement.cpp
@@ -29,7 +29,6 @@
 #include "core/dom/NodeTraversal.h"
 #include "core/html/HTMLFieldSetElement.h"
 #include "core/html/HTMLFormControlElement.h"
-#include <wtf/StdLibExtras.h>
 
 namespace WebCore {
 
@@ -62,7 +61,7 @@
     Element* element = fieldset;
     while ((element = ElementTraversal::next(element, fieldset))) {
         if (element->isFormControlElement())
-            return static_cast<HTMLFormControlElement*>(element);
+            return toHTMLFormControlElement(element);
     }
 
     return 0;
diff --git a/Source/core/html/HTMLLinkElement.cpp b/Source/core/html/HTMLLinkElement.cpp
index 381f096..a98eaa0 100644
--- a/Source/core/html/HTMLLinkElement.cpp
+++ b/Source/core/html/HTMLLinkElement.cpp
@@ -25,7 +25,6 @@
 #include "config.h"
 #include "core/html/HTMLLinkElement.h"
 
-#include <wtf/StdLibExtras.h>
 #include "HTMLNames.h"
 #include "bindings/v8/ScriptEventListener.h"
 #include "core/css/MediaList.h"
@@ -34,7 +33,6 @@
 #include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Attribute.h"
 #include "core/dom/Document.h"
-#include "core/dom/DocumentFragment.h"
 #include "core/dom/DocumentStyleSheetCollection.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventSender.h"
@@ -45,6 +43,7 @@
 #include "core/loader/cache/CachedResourceRequest.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
+#include "wtf/StdLibExtras.h"
 
 namespace WebCore {
 
@@ -532,6 +531,9 @@
             return;
         }
 
+        if (m_sheet)
+            m_sheet->setDisabled(disabled);
+
         // Load the sheet, since it's never been loaded before.
         if (!m_sheet && m_disabledState == EnabledViaScript) {
             if (m_owner->shouldProcessStyle())
diff --git a/Source/core/html/HTMLLinkElement.h b/Source/core/html/HTMLLinkElement.h
index a227aa5..c854140 100644
--- a/Source/core/html/HTMLLinkElement.h
+++ b/Source/core/html/HTMLLinkElement.h
@@ -34,7 +34,6 @@
 #include "core/loader/LinkLoaderClient.h"
 #include "core/loader/cache/CachedResourceHandle.h"
 #include "core/loader/cache/CachedStyleSheetClient.h"
-#include "core/platform/Timer.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/HTMLMarqueeElement.cpp b/Source/core/html/HTMLMarqueeElement.cpp
index e66d444..181c72c 100644
--- a/Source/core/html/HTMLMarqueeElement.cpp
+++ b/Source/core/html/HTMLMarqueeElement.cpp
@@ -27,7 +27,6 @@
 #include "CSSValueKeywords.h"
 #include "HTMLNames.h"
 #include "core/dom/ExceptionCode.h"
-#include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderMarquee.h"
 
 namespace WebCore {
@@ -190,9 +189,9 @@
     return 0;
 }
 
-RenderObject* HTMLMarqueeElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* HTMLMarqueeElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderMarquee(this);
+    return new (document()->renderArena()) RenderMarquee(this);
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/HTMLMarqueeElement.h b/Source/core/html/HTMLMarqueeElement.h
index 26188a7..ad49859 100644
--- a/Source/core/html/HTMLMarqueeElement.h
+++ b/Source/core/html/HTMLMarqueeElement.h
@@ -61,7 +61,7 @@
     virtual void suspend(ReasonForSuspension);
     virtual void resume();
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) OVERRIDE FINAL;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE FINAL;
 
     RenderMarquee* renderMarquee() const;
 };
diff --git a/Source/core/html/HTMLMediaElement.cpp b/Source/core/html/HTMLMediaElement.cpp
index 530c97c..8c01b54 100644
--- a/Source/core/html/HTMLMediaElement.cpp
+++ b/Source/core/html/HTMLMediaElement.cpp
@@ -26,13 +26,6 @@
 #include "config.h"
 #include "core/html/HTMLMediaElement.h"
 
-#include <wtf/CurrentTime.h>
-#include <wtf/MathExtras.h>
-#include <wtf/MemoryInstrumentationVector.h>
-#include <wtf/NonCopyingSort.h>
-#include <wtf/text/CString.h>
-#include <wtf/Uint8Array.h>
-#include <limits>
 #include "HTMLNames.h"
 #include "RuntimeEnabledFeatures.h"
 #include "bindings/v8/ScriptController.h"
@@ -51,7 +44,6 @@
 #include "core/html/HTMLSourceElement.h"
 #include "core/html/HTMLTrackElement.h"
 #include "core/html/MediaController.h"
-#include "core/html/MediaDocument.h"
 #include "core/html/MediaError.h"
 #include "core/html/MediaFragmentURIParser.h"
 #include "core/html/MediaKeyError.h"
@@ -64,9 +56,7 @@
 #include "core/loader/FrameLoader.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "core/page/Frame.h"
-#include "core/page/FrameView.h"
 #include "core/page/Page.h"
-#include "core/page/PageGroup.h"
 #include "core/page/Settings.h"
 #include "core/platform/ContentType.h"
 #include "core/platform/Language.h"
@@ -76,15 +66,19 @@
 #include "core/platform/NotImplemented.h"
 #include "core/platform/graphics/InbandTextTrackPrivate.h"
 #include "core/platform/graphics/MediaPlayer.h"
-#include "core/rendering/RenderLayerCompositor.h"
 #include "core/rendering/RenderVideo.h"
-#include "core/rendering/RenderView.h"
 #include "modules/mediasource/MediaSourceBase.h"
 #include "modules/mediasource/MediaSourceRegistry.h"
 #include "modules/mediastream/MediaStreamRegistry.h"
-#include "weborigin/SecurityOrigin.h"
-#include "weborigin/SecurityPolicy.h"
 #include "public/platform/Platform.h"
+#include "weborigin/SecurityOrigin.h"
+#include "wtf/CurrentTime.h"
+#include "wtf/MathExtras.h"
+#include "wtf/MemoryInstrumentationVector.h"
+#include "wtf/NonCopyingSort.h"
+#include "wtf/Uint8Array.h"
+#include "wtf/text/CString.h"
+#include <limits>
 
 #if ENABLE(WEB_AUDIO)
 #include "core/platform/audio/AudioSourceProvider.h"
@@ -493,9 +487,9 @@
     return controls() ? HTMLElement::rendererIsNeeded(context) : false;
 }
 
-RenderObject* HTMLMediaElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* HTMLMediaElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderMedia(this);
+    return new (document()->renderArena()) RenderMedia(this);
 }
 
 bool HTMLMediaElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
@@ -3943,9 +3937,9 @@
     m_restrictions = NoRestrictions;
 }
 
-void HTMLMediaElement::mediaPlayerNeedsStyleRecalc()
+void HTMLMediaElement::scheduleLayerUpdate()
 {
-    setNeedsStyleRecalc(WebCore::SyntheticStyleChange);
+    setNeedsLayerUpdate();
 }
 
 void HTMLMediaElement::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
diff --git a/Source/core/html/HTMLMediaElement.h b/Source/core/html/HTMLMediaElement.h
index 2bcda2a..3e2d4b8 100644
--- a/Source/core/html/HTMLMediaElement.h
+++ b/Source/core/html/HTMLMediaElement.h
@@ -336,7 +336,7 @@
     virtual bool supportsFocus() const;
     virtual bool isMouseFocusable() const;
     virtual bool rendererIsNeeded(const NodeRenderingContext&);
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
@@ -376,7 +376,7 @@
 
     virtual CORSMode mediaPlayerCORSMode() const OVERRIDE;
 
-    virtual void mediaPlayerNeedsStyleRecalc() OVERRIDE;
+    virtual void scheduleLayerUpdate() OVERRIDE;
 
     void loadTimerFired(Timer<HTMLMediaElement>*);
     void progressEventTimerFired(Timer<HTMLMediaElement>*);
diff --git a/Source/core/html/HTMLMediaElement.idl b/Source/core/html/HTMLMediaElement.idl
index 5db5f75..10ebf8a 100644
--- a/Source/core/html/HTMLMediaElement.idl
+++ b/Source/core/html/HTMLMediaElement.idl
@@ -97,9 +97,7 @@
 [EnabledAtRuntime=legacyEncryptedMedia] attribute EventListener onwebkitkeymessage;
 [EnabledAtRuntime=legacyEncryptedMedia] attribute EventListener onwebkitneedkey;
 
-#if defined(ENABLE_ENCRYPTED_MEDIA_V2) && ENABLE_ENCRYPTED_MEDIA_V2
-[EnabledAtRuntime=encryptedMedia] attribute MediaKeys mediaKeys;
-#endif
+[EnabledAtRuntime=encryptedMedia, Conditional=ENCRYPTED_MEDIA_V2] attribute MediaKeys mediaKeys;
 
 [EnabledAtRuntime=videoTrack, RaisesException] TextTrack addTextTrack(DOMString kind, optional DOMString label, optional DOMString language);
 [EnabledAtRuntime=videoTrack] readonly attribute TextTrackList textTracks;
diff --git a/Source/core/html/HTMLMeterElement.cpp b/Source/core/html/HTMLMeterElement.cpp
index 02885fe..e2680b9 100644
--- a/Source/core/html/HTMLMeterElement.cpp
+++ b/Source/core/html/HTMLMeterElement.cpp
@@ -31,7 +31,6 @@
 #include "core/page/Page.h"
 #include "core/rendering/RenderMeter.h"
 #include "core/rendering/RenderTheme.h"
-#include <wtf/StdLibExtras.h>
 
 namespace WebCore {
 
@@ -55,12 +54,12 @@
     return meter;
 }
 
-RenderObject* HTMLMeterElement::createRenderer(RenderArena* arena, RenderStyle* style)
+RenderObject* HTMLMeterElement::createRenderer(RenderStyle* style)
 {
     if (hasAuthorShadowRoot() || !document()->page()->theme()->supportsMeter(style->appearance()))
         return RenderObject::createObject(this, style);
 
-    return new (arena) RenderMeter(this);
+    return new (document()->renderArena()) RenderMeter(this);
 }
 
 bool HTMLMeterElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
diff --git a/Source/core/html/HTMLMeterElement.h b/Source/core/html/HTMLMeterElement.h
index 0ed11eb..0411f71 100644
--- a/Source/core/html/HTMLMeterElement.h
+++ b/Source/core/html/HTMLMeterElement.h
@@ -71,7 +71,7 @@
     virtual bool supportLabels() const OVERRIDE { return true; }
 
     virtual bool recalcWillValidate() const { return false; }
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const OVERRIDE;
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
diff --git a/Source/core/html/HTMLOptionElement.cpp b/Source/core/html/HTMLOptionElement.cpp
index dd763b6..4947a72 100644
--- a/Source/core/html/HTMLOptionElement.cpp
+++ b/Source/core/html/HTMLOptionElement.cpp
@@ -28,7 +28,6 @@
 #include "core/html/HTMLOptionElement.h"
 
 #include "HTMLNames.h"
-#include "core/css/resolver/StyleResolver.h"
 #include "core/dom/Document.h"
 #include "core/dom/NodeRenderStyle.h"
 #include "core/dom/NodeTraversal.h"
@@ -38,9 +37,8 @@
 #include "core/html/HTMLSelectElement.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/rendering/RenderTheme.h"
-#include <wtf/StdLibExtras.h>
-#include <wtf/text/StringBuilder.h>
-#include <wtf/Vector.h>
+#include "wtf/Vector.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
@@ -344,12 +342,9 @@
 {
     if (ownElementDisabled())
         return true;
-
-    if (!parentNode() || !parentNode()->isHTMLElement())
-        return false;
-
-    HTMLElement* parentElement = static_cast<HTMLElement*>(parentNode());
-    return parentElement->hasTagName(optgroupTag) && parentElement->isDisabledFormControl();
+    if (Element* parent = parentElement())
+        return parent->hasTagName(optgroupTag) && parent->isDisabledFormControl();
+    return false;
 }
 
 Node::InsertionNotificationRequest HTMLOptionElement::insertedInto(ContainerNode* insertionPoint)
@@ -383,20 +378,4 @@
     return text.toString();
 }
 
-#ifndef NDEBUG
-
-HTMLOptionElement* toHTMLOptionElement(Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(optionTag));
-    return static_cast<HTMLOptionElement*>(node);
-}
-
-const HTMLOptionElement* toHTMLOptionElement(const Node* node)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(optionTag));
-    return static_cast<const HTMLOptionElement*>(node);
-}
-
-#endif
-
-} // namespace
+} // namespace WebCore
diff --git a/Source/core/html/HTMLOptionElement.h b/Source/core/html/HTMLOptionElement.h
index 5c5fd6f..a0e81c4 100644
--- a/Source/core/html/HTMLOptionElement.h
+++ b/Source/core/html/HTMLOptionElement.h
@@ -93,26 +93,20 @@
     RefPtr<RenderStyle> m_style;
 };
 
-HTMLOptionElement* toHTMLOptionElement(Node*);
-const HTMLOptionElement* toHTMLOptionElement(const Node*);
 void toHTMLOptionElement(const HTMLOptionElement*); // This overload will catch anyone doing an unnecessary cast.
 
-#ifdef NDEBUG
-
-// The debug versions of these, with assertions, are not inlined.
-
 inline HTMLOptionElement* toHTMLOptionElement(Node* node)
 {
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::optionTag));
     return static_cast<HTMLOptionElement*>(node);
 }
 
 inline const HTMLOptionElement* toHTMLOptionElement(const Node* node)
 {
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::optionTag));
     return static_cast<const HTMLOptionElement*>(node);
 }
 
-#endif
-
-} // namespace
+} // namespace WebCore
 
 #endif
diff --git a/Source/core/html/HTMLOptionsCollection.cpp b/Source/core/html/HTMLOptionsCollection.cpp
index ef8bba0..e0a7a4b 100644
--- a/Source/core/html/HTMLOptionsCollection.cpp
+++ b/Source/core/html/HTMLOptionsCollection.cpp
@@ -65,7 +65,7 @@
     if (index == -1 || unsigned(index) >= length())
         select->add(newOption, 0, ec);
     else
-        select->add(newOption, static_cast<HTMLOptionElement*>(item(index)), ec);
+        select->add(newOption, toHTMLOptionElement(item(index)), ec);
 
     ASSERT(!ec);
 }
diff --git a/Source/core/html/HTMLOutputElement.h b/Source/core/html/HTMLOutputElement.h
index 4b27451..8981f7d 100644
--- a/Source/core/html/HTMLOutputElement.h
+++ b/Source/core/html/HTMLOutputElement.h
@@ -33,7 +33,6 @@
 
 #include "core/html/DOMSettableTokenList.h"
 #include "core/html/HTMLFormControlElement.h"
-#include <wtf/OwnPtr.h>
 
 namespace WebCore {
 
diff --git a/Source/core/html/HTMLPlugInElement.h b/Source/core/html/HTMLPlugInElement.h
index 7a567c7..75c8e36 100644
--- a/Source/core/html/HTMLPlugInElement.h
+++ b/Source/core/html/HTMLPlugInElement.h
@@ -24,7 +24,6 @@
 #define HTMLPlugInElement_h
 
 #include "core/html/HTMLFrameOwnerElement.h"
-#include "core/platform/graphics/Image.h"
 
 #include "bindings/v8/ScriptInstance.h"
 
diff --git a/Source/core/html/HTMLPlugInImageElement.cpp b/Source/core/html/HTMLPlugInImageElement.cpp
index 622dbc2..8a931c2 100644
--- a/Source/core/html/HTMLPlugInImageElement.cpp
+++ b/Source/core/html/HTMLPlugInImageElement.cpp
@@ -21,31 +21,16 @@
 #include "config.h"
 #include "core/html/HTMLPlugInImageElement.h"
 
-#include <wtf/CurrentTime.h>
 #include "bindings/v8/ScriptController.h"
-#include "core/dom/MouseEvent.h"
-#include "core/dom/NodeList.h"
-#include "core/dom/NodeRenderStyle.h"
-#include "core/dom/NodeRenderingContext.h"
-#include "core/dom/Text.h"
-#include "core/dom/shadow/ShadowRoot.h"
-#include "core/html/HTMLDivElement.h"
 #include "core/html/HTMLImageLoader.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/page/Chrome.h"
-#include "core/page/ChromeClient.h"
 #include "core/page/Frame.h"
-#include "core/page/FrameView.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/LocalizedStrings.h"
 #include "core/platform/Logging.h"
 #include "core/platform/MIMETypeFromURL.h"
 #include "core/platform/graphics/Image.h"
 #include "core/rendering/RenderEmbeddedObject.h"
 #include "core/rendering/RenderImage.h"
-#include "weborigin/SchemeRegistry.h"
 #include "weborigin/SecurityOrigin.h"
 
 namespace WebCore {
@@ -135,7 +120,7 @@
     return false;
 }
 
-RenderObject* HTMLPlugInImageElement::createRenderer(RenderArena* arena, RenderStyle* style)
+RenderObject* HTMLPlugInImageElement::createRenderer(RenderStyle* style)
 {
     // Fallback content breaks the DOM->Renderer class relationship of this
     // class and all superclasses because createObject won't necessarily
@@ -144,12 +129,12 @@
         return RenderObject::createObject(this, style);
 
     if (isImageType()) {
-        RenderImage* image = new (arena) RenderImage(this);
+        RenderImage* image = new (document()->renderArena()) RenderImage(this);
         image->setImageResource(RenderImageResource::create());
         return image;
     }
 
-    return new (arena) RenderEmbeddedObject(this);
+    return new (document()->renderArena()) RenderEmbeddedObject(this);
 }
 
 void HTMLPlugInImageElement::willRecalcStyle(StyleChange)
diff --git a/Source/core/html/HTMLPlugInImageElement.h b/Source/core/html/HTMLPlugInImageElement.h
index 4f5ae54..fc79771 100644
--- a/Source/core/html/HTMLPlugInImageElement.h
+++ b/Source/core/html/HTMLPlugInImageElement.h
@@ -25,8 +25,7 @@
 
 #include "core/platform/MIMETypeFromURL.h"
 #include "core/rendering/style/RenderStyle.h"
-#include <wtf/OwnPtr.h>
-#include <wtf/RefPtr.h>
+#include "wtf/OwnPtr.h"
 
 namespace WebCore {
 
@@ -98,7 +97,7 @@
     virtual void didMoveToNewDocument(Document* oldDocument) OVERRIDE;
 
 private:
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual void willRecalcStyle(StyleChange) OVERRIDE FINAL;
 
     virtual void finishParsingChildren();
diff --git a/Source/core/html/HTMLProgressElement.cpp b/Source/core/html/HTMLProgressElement.cpp
index 17e7890..d39fc76 100644
--- a/Source/core/html/HTMLProgressElement.cpp
+++ b/Source/core/html/HTMLProgressElement.cpp
@@ -29,7 +29,6 @@
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/shadow/ProgressShadowElement.h"
 #include "core/rendering/RenderProgress.h"
-#include <wtf/StdLibExtras.h>
 
 namespace WebCore {
 
@@ -57,12 +56,12 @@
     return progress.release();
 }
 
-RenderObject* HTMLProgressElement::createRenderer(RenderArena* arena, RenderStyle* style)
+RenderObject* HTMLProgressElement::createRenderer(RenderStyle* style)
 {
     if (!style->hasAppearance() || hasAuthorShadowRoot())
         return RenderObject::createObject(this, style);
 
-    return new (arena) RenderProgress(this);
+    return new (document()->renderArena()) RenderProgress(this);
 }
 
 bool HTMLProgressElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
diff --git a/Source/core/html/HTMLProgressElement.h b/Source/core/html/HTMLProgressElement.h
index 42e3287..91fca9b 100644
--- a/Source/core/html/HTMLProgressElement.h
+++ b/Source/core/html/HTMLProgressElement.h
@@ -53,7 +53,7 @@
     virtual bool shouldAppearIndeterminate() const OVERRIDE;
     virtual bool supportLabels() const OVERRIDE { return true; }
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const OVERRIDE;
     RenderProgress* renderProgress() const;
 
diff --git a/Source/core/html/HTMLSelectElement.cpp b/Source/core/html/HTMLSelectElement.cpp
index 017631e..cdec5af 100644
--- a/Source/core/html/HTMLSelectElement.cpp
+++ b/Source/core/html/HTMLSelectElement.cpp
@@ -51,8 +51,6 @@
 #include "core/rendering/RenderListBox.h"
 #include "core/rendering/RenderMenuList.h"
 #include "core/rendering/RenderTheme.h"
-#include <wtf/text/StringBuilder.h>
-#include <wtf/unicode/Unicode.h>
 
 using namespace std;
 using namespace WTF::Unicode;
@@ -142,8 +140,7 @@
     ASSERT(listIndex >= 0);
     if (listIndex < 0)
         return false;
-    HTMLOptionElement* option = static_cast<HTMLOptionElement*>(listItems()[listIndex]);
-    return !listIndex && option->value().isEmpty();
+    return !listIndex && toHTMLOptionElement(listItems()[listIndex])->value().isEmpty();
 }
 
 String HTMLSelectElement::validationMessage() const
@@ -215,7 +212,7 @@
     if (!element || !(element->hasLocalName(optionTag) || element->hasLocalName(hrTag)))
         return;
 
-    insertBefore(element, before, ec);
+    insertBefore(element, before, ec, AttachLazily);
     setNeedsValidityCheck();
 }
 
@@ -240,8 +237,8 @@
 {
     const Vector<HTMLElement*>& items = listItems();
     for (unsigned i = 0; i < items.size(); i++) {
-        if (items[i]->hasLocalName(optionTag) && static_cast<HTMLOptionElement*>(items[i])->selected())
-            return static_cast<HTMLOptionElement*>(items[i])->value();
+        if (items[i]->hasLocalName(optionTag) && toHTMLOptionElement(items[i])->selected())
+            return toHTMLOptionElement(items[i])->value();
     }
     return "";
 }
@@ -259,7 +256,7 @@
     unsigned optionIndex = 0;
     for (unsigned i = 0; i < items.size(); i++) {
         if (items[i]->hasLocalName(optionTag)) {
-            if (static_cast<HTMLOptionElement*>(items[i])->value() == value) {
+            if (toHTMLOptionElement(items[i])->value() == value) {
                 setSelectedIndex(optionIndex);
                 return;
             }
@@ -315,18 +312,9 @@
         HTMLFormControlElementWithState::parseAttribute(name, value);
 }
 
-bool HTMLSelectElement::isKeyboardFocusable(KeyboardEvent* event) const
+bool HTMLSelectElement::shouldShowFocusRingOnMouseFocus() const
 {
-    if (renderer())
-        return isFocusable();
-    return HTMLFormControlElementWithState::isKeyboardFocusable(event);
-}
-
-bool HTMLSelectElement::isMouseFocusable() const
-{
-    if (renderer())
-        return isFocusable();
-    return HTMLFormControlElementWithState::isMouseFocusable();
+    return true;
 }
 
 bool HTMLSelectElement::canSelectAll() const
@@ -334,11 +322,11 @@
     return !usesMenuList();
 }
 
-RenderObject* HTMLSelectElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* HTMLSelectElement::createRenderer(RenderStyle*)
 {
     if (usesMenuList())
-        return new (arena) RenderMenuList(this);
-    return new (arena) RenderListBox(this);
+        return new (document()->renderArena()) RenderMenuList(this);
+    return new (document()->renderArena()) RenderListBox(this);
 }
 
 bool HTMLSelectElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
@@ -373,6 +361,7 @@
 {
     setRecalcListItems();
     setNeedsValidityCheck();
+    m_lastOnChangeSelection.clear();
 
     HTMLFormControlElementWithState::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
 }
@@ -641,6 +630,7 @@
 
     // If the cached selection list is empty, or the size has changed, then fire
     // dispatchFormControlChangeEvent, and return early.
+    // FIXME: Why? This looks unreasonable.
     if (m_lastOnChangeSelection.isEmpty() || m_lastOnChangeSelection.size() != items.size()) {
         dispatchFormControlChangeEvent();
         return;
@@ -959,7 +949,7 @@
     for (size_t i = listIndexStart; i < loopEndIndex; ++i) {
         if (!items[i]->hasLocalName(optionTag))
             continue;
-        if (static_cast<HTMLOptionElement*>(items[i])->value() == value)
+        if (toHTMLOptionElement(items[i])->value() == value)
             return i;
     }
     return notFound;
@@ -977,7 +967,7 @@
     for (size_t i = 0; i < itemsSize; ++i) {
         if (!items[i]->hasLocalName(optionTag))
             continue;
-        static_cast<HTMLOptionElement*>(items[i])->setSelectedState(false);
+        toHTMLOptionElement(items[i])->setSelectedState(false);
     }
 
     if (!multiple()) {
@@ -1108,7 +1098,7 @@
         if (!renderer() || !event->isKeyboardEvent())
             return;
 
-        if (platformHandleKeydownEvent(static_cast<KeyboardEvent*>(event)))
+        if (platformHandleKeydownEvent(toKeyboardEvent(event)))
             return;
 
         // When using spatial navigation, we want to be able to navigate away
@@ -1119,7 +1109,7 @@
                 return;
         }
 
-        const String& keyIdentifier = static_cast<KeyboardEvent*>(event)->keyIdentifier();
+        const String& keyIdentifier = toKeyboardEvent(event)->keyIdentifier();
         bool handled = true;
         const Vector<HTMLElement*>& listItems = this->listItems();
         int listIndex = optionToListIndex(selectedIndex());
@@ -1152,7 +1142,7 @@
         if (!renderer() || !event->isKeyboardEvent())
             return;
 
-        int keyCode = static_cast<KeyboardEvent*>(event)->keyCode();
+        int keyCode = toKeyboardEvent(event)->keyCode();
         bool handled = false;
 
         if (keyCode == ' ' && isSpatialNavigationEnabled(document()->frame())) {
@@ -1209,7 +1199,7 @@
             event->setDefaultHandled();
     }
 
-    if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && static_cast<MouseEvent*>(event)->button() == LeftButton) {
+    if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         focus();
         if (renderer() && renderer()->isMenuList()) {
             if (RenderMenuList* menuList = toRenderMenuList(renderer())) {
@@ -1290,14 +1280,14 @@
 {
     const Vector<HTMLElement*>& listItems = this->listItems();
 
-    if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && static_cast<MouseEvent*>(event)->button() == LeftButton) {
+    if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         focus();
         // Calling focus() may cause us to lose our renderer, in which case do not want to handle the event.
         if (!renderer())
             return;
 
         // Convert to coords relative to the list box if needed.
-        MouseEvent* mouseEvent = static_cast<MouseEvent*>(event);
+        MouseEvent* mouseEvent = toMouseEvent(event);
         IntPoint localOffset = roundedIntPoint(renderer()->absoluteToLocal(mouseEvent->absoluteLocation(), UseTransforms));
         int listIndex = toRenderListBox(renderer())->listIndexAtOffset(toIntSize(localOffset));
         if (listIndex >= 0) {
@@ -1314,7 +1304,7 @@
             event->setDefaultHandled();
         }
     } else if (event->type() == eventNames().mousemoveEvent && event->isMouseEvent() && !toRenderBox(renderer())->canBeScrolledAndHasScrollableArea()) {
-        MouseEvent* mouseEvent = static_cast<MouseEvent*>(event);
+        MouseEvent* mouseEvent = toMouseEvent(event);
         if (mouseEvent->button() != LeftButton || !mouseEvent->buttonDown())
             return;
 
@@ -1337,7 +1327,7 @@
             }
             event->setDefaultHandled();
         }
-    } else if (event->type() == eventNames().mouseupEvent && event->isMouseEvent() && static_cast<MouseEvent*>(event)->button() == LeftButton && renderer() && !toRenderBox(renderer())->autoscrollInProgress()) {
+    } else if (event->type() == eventNames().mouseupEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton && renderer() && !toRenderBox(renderer())->autoscrollInProgress()) {
         // We didn't start this click/drag on any options.
         if (m_lastOnChangeSelection.isEmpty())
             return;
@@ -1348,7 +1338,7 @@
     } else if (event->type() == eventNames().keydownEvent) {
         if (!event->isKeyboardEvent())
             return;
-        const String& keyIdentifier = static_cast<KeyboardEvent*>(event)->keyIdentifier();
+        const String& keyIdentifier = toKeyboardEvent(event)->keyIdentifier();
 
         bool handled = false;
         int endIndex = 0;
@@ -1407,12 +1397,12 @@
             ASSERT_UNUSED(listItems, !listItems.size() || static_cast<size_t>(endIndex) < listItems.size());
             setActiveSelectionEndIndex(endIndex);
 
-            bool selectNewItem = !m_multiple || static_cast<KeyboardEvent*>(event)->shiftKey() || !isSpatialNavigationEnabled(document()->frame());
+            bool selectNewItem = !m_multiple || toKeyboardEvent(event)->shiftKey() || !isSpatialNavigationEnabled(document()->frame());
             if (selectNewItem)
                 m_activeSelectionState = true;
             // If the anchor is unitialized, or if we're going to deselect all
             // other options, then set the anchor index equal to the end index.
-            bool deselectOthers = !m_multiple || (!static_cast<KeyboardEvent*>(event)->shiftKey() && selectNewItem);
+            bool deselectOthers = !m_multiple || (!toKeyboardEvent(event)->shiftKey() && selectNewItem);
             if (m_activeSelectionAnchorIndex < 0 || deselectOthers) {
                 if (deselectOthers)
                     deselectItemsWithoutValidation();
@@ -1431,7 +1421,7 @@
     } else if (event->type() == eventNames().keypressEvent) {
         if (!event->isKeyboardEvent())
             return;
-        int keyCode = static_cast<KeyboardEvent*>(event)->keyCode();
+        int keyCode = toKeyboardEvent(event)->keyCode();
 
         if (keyCode == '\r') {
             if (form())
@@ -1465,7 +1455,7 @@
         return;
 
     if (event->type() == eventNames().keypressEvent && event->isKeyboardEvent()) {
-        KeyboardEvent* keyboardEvent = static_cast<KeyboardEvent*>(event);
+        KeyboardEvent* keyboardEvent = toKeyboardEvent(event);
         if (!keyboardEvent->ctrlKey() && !keyboardEvent->altKey() && !keyboardEvent->metaKey() && isPrintableChar(keyboardEvent->charCode())) {
             typeAheadFind(keyboardEvent);
             event->setDefaultHandled();
diff --git a/Source/core/html/HTMLSelectElement.h b/Source/core/html/HTMLSelectElement.h
index bac7c08..1fa1b46 100644
--- a/Source/core/html/HTMLSelectElement.h
+++ b/Source/core/html/HTMLSelectElement.h
@@ -49,6 +49,8 @@
     virtual String validationMessage() const OVERRIDE;
     virtual bool valueMissing() const OVERRIDE;
 
+    virtual void reset() OVERRIDE;
+
     unsigned length() const;
 
     int size() const { return m_size; }
@@ -113,8 +115,7 @@
 private:
     virtual const AtomicString& formControlType() const;
     
-    virtual bool isKeyboardFocusable(KeyboardEvent*) const;
-    virtual bool isMouseFocusable() const;
+    virtual bool shouldShowFocusRingOnMouseFocus() const OVERRIDE;
 
     virtual void dispatchFocusEvent(PassRefPtr<Node> oldFocusedNode, FocusDirection) OVERRIDE;
     virtual void dispatchBlurEvent(PassRefPtr<Node> newFocusedNode);
@@ -131,11 +132,9 @@
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
 
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle *);
+    virtual RenderObject* createRenderer(RenderStyle *);
     virtual bool appendFormData(FormDataList&, bool);
 
-    virtual void reset();
-
     virtual void defaultEventHandler(Event*);
 
     void dispatchChangeEventForMenuList();
diff --git a/Source/core/html/HTMLSourceElement.cpp b/Source/core/html/HTMLSourceElement.cpp
index 0c42dda..9c02a7b 100644
--- a/Source/core/html/HTMLSourceElement.cpp
+++ b/Source/core/html/HTMLSourceElement.cpp
@@ -29,7 +29,6 @@
 #include "HTMLNames.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
-#include "core/html/HTMLDocument.h"
 #include "core/html/HTMLMediaElement.h"
 #include "core/platform/Logging.h"
 
diff --git a/Source/core/html/HTMLStyleElement.h b/Source/core/html/HTMLStyleElement.h
index ba2bcf1..084d4fd 100644
--- a/Source/core/html/HTMLStyleElement.h
+++ b/Source/core/html/HTMLStyleElement.h
@@ -103,14 +103,9 @@
     ScopedStyleRegistrationState m_scopedStyleRegistrationState;
 };
 
-inline bool isHTMLStyleElement(Node* node)
-{
-    return node->hasTagName(HTMLNames::styleTag);
-}
-
 inline HTMLStyleElement* toHTMLStyleElement(Node* node)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || isHTMLStyleElement(node));
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || node->hasTagName(HTMLNames::styleTag));
     return static_cast<HTMLStyleElement*>(node);
 }
 
diff --git a/Source/core/html/HTMLSummaryElement.cpp b/Source/core/html/HTMLSummaryElement.cpp
index c50214a..d047101 100644
--- a/Source/core/html/HTMLSummaryElement.cpp
+++ b/Source/core/html/HTMLSummaryElement.cpp
@@ -47,9 +47,9 @@
     ASSERT(hasTagName(summaryTag));
 }
 
-RenderObject* HTMLSummaryElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* HTMLSummaryElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderBlock(this);
+    return new (document()->renderArena()) RenderBlock(this);
 }
 
 bool HTMLSummaryElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
@@ -108,13 +108,13 @@
         }
 
         if (event->isKeyboardEvent()) {
-            if (event->type() == eventNames().keydownEvent && static_cast<KeyboardEvent*>(event)->keyIdentifier() == "U+0020") {
+            if (event->type() == eventNames().keydownEvent && toKeyboardEvent(event)->keyIdentifier() == "U+0020") {
                 setActive(true, true);
                 // No setDefaultHandled() - IE dispatches a keypress in this case.
                 return;
             }
             if (event->type() == eventNames().keypressEvent) {
-                switch (static_cast<KeyboardEvent*>(event)->charCode()) {
+                switch (toKeyboardEvent(event)->charCode()) {
                 case '\r':
                     dispatchSimulatedClick(event);
                     event->setDefaultHandled();
@@ -125,7 +125,7 @@
                     return;
                 }
             }
-            if (event->type() == eventNames().keyupEvent && static_cast<KeyboardEvent*>(event)->keyIdentifier() == "U+0020") {
+            if (event->type() == eventNames().keyupEvent && toKeyboardEvent(event)->keyIdentifier() == "U+0020") {
                 if (active())
                     dispatchSimulatedClick(event);
                 event->setDefaultHandled();
diff --git a/Source/core/html/HTMLSummaryElement.h b/Source/core/html/HTMLSummaryElement.h
index feaa019..8a2108e 100644
--- a/Source/core/html/HTMLSummaryElement.h
+++ b/Source/core/html/HTMLSummaryElement.h
@@ -36,7 +36,7 @@
 private:
     HTMLSummaryElement(const QualifiedName&, Document*);
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const OVERRIDE;
     virtual void defaultEventHandler(Event*);
 
diff --git a/Source/core/html/HTMLTableElement.cpp b/Source/core/html/HTMLTableElement.cpp
index e9145c9..209470e 100644
--- a/Source/core/html/HTMLTableElement.cpp
+++ b/Source/core/html/HTMLTableElement.cpp
@@ -29,13 +29,11 @@
 #include "CSSValueKeywords.h"
 #include "HTMLNames.h"
 #include "core/css/CSSImageValue.h"
-#include "core/css/CSSStyleSheet.h"
 #include "core/css/CSSValuePool.h"
 #include "core/css/StylePropertySet.h"
 #include "core/dom/Attribute.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/ExceptionCodePlaceholder.h"
-#include "core/dom/Text.h"
 #include "core/html/HTMLTableCaptionElement.h"
 #include "core/html/HTMLTableRowElement.h"
 #include "core/html/HTMLTableRowsCollection.h"
diff --git a/Source/core/html/HTMLTextAreaElement.cpp b/Source/core/html/HTMLTextAreaElement.cpp
index 6ba0903..2c102f2 100644
--- a/Source/core/html/HTMLTextAreaElement.cpp
+++ b/Source/core/html/HTMLTextAreaElement.cpp
@@ -204,9 +204,9 @@
         HTMLTextFormControlElement::parseAttribute(name, value);
 }
 
-RenderObject* HTMLTextAreaElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* HTMLTextAreaElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderTextControlMultiLine(this);
+    return new (document()->renderArena()) RenderTextControlMultiLine(this);
 }
 
 bool HTMLTextAreaElement::appendFormData(FormDataList& encoding, bool)
@@ -241,9 +241,9 @@
     return isFocusable();
 }
 
-bool HTMLTextAreaElement::isMouseFocusable() const
+bool HTMLTextAreaElement::shouldShowFocusRingOnMouseFocus() const
 {
-    return isFocusable();
+    return true;
 }
 
 void HTMLTextAreaElement::updateFocusAppearance(bool restorePreviousSelection)
diff --git a/Source/core/html/HTMLTextAreaElement.h b/Source/core/html/HTMLTextAreaElement.h
index 4a5efac..8d06a88 100644
--- a/Source/core/html/HTMLTextAreaElement.h
+++ b/Source/core/html/HTMLTextAreaElement.h
@@ -100,11 +100,11 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
     virtual void collectStyleForPresentationAttribute(const QualifiedName&, const AtomicString&, MutableStylePropertySet*) OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool appendFormData(FormDataList&, bool);
     virtual void reset();
     virtual bool hasCustomFocusLogic() const OVERRIDE;
-    virtual bool isMouseFocusable() const;
+    virtual bool shouldShowFocusRingOnMouseFocus() const OVERRIDE;
     virtual bool isKeyboardFocusable(KeyboardEvent*) const;
     virtual void updateFocusAppearance(bool restorePreviousSelection);
 
diff --git a/Source/core/html/HTMLTextAreaElement.idl b/Source/core/html/HTMLTextAreaElement.idl
index 105683b..cefbca9 100644
--- a/Source/core/html/HTMLTextAreaElement.idl
+++ b/Source/core/html/HTMLTextAreaElement.idl
@@ -32,6 +32,7 @@
     [Reflect] attribute boolean required;
     attribute long rows;
     [Reflect] attribute DOMString wrap;
+    [EnabledAtRuntime=inputModeAttribute, Reflect] attribute DOMString inputMode;
 
     readonly attribute DOMString type;
     [TreatNullAs=NullString] attribute DOMString defaultValue;
diff --git a/Source/core/html/HTMLTextFormControlElement.cpp b/Source/core/html/HTMLTextFormControlElement.cpp
index 100fdcc..50c6c79 100644
--- a/Source/core/html/HTMLTextFormControlElement.cpp
+++ b/Source/core/html/HTMLTextFormControlElement.cpp
@@ -621,13 +621,13 @@
             unsigned position = 0;
             while (breakNode == node && breakOffset <= length) {
                 if (breakOffset > position) {
-                    result.append(data.characters() + position, breakOffset - position);
+                    result.append(data, position, breakOffset - position);
                     position = breakOffset;
                     result.append(newlineCharacter);
                 }
                 getNextSoftBreak(line, breakNode, breakOffset);
             }
-            result.append(data.characters() + position, length - position);
+            result.append(data, position, length - position);
         }
         while (breakNode == node)
             getNextSoftBreak(line, breakNode, breakOffset);
diff --git a/Source/core/html/HTMLTitleElement.cpp b/Source/core/html/HTMLTitleElement.cpp
index 14e02ca..9df7789 100644
--- a/Source/core/html/HTMLTitleElement.cpp
+++ b/Source/core/html/HTMLTitleElement.cpp
@@ -25,11 +25,10 @@
 
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
-#include "core/dom/NodeRenderingContext.h"
 #include "core/dom/Text.h"
 #include "core/rendering/style/RenderStyle.h"
 #include "core/rendering/style/StyleInheritedData.h"
-#include <wtf/text/StringBuilder.h>
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/HTMLTrackElement.cpp b/Source/core/html/HTMLTrackElement.cpp
index 4d4a314..17e9e65 100644
--- a/Source/core/html/HTMLTrackElement.cpp
+++ b/Source/core/html/HTMLTrackElement.cpp
@@ -27,10 +27,8 @@
 #include "core/html/HTMLTrackElement.h"
 
 #include "HTMLNames.h"
-#include "bindings/v8/ScriptEventListener.h"
 #include "core/dom/Event.h"
 #include "core/html/HTMLMediaElement.h"
-#include "core/inspector/ScriptCallStack.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "RuntimeEnabledFeatures.h"
 #include "core/platform/Logging.h"
diff --git a/Source/core/html/HTMLVideoElement.cpp b/Source/core/html/HTMLVideoElement.cpp
index de51bcf..83eb6fe 100644
--- a/Source/core/html/HTMLVideoElement.cpp
+++ b/Source/core/html/HTMLVideoElement.cpp
@@ -34,7 +34,6 @@
 #include "core/dom/ExceptionCode.h"
 #include "core/html/HTMLImageLoader.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/page/Frame.h"
 #include "core/page/Settings.h"
 #include "core/rendering/RenderImage.h"
 #include "core/rendering/RenderVideo.h"
@@ -64,9 +63,9 @@
     return HTMLElement::rendererIsNeeded(context); 
 }
 
-RenderObject* HTMLVideoElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* HTMLVideoElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderVideo(this);
+    return new (document()->renderArena()) RenderVideo(this);
 }
 
 void HTMLVideoElement::attach(const AttachContext& context)
diff --git a/Source/core/html/HTMLVideoElement.h b/Source/core/html/HTMLVideoElement.h
index d2ded02..d77a4b5 100644
--- a/Source/core/html/HTMLVideoElement.h
+++ b/Source/core/html/HTMLVideoElement.h
@@ -72,7 +72,7 @@
     HTMLVideoElement(const QualifiedName&, Document*, bool);
 
     virtual bool rendererIsNeeded(const NodeRenderingContext&);
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual bool isPresentationAttribute(const QualifiedName&) const OVERRIDE;
diff --git a/Source/core/html/HiddenInputType.cpp b/Source/core/html/HiddenInputType.cpp
index b48060d..8b1d15c 100644
--- a/Source/core/html/HiddenInputType.cpp
+++ b/Source/core/html/HiddenInputType.cpp
@@ -72,7 +72,7 @@
     return false;
 }
 
-RenderObject* HiddenInputType::createRenderer(RenderArena*, RenderStyle*) const
+RenderObject* HiddenInputType::createRenderer(RenderStyle*) const
 {
     ASSERT_NOT_REACHED();
     return 0;
diff --git a/Source/core/html/HiddenInputType.h b/Source/core/html/HiddenInputType.h
index d6af8c2..bb31b47 100644
--- a/Source/core/html/HiddenInputType.h
+++ b/Source/core/html/HiddenInputType.h
@@ -45,7 +45,7 @@
     virtual FormControlState saveFormControlState() const OVERRIDE;
     virtual void restoreFormControlState(const FormControlState&) OVERRIDE;
     virtual bool supportsValidation() const OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) const OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) const OVERRIDE;
     virtual void accessKeyAction(bool sendMouseEvents) OVERRIDE;
     virtual bool rendererIsNeeded() OVERRIDE;
     virtual bool storesValueSeparateFromAttribute() OVERRIDE;
diff --git a/Source/core/html/ImageDocument.cpp b/Source/core/html/ImageDocument.cpp
index 85b95b1..eb594be 100644
--- a/Source/core/html/ImageDocument.cpp
+++ b/Source/core/html/ImageDocument.cpp
@@ -91,7 +91,7 @@
     {
     }
 
-    virtual void appendBytes(DocumentWriter*, const char*, size_t);
+    virtual size_t appendBytes(const char*, size_t) OVERRIDE;
     virtual void finish();
 };
 
@@ -125,18 +125,19 @@
     return frame ? frame->pageZoomFactor() : 1;
 }
 
-void ImageDocumentParser::appendBytes(DocumentWriter*, const char* data, size_t length)
+size_t ImageDocumentParser::appendBytes(const char* data, size_t length)
 {
     if (!length)
-        return;
+        return 0;
 
     Frame* frame = document()->frame();
     Settings* settings = frame->settings();
     if (!frame->loader()->client()->allowImage(!settings || settings->areImagesEnabled(), document()->url()))
-        return;
+        return 0;
 
     document()->cachedImage()->appendData(data, length);
     document()->imageUpdated();
+    return 0;
 }
 
 void ImageDocumentParser::finish()
@@ -374,7 +375,7 @@
     if (event->type() == eventNames().resizeEvent)
         m_doc->windowSizeChanged();
     else if (event->type() == eventNames().clickEvent && event->isMouseEvent()) {
-        MouseEvent* mouseEvent = static_cast<MouseEvent*>(event);
+        MouseEvent* mouseEvent = toMouseEvent(event);
         m_doc->imageClicked(mouseEvent->x(), mouseEvent->y());
     }
 }
diff --git a/Source/core/html/ImageInputType.cpp b/Source/core/html/ImageInputType.cpp
index eef34da..3147783 100644
--- a/Source/core/html/ImageInputType.cpp
+++ b/Source/core/html/ImageInputType.cpp
@@ -92,7 +92,7 @@
         return;
     element->setActivatedSubmit(true);
     if (event->underlyingEvent() && event->underlyingEvent()->isMouseEvent()) {
-        MouseEvent* mouseEvent = static_cast<MouseEvent*>(event->underlyingEvent());
+        MouseEvent* mouseEvent = toMouseEvent(event->underlyingEvent());
         m_clickLocation = IntPoint(mouseEvent->offsetX(), mouseEvent->offsetY());
     } else
         m_clickLocation = IntPoint();
@@ -101,9 +101,9 @@
     event->setDefaultHandled();
 }
 
-RenderObject* ImageInputType::createRenderer(RenderArena* arena, RenderStyle*) const
+RenderObject* ImageInputType::createRenderer(RenderStyle*) const
 {
-    RenderImage* image = new (arena) RenderImage(element());
+    RenderImage* image = new (element()->document()->renderArena()) RenderImage(element());
     image->setImageResource(RenderImageResource::create());
     return image;
 }
diff --git a/Source/core/html/ImageInputType.h b/Source/core/html/ImageInputType.h
index ebaca90..2341c4e 100644
--- a/Source/core/html/ImageInputType.h
+++ b/Source/core/html/ImageInputType.h
@@ -35,7 +35,6 @@
 
 #include "core/html/BaseButtonInputType.h"
 #include "core/platform/graphics/IntPoint.h"
-#include <wtf/OwnPtr.h>
 
 namespace WebCore {
 
@@ -49,7 +48,7 @@
     virtual bool isFormDataAppendable() const OVERRIDE;
     virtual bool appendFormData(FormDataList&, bool) const OVERRIDE;
     virtual bool supportsValidation() const OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) const OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) const OVERRIDE;
     virtual void handleDOMActivateEvent(Event*) OVERRIDE;
     virtual void altAttributeChanged() OVERRIDE;
     virtual void srcAttributeChanged() OVERRIDE;
diff --git a/Source/core/html/InputType.cpp b/Source/core/html/InputType.cpp
index 18bead5..665b6ae 100644
--- a/Source/core/html/InputType.cpp
+++ b/Source/core/html/InputType.cpp
@@ -429,7 +429,7 @@
 
 bool InputType::shouldSubmitImplicitly(Event* event)
 {
-    return event->isKeyboardEvent() && event->type() == eventNames().keypressEvent && static_cast<KeyboardEvent*>(event)->charCode() == '\r';
+    return event->isKeyboardEvent() && event->type() == eventNames().keypressEvent && toKeyboardEvent(event)->charCode() == '\r';
 }
 
 PassRefPtr<HTMLFormElement> InputType::formForSubmission() const
@@ -437,7 +437,7 @@
     return element()->form();
 }
 
-RenderObject* InputType::createRenderer(RenderArena*, RenderStyle* style) const
+RenderObject* InputType::createRenderer(RenderStyle* style) const
 {
     return RenderObject::createObject(element(), style);
 }
@@ -531,9 +531,9 @@
     return element()->isTextFormControlKeyboardFocusable(event);
 }
 
-bool InputType::isMouseFocusable() const
+bool InputType::shouldShowFocusRingOnMouseFocus() const
 {
-    return element()->isTextFormControlMouseFocusable();
+    return false;
 }
 
 bool InputType::shouldUseInputMethod() const
diff --git a/Source/core/html/InputType.h b/Source/core/html/InputType.h
index 0c316e4..28f95d7 100644
--- a/Source/core/html/InputType.h
+++ b/Source/core/html/InputType.h
@@ -36,11 +36,10 @@
 #include "core/html/HTMLTextFormControlElement.h"
 #include "core/html/StepRange.h"
 #include "core/page/UseCounter.h"
-#include <wtf/FastAllocBase.h>
-#include <wtf/Forward.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/FastAllocBase.h"
+#include "wtf/Forward.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
@@ -59,7 +58,6 @@
 class KeyboardEvent;
 class MouseEvent;
 class Node;
-class RenderArena;
 class RenderObject;
 class RenderStyle;
 class TouchEvent;
@@ -197,7 +195,7 @@
     virtual PassRefPtr<HTMLFormElement> formForSubmission() const;
     virtual bool hasCustomFocusLogic() const;
     virtual bool isKeyboardFocusable(KeyboardEvent*) const;
-    virtual bool isMouseFocusable() const;
+    virtual bool shouldShowFocusRingOnMouseFocus() const;
     virtual bool shouldUseInputMethod() const;
     virtual void handleFocusEvent(Node* oldFocusedNode, FocusDirection);
     virtual void handleBlurEvent();
@@ -230,7 +228,7 @@
     // Miscellaneous functions
 
     virtual bool rendererIsNeeded();
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) const;
+    virtual RenderObject* createRenderer(RenderStyle*) const;
     virtual PassRefPtr<RenderStyle> customStyleForRenderer(PassRefPtr<RenderStyle>);
     virtual void attach();
     virtual void detach();
diff --git a/Source/core/html/LabelableElement.h b/Source/core/html/LabelableElement.h
index ce7a2cf..86a23ed 100644
--- a/Source/core/html/LabelableElement.h
+++ b/Source/core/html/LabelableElement.h
@@ -50,6 +50,12 @@
     virtual bool isLabelable() const OVERRIDE FINAL { return true; }
 };
 
+inline LabelableElement* toLabelableElement(Node* node)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || (node->isHTMLElement() && toHTMLElement(node)->isLabelable()));
+    return static_cast<LabelableElement*>(node);
+}
+
 } // namespace WebCore
 
 #endif
diff --git a/Source/core/html/LinkResource.h b/Source/core/html/LinkResource.h
index a4acde8..3cac604 100644
--- a/Source/core/html/LinkResource.h
+++ b/Source/core/html/LinkResource.h
@@ -33,7 +33,6 @@
 
 #include "core/loader/cache/CachedResourceRequest.h"
 #include "weborigin/KURL.h"
-#include "wtf/Forward.h"
 #include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
 
diff --git a/Source/core/html/MediaController.h b/Source/core/html/MediaController.h
index 4ec9d6e..cb05e8c 100644
--- a/Source/core/html/MediaController.h
+++ b/Source/core/html/MediaController.h
@@ -27,15 +27,13 @@
 #define MediaController_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/ActiveDOMObject.h"
 #include "core/dom/Event.h"
-#include "core/dom/EventListener.h"
 #include "core/dom/EventTarget.h"
 #include "core/html/MediaControllerInterface.h"
 #include "core/platform/Timer.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/Vector.h>
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/MediaDocument.cpp b/Source/core/html/MediaDocument.cpp
index 9c8d880..4be22af 100644
--- a/Source/core/html/MediaDocument.cpp
+++ b/Source/core/html/MediaDocument.cpp
@@ -60,7 +60,7 @@
     {
     }
 
-    virtual void appendBytes(DocumentWriter*, const char*, size_t);
+    virtual size_t appendBytes(const char*, size_t) OVERRIDE;
 
     void createDocumentStructure();
 
@@ -97,21 +97,16 @@
 
     m_mediaElement->appendChild(sourceElement, IGNORE_EXCEPTION);
     body->appendChild(mediaElement, IGNORE_EXCEPTION);
-
-    Frame* frame = document()->frame();
-    if (!frame)
-        return;
-
-    frame->loader()->activeDocumentLoader()->setMainResourceDataBufferingPolicy(DoNotBufferData);
 }
 
-void MediaDocumentParser::appendBytes(DocumentWriter*, const char*, size_t)
+size_t MediaDocumentParser::appendBytes(const char*, size_t)
 {
     if (m_mediaElement)
-        return;
+        return 0;
 
     createDocumentStructure();
     finish();
+    return 0;
 }
     
 MediaDocument::MediaDocument(Frame* frame, const KURL& url)
@@ -154,7 +149,7 @@
         if (!video)
             return;
 
-        KeyboardEvent* keyboardEvent = static_cast<KeyboardEvent*>(event);
+        KeyboardEvent* keyboardEvent = toKeyboardEvent(event);
         if (keyboardEvent->keyIdentifier() == "U+0020" || keyboardEvent->keyCode() == VKEY_MEDIA_PLAY_PAUSE) {
             // space or media key (play/pause)
             if (video->paused()) {
diff --git a/Source/core/html/MediaFragmentURIParser.cpp b/Source/core/html/MediaFragmentURIParser.cpp
index d8e7af5..5a8ddf9 100644
--- a/Source/core/html/MediaFragmentURIParser.cpp
+++ b/Source/core/html/MediaFragmentURIParser.cpp
@@ -126,11 +126,10 @@
         //  a. Decode percent-encoded octets in name and value as defined by RFC 3986. If either
         //     name or value are not valid percent-encoded strings, then remove the name-value pair
         //     from the list.
-        const UChar* fragmentStart = fragmentString.characters();
-        String name = decodeURLEscapeSequences(String(fragmentStart + parameterStart, equalOffset - parameterStart));
+        String name = decodeURLEscapeSequences(fragmentString.substring(parameterStart, equalOffset - parameterStart));
         String value;
         if (equalOffset != parameterEnd)
-            value = decodeURLEscapeSequences(String(fragmentStart + equalOffset + 1, parameterEnd - equalOffset - 1));
+            value = decodeURLEscapeSequences(fragmentString.substring(equalOffset + 1, parameterEnd - equalOffset - 1));
         
         //  b. Convert name and value to Unicode strings by interpreting them as UTF-8. If either
         //     name or value are not valid UTF-8 strings, then remove the name-value pair from the list.
diff --git a/Source/core/html/MediaFragmentURIParser.h b/Source/core/html/MediaFragmentURIParser.h
index 5d5be04..50c95c7 100644
--- a/Source/core/html/MediaFragmentURIParser.h
+++ b/Source/core/html/MediaFragmentURIParser.h
@@ -27,7 +27,6 @@
 #define MediaFragmentURIParser_h
 
 #include "weborigin/KURL.h"
-#include "wtf/PassOwnPtr.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
diff --git a/Source/core/html/MonthInputType.cpp b/Source/core/html/MonthInputType.cpp
index bf4f8b5..885f311 100644
--- a/Source/core/html/MonthInputType.cpp
+++ b/Source/core/html/MonthInputType.cpp
@@ -128,11 +128,11 @@
     return Decimal::fromDouble(months);
 }
 
-bool MonthInputType::parseToDateComponentsInternal(const UChar* characters, unsigned length, DateComponents* out) const
+bool MonthInputType::parseToDateComponentsInternal(const String& string, DateComponents* out) const
 {
     ASSERT(out);
     unsigned end;
-    return out->parseMonth(characters, length, 0, end) && end == length;
+    return out->parseMonth(string, 0, end) && end == string.length();
 }
 
 bool MonthInputType::setMillisecondToDateComponents(double value, DateComponents* date) const
diff --git a/Source/core/html/MonthInputType.h b/Source/core/html/MonthInputType.h
index 2e11cd4..9fbfd33 100644
--- a/Source/core/html/MonthInputType.h
+++ b/Source/core/html/MonthInputType.h
@@ -56,7 +56,7 @@
     virtual Decimal parseToNumber(const String&, const Decimal&) const OVERRIDE;
     virtual Decimal defaultValueForStepUp() const OVERRIDE;
     virtual StepRange createStepRange(AnyStepHandling) const OVERRIDE;
-    virtual bool parseToDateComponentsInternal(const UChar*, unsigned length, DateComponents*) const OVERRIDE;
+    virtual bool parseToDateComponentsInternal(const String&, DateComponents*) const OVERRIDE;
     virtual bool setMillisecondToDateComponents(double, DateComponents*) const OVERRIDE;
     virtual bool isMonthField() const OVERRIDE;
 
diff --git a/Source/core/html/NumberInputType.cpp b/Source/core/html/NumberInputType.cpp
index e66394b..be73a85 100644
--- a/Source/core/html/NumberInputType.cpp
+++ b/Source/core/html/NumberInputType.cpp
@@ -34,7 +34,6 @@
 
 #include <limits>
 #include "HTMLNames.h"
-#include "core/dom/BeforeTextInsertedEvent.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/KeyboardEvent.h"
 #include "core/html/HTMLInputElement.h"
@@ -43,9 +42,8 @@
 #include "core/platform/LocalizedStrings.h"
 #include "core/platform/text/PlatformLocale.h"
 #include "core/rendering/RenderTextControl.h"
-#include <wtf/ASCIICType.h>
-#include <wtf/MathExtras.h>
-#include <wtf/PassOwnPtr.h>
+#include "wtf/MathExtras.h"
+#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/PluginDocument.cpp b/Source/core/html/PluginDocument.cpp
index ad47278..b4f129c 100644
--- a/Source/core/html/PluginDocument.cpp
+++ b/Source/core/html/PluginDocument.cpp
@@ -35,6 +35,7 @@
 #include "core/loader/FrameLoaderClient.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
+#include "core/plugins/PluginView.h"
 #include "core/rendering/RenderEmbeddedObject.h"
 
 namespace WebCore {
@@ -56,10 +57,14 @@
     {
     }
 
-    virtual void appendBytes(DocumentWriter*, const char*, size_t);
+    virtual size_t appendBytes(const char*, size_t) OVERRIDE;
+
+    virtual void finish() OVERRIDE;
 
     void createDocumentStructure();
 
+    PluginView* pluginView() const;
+
     HTMLEmbedElement* m_embedElement;
 };
 
@@ -91,19 +96,11 @@
     DocumentLoader* loader = document()->loader();
     ASSERT(loader);
     if (loader)
-        m_embedElement->setAttribute(typeAttr, loader->writer()->mimeType());
+        m_embedElement->setAttribute(typeAttr, loader->mimeType());
 
     toPluginDocument(document())->setPluginNode(m_embedElement);
 
     body->appendChild(embedElement, IGNORE_EXCEPTION);
-}
-
-void PluginDocumentParser::appendBytes(DocumentWriter*, const char*, size_t)
-{
-    if (m_embedElement)
-        return;
-
-    createDocumentStructure();
 
     Frame* frame = document()->frame();
     if (!frame)
@@ -121,15 +118,42 @@
     // can synchronously redirect data to the plugin.
     frame->view()->flushAnyPendingPostLayoutTasks();
 
-    if (RenderPart* renderer = m_embedElement->renderPart()) {
-        if (Widget* widget = renderer->widget()) {
-            frame->loader()->client()->redirectDataToPlugin(widget);
-            // In a plugin document, the main resource is the plugin. If we have a null widget, that means
-            // the loading of the plugin was cancelled, which gives us a null mainResourceLoader(), so we
-            // need to have this call in a null check of the widget or of mainResourceLoader().
-            frame->loader()->activeDocumentLoader()->setMainResourceDataBufferingPolicy(DoNotBufferData);
-        }
+    if (PluginView* view = pluginView())
+        view->didReceiveResponse(document()->loader()->response());
+}
+
+size_t PluginDocumentParser::appendBytes(const char* data, size_t length)
+{
+    if (!m_embedElement)
+        createDocumentStructure();
+
+    if (!length)
+        return 0;
+    if (PluginView* view = pluginView())
+        view->didReceiveData(data, length);
+
+    return 0;
+}
+
+void PluginDocumentParser::finish()
+{
+    if (PluginView* view = pluginView()) {
+        const ResourceError& error = document()->loader()->mainDocumentError();
+        if (error.isNull())
+            view->didFinishLoading();
+        else
+            view->didFailLoading(error);
     }
+    RawDataDocumentParser::finish();
+}
+
+PluginView* PluginDocumentParser::pluginView() const
+{
+    if (Widget* widget = static_cast<PluginDocument*>(document())->pluginWidget()) {
+        ASSERT_WITH_SECURITY_IMPLICATION(widget->isPluginContainer());
+        return static_cast<PluginView*>(widget);
+    }
+    return 0;
 }
 
 PluginDocument::PluginDocument(Frame* frame, const KURL& url)
@@ -163,8 +187,6 @@
 {
     // Release the plugin node so that we don't have a circular reference.
     m_pluginNode = 0;
-    if (FrameLoader* loader = frame()->loader())
-        loader->client()->redirectDataToPlugin(0);
     HTMLDocument::detach(context);
 }
 
diff --git a/Source/core/html/PublicURLManager.h b/Source/core/html/PublicURLManager.h
index 9aeed98..7b9f2f7 100644
--- a/Source/core/html/PublicURLManager.h
+++ b/Source/core/html/PublicURLManager.h
@@ -30,7 +30,6 @@
 #include "wtf/HashMap.h"
 #include "wtf/HashSet.h"
 #include "wtf/PassOwnPtr.h"
-#include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
diff --git a/Source/core/html/RadioInputType.cpp b/Source/core/html/RadioInputType.cpp
index d228a97..1818056 100644
--- a/Source/core/html/RadioInputType.cpp
+++ b/Source/core/html/RadioInputType.cpp
@@ -94,6 +94,7 @@
         if (inputElement->form() != element()->form())
             break;
         if (inputElement->isRadioButton() && inputElement->name() == element()->name() && inputElement->isFocusable()) {
+            RefPtr<HTMLInputElement> protector(inputElement);
             document->setFocusedNode(inputElement);
             inputElement->dispatchSimulatedClick(event, SendNoEvents, DoNotShowPressedLook);
             event->setDefaultHandled();
diff --git a/Source/core/html/RadioNodeList.cpp b/Source/core/html/RadioNodeList.cpp
index 66fd5dc..5768dcf 100644
--- a/Source/core/html/RadioNodeList.cpp
+++ b/Source/core/html/RadioNodeList.cpp
@@ -92,7 +92,7 @@
         if (testElement->hasTagName(objectTag))
             formElement = static_cast<HTMLObjectElement*>(testElement)->form();
         else
-            formElement = static_cast<HTMLFormControlElement*>(testElement)->form();
+            formElement = toHTMLFormControlElement(testElement)->form();
         if (!formElement || formElement != ownerNode())
             return false;
     }
diff --git a/Source/core/html/RadioNodeList.h b/Source/core/html/RadioNodeList.h
index 85a5dfd..d0bdbf3 100644
--- a/Source/core/html/RadioNodeList.h
+++ b/Source/core/html/RadioNodeList.h
@@ -27,10 +27,8 @@
 #define RadioNodeList_h
 
 #include "core/dom/LiveNodeList.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/AtomicString.h>
-#include <wtf/Vector.h>
+#include "wtf/PassRefPtr.h"
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/RangeInputType.cpp b/Source/core/html/RangeInputType.cpp
index e96c490..ebac793 100644
--- a/Source/core/html/RangeInputType.cpp
+++ b/Source/core/html/RangeInputType.cpp
@@ -254,9 +254,9 @@
     element()->userAgentShadowRoot()->appendChild(container.release(), IGNORE_EXCEPTION);
 }
 
-RenderObject* RangeInputType::createRenderer(RenderArena* arena, RenderStyle*) const
+RenderObject* RangeInputType::createRenderer(RenderStyle*) const
 {
-    return new (arena) RenderSlider(element());
+    return new (element()->document()->renderArena()) RenderSlider(element());
 }
 
 Decimal RangeInputType::parseToNumber(const String& src, const Decimal& defaultValue) const
diff --git a/Source/core/html/RangeInputType.h b/Source/core/html/RangeInputType.h
index 76c2ceb..2b6e24d 100644
--- a/Source/core/html/RangeInputType.h
+++ b/Source/core/html/RangeInputType.h
@@ -56,7 +56,7 @@
     virtual void handleTouchEvent(TouchEvent*) OVERRIDE;
     virtual bool hasTouchEventHandler() const OVERRIDE;
     virtual void handleKeydownEvent(KeyboardEvent*) OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) const OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) const OVERRIDE;
     virtual void createShadowSubtree() OVERRIDE;
     virtual Decimal parseToNumber(const String&, const Decimal&) const OVERRIDE;
     virtual String serialize(const Decimal&) const OVERRIDE;
diff --git a/Source/core/html/SearchInputType.cpp b/Source/core/html/SearchInputType.cpp
index 7d21d26..dc515fc 100644
--- a/Source/core/html/SearchInputType.cpp
+++ b/Source/core/html/SearchInputType.cpp
@@ -62,9 +62,9 @@
     observeFeatureIfVisible(UseCounter::InputTypeSearch);
 }
 
-RenderObject* SearchInputType::createRenderer(RenderArena* arena, RenderStyle*) const
+RenderObject* SearchInputType::createRenderer(RenderStyle*) const
 {
-    return new (arena) RenderSearchField(element());
+    return new (element()->document()->renderArena()) RenderSearchField(element());
 }
 
 const AtomicString& SearchInputType::formControlType() const
diff --git a/Source/core/html/SearchInputType.h b/Source/core/html/SearchInputType.h
index 3a35cc9..c30272e 100644
--- a/Source/core/html/SearchInputType.h
+++ b/Source/core/html/SearchInputType.h
@@ -48,7 +48,7 @@
 private:
     SearchInputType(HTMLInputElement*);
     virtual void attach() OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) const OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) const OVERRIDE;
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual bool shouldRespectSpeechAttribute() OVERRIDE;
     virtual bool isSearchField() const OVERRIDE;
diff --git a/Source/core/html/StepRange.h b/Source/core/html/StepRange.h
index 4aa5cae..0b04444 100644
--- a/Source/core/html/StepRange.h
+++ b/Source/core/html/StepRange.h
@@ -22,8 +22,7 @@
 #define StepRange_h
 
 #include "core/platform/Decimal.h"
-#include <wtf/Forward.h>
-#include <wtf/Noncopyable.h>
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/TextFieldInputType.cpp b/Source/core/html/TextFieldInputType.cpp
index 92a4676..9c848cb 100644
--- a/Source/core/html/TextFieldInputType.cpp
+++ b/Source/core/html/TextFieldInputType.cpp
@@ -48,6 +48,7 @@
 #include "core/page/ChromeClient.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
+#include "core/page/Settings.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderTextControlSingleLine.h"
 #include "core/rendering/RenderTheme.h"
@@ -73,9 +74,9 @@
     return element()->isFocusable();
 }
 
-bool TextFieldInputType::isMouseFocusable() const
+bool TextFieldInputType::shouldShowFocusRingOnMouseFocus() const
 {
-    return element()->isFocusable();
+    return true;
 }
 
 bool TextFieldInputType::isTextField() const
@@ -83,9 +84,18 @@
     return true;
 }
 
+static inline bool shouldIgnoreRequiredAttribute(const HTMLInputElement& input)
+{
+    if (!input.document()->settings() || !input.document()->settings()->needsSiteSpecificQuirks())
+        return false;
+    if (!equalIgnoringCase(input.document()->url().host(), "egov.uscis.gov"))
+        return false;
+    return input.fastGetAttribute(requiredAttr) == "no";
+}
+
 bool TextFieldInputType::valueMissing(const String& value) const
 {
-    return element()->isRequired() && value.isEmpty();
+    return !shouldIgnoreRequiredAttribute(*element()) && element()->isRequired() && value.isEmpty();
 }
 
 bool TextFieldInputType::canSetSuggestedValue()
@@ -201,9 +211,9 @@
     return (event->type() == eventNames().textInputEvent && event->hasInterface(eventNames().interfaceForTextEvent) && static_cast<TextEvent*>(event)->data() == "\n") || InputType::shouldSubmitImplicitly(event);
 }
 
-RenderObject* TextFieldInputType::createRenderer(RenderArena* arena, RenderStyle*) const
+RenderObject* TextFieldInputType::createRenderer(RenderStyle*) const
 {
-    return new (arena) RenderTextControlSingleLine(element());
+    return new (element()->document()->renderArena()) RenderTextControlSingleLine(element());
 }
 
 bool TextFieldInputType::needsContainer() const
diff --git a/Source/core/html/TextFieldInputType.h b/Source/core/html/TextFieldInputType.h
index 48e06fc..e38ad76 100644
--- a/Source/core/html/TextFieldInputType.h
+++ b/Source/core/html/TextFieldInputType.h
@@ -33,7 +33,6 @@
 
 #include "core/html/InputType.h"
 #include "core/html/shadow/SpinButtonElement.h"
-#include "core/html/shadow/TextControlInnerElements.h"
 
 namespace WebCore {
 
@@ -80,13 +79,13 @@
 
 private:
     virtual bool isKeyboardFocusable(KeyboardEvent*) const OVERRIDE;
-    virtual bool isMouseFocusable() const OVERRIDE;
+    virtual bool shouldShowFocusRingOnMouseFocus() const OVERRIDE;
     virtual bool isTextField() const OVERRIDE;
     virtual bool valueMissing(const String&) const OVERRIDE;
     virtual void handleBeforeTextInsertedEvent(BeforeTextInsertedEvent*) OVERRIDE;
     virtual void forwardEvent(Event*) OVERRIDE;
     virtual bool shouldSubmitImplicitly(Event*) OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) const OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) const OVERRIDE;
     virtual bool shouldUseInputMethod() const OVERRIDE;
     virtual String sanitizeValue(const String&) const OVERRIDE;
     virtual bool shouldRespectListAttribute() OVERRIDE;
diff --git a/Source/core/html/TimeInputType.cpp b/Source/core/html/TimeInputType.cpp
index bc0d6ea..c20d431 100644
--- a/Source/core/html/TimeInputType.cpp
+++ b/Source/core/html/TimeInputType.cpp
@@ -105,11 +105,11 @@
     return StepRange(stepBase, minimum, maximum, step, stepDescription);
 }
 
-bool TimeInputType::parseToDateComponentsInternal(const UChar* characters, unsigned length, DateComponents* out) const
+bool TimeInputType::parseToDateComponentsInternal(const String& string, DateComponents* out) const
 {
     ASSERT(out);
     unsigned end;
-    return out->parseTime(characters, length, 0, end) && end == length;
+    return out->parseTime(string, 0, end) && end == string.length();
 }
 
 bool TimeInputType::setMillisecondToDateComponents(double value, DateComponents* date) const
diff --git a/Source/core/html/TimeInputType.h b/Source/core/html/TimeInputType.h
index 4a1eca6..31a968b 100644
--- a/Source/core/html/TimeInputType.h
+++ b/Source/core/html/TimeInputType.h
@@ -53,7 +53,7 @@
     virtual DateComponents::Type dateType() const OVERRIDE;
     virtual Decimal defaultValueForStepUp() const OVERRIDE;
     virtual StepRange createStepRange(AnyStepHandling) const OVERRIDE;
-    virtual bool parseToDateComponentsInternal(const UChar*, unsigned length, DateComponents*) const OVERRIDE;
+    virtual bool parseToDateComponentsInternal(const String&, DateComponents*) const OVERRIDE;
     virtual bool setMillisecondToDateComponents(double, DateComponents*) const OVERRIDE;
     virtual bool isTimeField() const OVERRIDE;
 #if ENABLE(INPUT_MULTIPLE_FIELDS_UI)
diff --git a/Source/core/html/TypeAhead.cpp b/Source/core/html/TypeAhead.cpp
index e404255..d93541f 100644
--- a/Source/core/html/TypeAhead.cpp
+++ b/Source/core/html/TypeAhead.cpp
@@ -29,8 +29,7 @@
 #include "core/html/TypeAhead.h"
 
 #include "core/dom/KeyboardEvent.h"
-#include <wtf/unicode/CharacterNames.h>
-#include <wtf/unicode/Unicode.h>
+#include "wtf/unicode/CharacterNames.h"
 
 using namespace WTF::Unicode;
 
diff --git a/Source/core/html/URL.idl b/Source/core/html/URL.idl
index b631c4c..9f71a67 100644
--- a/Source/core/html/URL.idl
+++ b/Source/core/html/URL.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     Constructor,
     ImplementedAs=DOMURL
 ] interface URL {
diff --git a/Source/core/html/ValidationMessage.cpp b/Source/core/html/ValidationMessage.cpp
index 83cf399..7b4e298 100644
--- a/Source/core/html/ValidationMessage.cpp
+++ b/Source/core/html/ValidationMessage.cpp
@@ -33,7 +33,6 @@
 
 #include "core/html/HTMLFormControlElement.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
 #include "core/page/ValidationMessageClient.h"
 #include "wtf/PassOwnPtr.h"
 
diff --git a/Source/core/html/ValidityState.cpp b/Source/core/html/ValidityState.cpp
index 98cbdb7..b47a93c 100644
--- a/Source/core/html/ValidityState.cpp
+++ b/Source/core/html/ValidityState.cpp
@@ -24,18 +24,8 @@
 #include "config.h"
 #include "core/html/ValidityState.h"
 
-#include "HTMLNames.h"
-#include "core/html/HTMLInputElement.h"
-#include "core/html/HTMLSelectElement.h"
-#include "core/html/HTMLTextAreaElement.h"
-#include "core/html/parser/HTMLTreeBuilder.h"
-#include "core/platform/LocalizedStrings.h"
-#include <wtf/StdLibExtras.h>
-
 namespace WebCore {
 
-using namespace HTMLNames;
-
 String ValidityState::validationMessage() const
 {
     return m_control->validationMessage();
diff --git a/Source/core/html/WeekInputType.cpp b/Source/core/html/WeekInputType.cpp
index 64ad701..50cfd74 100644
--- a/Source/core/html/WeekInputType.cpp
+++ b/Source/core/html/WeekInputType.cpp
@@ -82,11 +82,11 @@
     return StepRange(stepBase, minimum, maximum, step, stepDescription);
 }
 
-bool WeekInputType::parseToDateComponentsInternal(const UChar* characters, unsigned length, DateComponents* out) const
+bool WeekInputType::parseToDateComponentsInternal(const String& string, DateComponents* out) const
 {
     ASSERT(out);
     unsigned end;
-    return out->parseWeek(characters, length, 0, end) && end == length;
+    return out->parseWeek(string, 0, end) && end == string.length();
 }
 
 bool WeekInputType::setMillisecondToDateComponents(double value, DateComponents* date) const
diff --git a/Source/core/html/WeekInputType.h b/Source/core/html/WeekInputType.h
index 9242089..5aa3ea7 100644
--- a/Source/core/html/WeekInputType.h
+++ b/Source/core/html/WeekInputType.h
@@ -52,7 +52,7 @@
     virtual const AtomicString& formControlType() const OVERRIDE;
     virtual DateComponents::Type dateType() const OVERRIDE;
     virtual StepRange createStepRange(AnyStepHandling) const OVERRIDE;
-    virtual bool parseToDateComponentsInternal(const UChar*, unsigned length, DateComponents*) const OVERRIDE;
+    virtual bool parseToDateComponentsInternal(const String&, DateComponents*) const OVERRIDE;
     virtual bool setMillisecondToDateComponents(double, DateComponents*) const OVERRIDE;
     virtual bool isWeekField() const OVERRIDE;
 
diff --git a/Source/core/html/canvas/ArrayBuffer.idl b/Source/core/html/canvas/ArrayBuffer.idl
index 1a6df2d..781bd90 100644
--- a/Source/core/html/canvas/ArrayBuffer.idl
+++ b/Source/core/html/canvas/ArrayBuffer.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     CustomConstructor(unsigned long length)
 ] interface ArrayBuffer {
     readonly attribute unsigned long byteLength;
diff --git a/Source/core/html/canvas/ArrayBufferView.idl b/Source/core/html/canvas/ArrayBufferView.idl
index 9626c46..0f0aba6 100644
--- a/Source/core/html/canvas/ArrayBufferView.idl
+++ b/Source/core/html/canvas/ArrayBufferView.idl
@@ -24,6 +24,7 @@
  */
 
 [
+    NoInterfaceObject,
     CustomToV8
 ] interface ArrayBufferView {
     readonly attribute ArrayBuffer buffer;
diff --git a/Source/core/html/canvas/CanvasGradient.idl b/Source/core/html/canvas/CanvasGradient.idl
index 0e07d5e..4d06b83 100644
--- a/Source/core/html/canvas/CanvasGradient.idl
+++ b/Source/core/html/canvas/CanvasGradient.idl
@@ -1,5 +1,6 @@
 /*
  * Copyright (C) 2006 Apple Computer, Inc.  All rights reserved.
+ * Copyright (C) 2013 Intel Corporation. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -25,8 +26,7 @@
 [
 ] interface CanvasGradient {
 
-    [RaisesException] void addColorStop([Default=Undefined] optional float offset, 
-                      [Default=Undefined] optional DOMString color);
+    [RaisesException] void addColorStop(float offset, DOMString color);
 
 };
 
diff --git a/Source/core/html/canvas/CanvasPathMethods.h b/Source/core/html/canvas/CanvasPathMethods.h
index 19fa93e..3259697 100644
--- a/Source/core/html/canvas/CanvasPathMethods.h
+++ b/Source/core/html/canvas/CanvasPathMethods.h
@@ -31,8 +31,6 @@
 
 #include "core/platform/graphics/Path.h"
 
-#include <wtf/Noncopyable.h>
-
 namespace WebCore {
 
 class FloatRect;
diff --git a/Source/core/html/canvas/CanvasRenderingContext.h b/Source/core/html/canvas/CanvasRenderingContext.h
index d8abb8e..f014a7f 100644
--- a/Source/core/html/canvas/CanvasRenderingContext.h
+++ b/Source/core/html/canvas/CanvasRenderingContext.h
@@ -28,10 +28,9 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/html/HTMLCanvasElement.h"
-#include "core/platform/graphics/GraphicsLayer.h"
-#include <wtf/HashSet.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/text/StringHash.h>
+#include "wtf/HashSet.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/text/StringHash.h"
 
 namespace WebKit { class WebLayer; }
 
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.cpp b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
index 89ea17d..bbb61bb 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.cpp
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.cpp
@@ -34,8 +34,6 @@
 #include "core/html/canvas/CanvasRenderingContext2D.h"
 
 #include "CSSPropertyNames.h"
-#include "HTMLNames.h"
-#include "RuntimeEnabledFeatures.h"
 #include "core/css/CSSFontSelector.h"
 #include "core/css/CSSParser.h"
 #include "core/css/StylePropertySet.h"
@@ -54,33 +52,25 @@
 #include "core/html/canvas/CanvasStyle.h"
 #include "core/html/canvas/DOMPath.h"
 #include "core/loader/cache/CachedImage.h"
-#include "core/page/Console.h"
-#include "core/page/Page.h"
-#include "core/page/Settings.h"
-#include "core/platform/FloatConversion.h"
+#include "core/platform/graphics/DrawLooper.h"
 #include "core/platform/graphics/FloatQuad.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/platform/graphics/TextRun.h"
 #include "core/platform/graphics/transforms/AffineTransform.h"
-#include "core/rendering/RenderHTMLCanvas.h"
 #include "core/rendering/RenderLayer.h"
-#include "weborigin/KURL.h"
 #include "weborigin/SecurityOrigin.h"
 
-#include <wtf/CheckedArithmetic.h>
-#include <wtf/MathExtras.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/text/StringBuilder.h>
-#include <wtf/Uint8ClampedArray.h>
-#include <wtf/UnusedParam.h>
+#include "wtf/CheckedArithmetic.h"
+#include "wtf/MathExtras.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/Uint8ClampedArray.h"
+#include "wtf/text/StringBuilder.h"
 
 using namespace std;
 
 namespace WebCore {
 
-using namespace HTMLNames;
-
 static const int defaultFontSize = 10;
 static const char* const defaultFontFamily = "sans-serif";
 static const char* const defaultFont = "10px sans-serif";
@@ -587,8 +577,6 @@
     BlendMode blendMode = BlendModeNormal;
     if (!parseCompositeAndBlendOperator(operation, op, blendMode))
         return;
-    if (!RuntimeEnabledFeatures::cssCompositingEnabled() && blendMode != BlendModeNormal)
-        blendMode = BlendModeNormal;
     if ((state().m_globalComposite == op) && (state().m_globalBlend == blendMode))
         return;
     realizeSaves();
@@ -1163,10 +1151,12 @@
     if (!c)
         return;
 
-    if (shouldDrawShadows())
-        c->setShadow(state().m_shadowOffset, state().m_shadowBlur, state().m_shadowColor);
-    else
+    if (shouldDrawShadows()) {
+        c->setShadow(state().m_shadowOffset, state().m_shadowBlur, state().m_shadowColor,
+            DrawLooper::ShadowIgnoresTransforms);
+    } else {
         c->clearShadow();
+    }
 }
 
 bool CanvasRenderingContext2D::shouldDrawShadows() const
@@ -2076,7 +2066,7 @@
 {
     FontCachePurgePreventer fontCachePurgePreventer;
     RefPtr<TextMetrics> metrics = TextMetrics::create();
-    metrics->setWidth(accessFont().width(TextRun(text.characters(), text.length())));
+    metrics->setWidth(accessFont().width(TextRun(text)));
     return metrics.release();
 }
 
diff --git a/Source/core/html/canvas/CanvasRenderingContext2D.h b/Source/core/html/canvas/CanvasRenderingContext2D.h
index c48e913..d4ff4af 100644
--- a/Source/core/html/canvas/CanvasRenderingContext2D.h
+++ b/Source/core/html/canvas/CanvasRenderingContext2D.h
@@ -30,7 +30,6 @@
 #include "core/html/canvas/CanvasPathMethods.h"
 #include "core/html/canvas/CanvasRenderingContext.h"
 #include "core/platform/graphics/Color.h"
-#include "core/platform/graphics/DashArray.h"
 #include "core/platform/graphics/FloatSize.h"
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/GraphicsTypes.h"
diff --git a/Source/core/html/canvas/DataView.idl b/Source/core/html/canvas/DataView.idl
index 5ff575d..5847f9c 100644
--- a/Source/core/html/canvas/DataView.idl
+++ b/Source/core/html/canvas/DataView.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     CustomConstructor(ArrayBuffer buffer, optional unsigned long byteOffset, optional unsigned long byteLength),
     CustomToV8
 ] interface DataView : ArrayBufferView {
diff --git a/Source/core/html/canvas/Float32Array.idl b/Source/core/html/canvas/Float32Array.idl
index a9b9dac..7d5818d 100644
--- a/Source/core/html/canvas/Float32Array.idl
+++ b/Source/core/html/canvas/Float32Array.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     ConstructorTemplate=TypedArray,
     CustomToV8,
     DoNotCheckConstants
diff --git a/Source/core/html/canvas/Float64Array.idl b/Source/core/html/canvas/Float64Array.idl
index 28f9d6b..3215e80 100644
--- a/Source/core/html/canvas/Float64Array.idl
+++ b/Source/core/html/canvas/Float64Array.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     ConstructorTemplate=TypedArray,
     CustomToV8,
     DoNotCheckConstants
diff --git a/Source/core/html/canvas/Int16Array.idl b/Source/core/html/canvas/Int16Array.idl
index 42c8dac..63640db 100644
--- a/Source/core/html/canvas/Int16Array.idl
+++ b/Source/core/html/canvas/Int16Array.idl
@@ -24,7 +24,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     ConstructorTemplate=TypedArray,
     CustomToV8,
     DoNotCheckConstants
diff --git a/Source/core/html/canvas/Int32Array.idl b/Source/core/html/canvas/Int32Array.idl
index fb4b6d1..012e6a8 100644
--- a/Source/core/html/canvas/Int32Array.idl
+++ b/Source/core/html/canvas/Int32Array.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     ConstructorTemplate=TypedArray,
     CustomToV8,
     DoNotCheckConstants
diff --git a/Source/core/html/canvas/Int8Array.idl b/Source/core/html/canvas/Int8Array.idl
index 52434af..5c65ac1 100644
--- a/Source/core/html/canvas/Int8Array.idl
+++ b/Source/core/html/canvas/Int8Array.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     ConstructorTemplate=TypedArray,
     CustomToV8,
     DoNotCheckConstants
diff --git a/Source/core/html/canvas/OESVertexArrayObject.h b/Source/core/html/canvas/OESVertexArrayObject.h
index 7ac7de4..fc49109 100644
--- a/Source/core/html/canvas/OESVertexArrayObject.h
+++ b/Source/core/html/canvas/OESVertexArrayObject.h
@@ -28,10 +28,8 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/html/canvas/WebGLExtension.h"
-#include "core/html/canvas/WebGLVertexArrayObjectOES.h"
 #include "core/platform/graphics/GraphicsTypes3D.h"
 #include "wtf/PassRefPtr.h"
-#include "wtf/UnusedParam.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/canvas/Uint16Array.idl b/Source/core/html/canvas/Uint16Array.idl
index 086ee28..96e95ee 100644
--- a/Source/core/html/canvas/Uint16Array.idl
+++ b/Source/core/html/canvas/Uint16Array.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     ConstructorTemplate=TypedArray,
     CustomToV8,
     DoNotCheckConstants
diff --git a/Source/core/html/canvas/Uint32Array.idl b/Source/core/html/canvas/Uint32Array.idl
index 3c69bfd..a964686 100644
--- a/Source/core/html/canvas/Uint32Array.idl
+++ b/Source/core/html/canvas/Uint32Array.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     ConstructorTemplate=TypedArray,
     CustomToV8,
     DoNotCheckConstants
diff --git a/Source/core/html/canvas/Uint8Array.idl b/Source/core/html/canvas/Uint8Array.idl
index b9c6a21..afa941c 100644
--- a/Source/core/html/canvas/Uint8Array.idl
+++ b/Source/core/html/canvas/Uint8Array.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     ConstructorTemplate=TypedArray,
     CustomToV8,
     DoNotCheckConstants
diff --git a/Source/core/html/canvas/Uint8ClampedArray.idl b/Source/core/html/canvas/Uint8ClampedArray.idl
index 895505a..66c9289 100644
--- a/Source/core/html/canvas/Uint8ClampedArray.idl
+++ b/Source/core/html/canvas/Uint8ClampedArray.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     ConstructorTemplate=TypedArray,
     CustomToV8,
     DoNotCheckConstants
diff --git a/Source/core/html/canvas/WebGLBuffer.cpp b/Source/core/html/canvas/WebGLBuffer.cpp
index aac8a47..1a949c5 100644
--- a/Source/core/html/canvas/WebGLBuffer.cpp
+++ b/Source/core/html/canvas/WebGLBuffer.cpp
@@ -28,7 +28,6 @@
 #include "core/html/canvas/WebGLBuffer.h"
 
 #include "core/html/canvas/WebGLRenderingContext.h"
-#include <wtf/ArrayBufferView.h>
 
 namespace WebCore {
 
diff --git a/Source/core/html/canvas/WebGLBuffer.h b/Source/core/html/canvas/WebGLBuffer.h
index 4c7a470..5a7fa22 100644
--- a/Source/core/html/canvas/WebGLBuffer.h
+++ b/Source/core/html/canvas/WebGLBuffer.h
@@ -28,10 +28,8 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/html/canvas/WebGLSharedObject.h"
-#include "wtf/ArrayBuffer.h"
 #include "wtf/Forward.h"
 #include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/canvas/WebGLCompressedTextureATC.h b/Source/core/html/canvas/WebGLCompressedTextureATC.h
index 6cf6541..4984696 100644
--- a/Source/core/html/canvas/WebGLCompressedTextureATC.h
+++ b/Source/core/html/canvas/WebGLCompressedTextureATC.h
@@ -27,7 +27,6 @@
 #define WebGLCompressedTextureATC_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/ExceptionCode.h"
 #include "core/html/canvas/WebGLExtension.h"
 #include "wtf/PassRefPtr.h"
 
diff --git a/Source/core/html/canvas/WebGLCompressedTextureS3TC.cpp b/Source/core/html/canvas/WebGLCompressedTextureS3TC.cpp
index 287127e..46689f5 100644
--- a/Source/core/html/canvas/WebGLCompressedTextureS3TC.cpp
+++ b/Source/core/html/canvas/WebGLCompressedTextureS3TC.cpp
@@ -30,9 +30,6 @@
 #include "core/html/canvas/WebGLRenderingContext.h"
 #include "core/platform/graphics/Extensions3D.h"
 
-#include <wtf/Int32Array.h>
-#include <wtf/OwnArrayPtr.h>
-
 namespace WebCore {
 
 WebGLCompressedTextureS3TC::WebGLCompressedTextureS3TC(WebGLRenderingContext* context)
diff --git a/Source/core/html/canvas/WebGLCompressedTextureS3TC.h b/Source/core/html/canvas/WebGLCompressedTextureS3TC.h
index b8816be..5b8c1d0 100644
--- a/Source/core/html/canvas/WebGLCompressedTextureS3TC.h
+++ b/Source/core/html/canvas/WebGLCompressedTextureS3TC.h
@@ -27,7 +27,6 @@
 #define WebGLCompressedTextureS3TC_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/ExceptionCode.h"
 #include "core/html/canvas/WebGLExtension.h"
 #include "wtf/PassRefPtr.h"
 
diff --git a/Source/core/html/canvas/WebGLContextGroup.cpp b/Source/core/html/canvas/WebGLContextGroup.cpp
index 0620470..46650a6 100644
--- a/Source/core/html/canvas/WebGLContextGroup.cpp
+++ b/Source/core/html/canvas/WebGLContextGroup.cpp
@@ -88,10 +88,12 @@
 
 void WebGLContextGroup::loseContextGroup(WebGLRenderingContext::LostContextMode mode)
 {
+    // Detach must happen before loseContextImpl, which destroys the GraphicsContext3D
+    // and prevents groupObjects from being properly deleted.
+    detachAndRemoveAllObjects();
+
     for (HashSet<WebGLRenderingContext*>::iterator it = m_contexts.begin(); it != m_contexts.end(); ++it)
         (*it)->loseContextImpl(mode);
-
-    detachAndRemoveAllObjects();
 }
 
 } // namespace WebCore
diff --git a/Source/core/html/canvas/WebGLContextObject.h b/Source/core/html/canvas/WebGLContextObject.h
index b894008..1e4d296 100644
--- a/Source/core/html/canvas/WebGLContextObject.h
+++ b/Source/core/html/canvas/WebGLContextObject.h
@@ -27,7 +27,6 @@
 #define WebGLContextObject_h
 
 #include "core/html/canvas/WebGLObject.h"
-#include "core/platform/graphics/GraphicsContext3D.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/canvas/WebGLDebugShaders.cpp b/Source/core/html/canvas/WebGLDebugShaders.cpp
index ea33aa2..2448230 100644
--- a/Source/core/html/canvas/WebGLDebugShaders.cpp
+++ b/Source/core/html/canvas/WebGLDebugShaders.cpp
@@ -31,8 +31,6 @@
 #include "core/html/canvas/WebGLShader.h"
 #include "core/platform/graphics/Extensions3D.h"
 
-#include <wtf/OwnArrayPtr.h>
-
 namespace WebCore {
 
 WebGLDebugShaders::WebGLDebugShaders(WebGLRenderingContext* context)
diff --git a/Source/core/html/canvas/WebGLObject.h b/Source/core/html/canvas/WebGLObject.h
index a3a9f86..fdadfe2 100644
--- a/Source/core/html/canvas/WebGLObject.h
+++ b/Source/core/html/canvas/WebGLObject.h
@@ -28,8 +28,7 @@
 
 #include "core/platform/graphics/GraphicsContext3D.h"
 
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/canvas/WebGLProgram.cpp b/Source/core/html/canvas/WebGLProgram.cpp
index 5581744..4f2f23b 100644
--- a/Source/core/html/canvas/WebGLProgram.cpp
+++ b/Source/core/html/canvas/WebGLProgram.cpp
@@ -168,7 +168,7 @@
     for (int i = 0; i < numAttribs; ++i) {
         ActiveInfo info;
         context3d->getActiveAttrib(object(), i, info);
-        m_activeAttribLocations[i] = context3d->getAttribLocation(object(), info.name.charactersWithNullTermination());
+        m_activeAttribLocations[i] = context3d->getAttribLocation(object(), info.name);
     }
 }
 
diff --git a/Source/core/html/canvas/WebGLProgram.h b/Source/core/html/canvas/WebGLProgram.h
index 7356cac..63a976c 100644
--- a/Source/core/html/canvas/WebGLProgram.h
+++ b/Source/core/html/canvas/WebGLProgram.h
@@ -30,7 +30,6 @@
 #include "core/html/canvas/WebGLSharedObject.h"
 #include "core/html/canvas/WebGLShader.h"
 #include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
diff --git a/Source/core/html/canvas/WebGLRenderbuffer.h b/Source/core/html/canvas/WebGLRenderbuffer.h
index b353004..93bcc17 100644
--- a/Source/core/html/canvas/WebGLRenderbuffer.h
+++ b/Source/core/html/canvas/WebGLRenderbuffer.h
@@ -29,7 +29,6 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/html/canvas/WebGLSharedObject.h"
 #include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/canvas/WebGLRenderingContext.cpp b/Source/core/html/canvas/WebGLRenderingContext.cpp
index f6071a6..1faa49d 100644
--- a/Source/core/html/canvas/WebGLRenderingContext.cpp
+++ b/Source/core/html/canvas/WebGLRenderingContext.cpp
@@ -77,11 +77,10 @@
 #include "core/platform/graphics/gpu/DrawingBuffer.h"
 #include "core/rendering/RenderBox.h"
 
-#include <wtf/OwnArrayPtr.h>
-#include <wtf/PassOwnArrayPtr.h>
-#include <wtf/text/StringBuilder.h>
-#include <wtf/Uint16Array.h>
-#include <wtf/Uint32Array.h>
+#include "wtf/OwnArrayPtr.h"
+#include "wtf/PassOwnArrayPtr.h"
+#include "wtf/Uint32Array.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
@@ -743,9 +742,12 @@
     for (size_t i = 0; i < m_extensions.size(); ++i)
         delete m_extensions[i];
 
-    destroyGraphicsContext3D();
+    // Context must be removed from the group prior to the destruction of the
+    // GraphicsContext3D, otherwise shared objects may not be properly deleted.
     m_contextGroup->removeContext(this);
 
+    destroyGraphicsContext3D();
+
     if (m_multisamplingObserverRegistered) {
         Page* page = canvas()->document()->page();
         if (page)
@@ -1658,8 +1660,11 @@
     if (!deleteObject(texture))
         return;
     for (size_t i = 0; i < m_textureUnits.size(); ++i) {
-        if (texture == m_textureUnits[i].m_texture2DBinding)
+        if (texture == m_textureUnits[i].m_texture2DBinding) {
             m_textureUnits[i].m_texture2DBinding = 0;
+            if (!i)
+                m_drawingBuffer->setTexture2DBinding(0);
+        }
         if (texture == m_textureUnits[i].m_textureCubeMapBinding)
             m_textureUnits[i].m_textureCubeMapBinding = 0;
     }
diff --git a/Source/core/html/canvas/WebGLRenderingContext.h b/Source/core/html/canvas/WebGLRenderingContext.h
index 358b94b..e260a29 100644
--- a/Source/core/html/canvas/WebGLRenderingContext.h
+++ b/Source/core/html/canvas/WebGLRenderingContext.h
@@ -34,11 +34,10 @@
 #include "core/platform/graphics/GraphicsContext3D.h"
 #include "core/platform/graphics/ImageBuffer.h"
 
-#include <wtf/Float32Array.h>
-#include <wtf/Int32Array.h>
-#include <wtf/OwnArrayPtr.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Uint8Array.h>
+#include "wtf/Float32Array.h"
+#include "wtf/Int32Array.h"
+#include "wtf/OwnArrayPtr.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebKit { class WebLayer; }
 
diff --git a/Source/core/html/canvas/WebGLShader.h b/Source/core/html/canvas/WebGLShader.h
index fbeaac7..65f540a 100644
--- a/Source/core/html/canvas/WebGLShader.h
+++ b/Source/core/html/canvas/WebGLShader.h
@@ -29,7 +29,6 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/html/canvas/WebGLSharedObject.h"
 #include "wtf/PassRefPtr.h"
-#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/canvas/WebGLTexture.h b/Source/core/html/canvas/WebGLTexture.h
index 9b79082..5dd35c5 100644
--- a/Source/core/html/canvas/WebGLTexture.h
+++ b/Source/core/html/canvas/WebGLTexture.h
@@ -28,9 +28,8 @@
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/html/canvas/WebGLSharedObject.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/Vector.h>
+#include "wtf/PassRefPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/canvas/WebGLUniformLocation.h b/Source/core/html/canvas/WebGLUniformLocation.h
index 142a73b..d61aec7 100644
--- a/Source/core/html/canvas/WebGLUniformLocation.h
+++ b/Source/core/html/canvas/WebGLUniformLocation.h
@@ -28,7 +28,6 @@
 #define WebGLUniformLocation_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "core/html/canvas/WebGLObject.h"
 #include "core/html/canvas/WebGLProgram.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
diff --git a/Source/core/html/canvas/WebGLVertexArrayObjectOES.h b/Source/core/html/canvas/WebGLVertexArrayObjectOES.h
index 9bbc585..f1cdda2 100644
--- a/Source/core/html/canvas/WebGLVertexArrayObjectOES.h
+++ b/Source/core/html/canvas/WebGLVertexArrayObjectOES.h
@@ -29,8 +29,7 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/html/canvas/WebGLBuffer.h"
 #include "core/html/canvas/WebGLContextObject.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/ime/InputMethodContext.cpp b/Source/core/html/ime/InputMethodContext.cpp
index 6723fbb..537fa03 100644
--- a/Source/core/html/ime/InputMethodContext.cpp
+++ b/Source/core/html/ime/InputMethodContext.cpp
@@ -31,7 +31,11 @@
 #include "config.h"
 #include "core/html/ime/InputMethodContext.h"
 
+#include "core/editing/Editor.h"
 #include "core/html/ime/Composition.h"
+#include "core/page/EditorClient.h"
+#include "core/page/Frame.h"
+#include "core/page/Page.h"
 
 namespace WebCore {
 
@@ -80,7 +84,30 @@
 
 void InputMethodContext::confirmComposition()
 {
-    // FIXME: Implement this.
+    Frame* frame = m_element->document()->frame();
+    if (!frame)
+        return;
+    Editor* editor = frame->editor();
+    if (!editor->hasComposition())
+        return;
+
+    const Node* node = frame->document()->focusedNode();
+    if (!node || !node->isHTMLElement() || m_element != toHTMLElement(node))
+        return;
+
+    // We should verify the parent node of this IME composition node are
+    // editable because JavaScript may delete a parent node of the composition
+    // node. In this case, WebKit crashes while deleting texts from the parent
+    // node, which doesn't exist any longer.
+    RefPtr<Range> range = editor->compositionRange();
+    if (range) {
+        Node* node = range->startContainer();
+        if (!node || !node->isContentEditable())
+            return;
+    }
+
+    // This resets input method and the composition string is committed.
+    editor->client()->willSetInputMethodState();
 }
 
 void InputMethodContext::setCaretRectangle(Node* anchor, int x, int y, int w, int h)
diff --git a/Source/core/html/parser/BackgroundHTMLParser.cpp b/Source/core/html/parser/BackgroundHTMLParser.cpp
index 942725a..23747ed 100644
--- a/Source/core/html/parser/BackgroundHTMLParser.cpp
+++ b/Source/core/html/parser/BackgroundHTMLParser.cpp
@@ -27,12 +27,11 @@
 #include "core/html/parser/BackgroundHTMLParser.h"
 
 #include "core/html/parser/HTMLDocumentParser.h"
-#include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/parser/HTMLParserThread.h"
 #include "core/html/parser/HTMLTokenizer.h"
 #include "core/html/parser/XSSAuditor.h"
-#include <wtf/MainThread.h>
-#include <wtf/text/TextPosition.h>
+#include "wtf/MainThread.h"
+#include "wtf/text/TextPosition.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/parser/BackgroundHTMLParser.h b/Source/core/html/parser/BackgroundHTMLParser.h
index 14a0df5..b9b5a51 100644
--- a/Source/core/html/parser/BackgroundHTMLParser.h
+++ b/Source/core/html/parser/BackgroundHTMLParser.h
@@ -35,10 +35,8 @@
 #include "core/html/parser/HTMLTokenizer.h"
 #include "core/html/parser/HTMLTreeBuilderSimulator.h"
 #include "core/html/parser/XSSAuditorDelegate.h"
-#include <wtf/PassOwnPtr.h>
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
-#include <wtf/WeakPtr.h>
+#include "wtf/PassOwnPtr.h"
+#include "wtf/WeakPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/parser/CSSPreloadScanner.cpp b/Source/core/html/parser/CSSPreloadScanner.cpp
index ff31acf..c2711e8 100644
--- a/Source/core/html/parser/CSSPreloadScanner.cpp
+++ b/Source/core/html/parser/CSSPreloadScanner.cpp
@@ -30,7 +30,6 @@
 
 #include "core/html/parser/HTMLIdentifier.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/loader/cache/CachedResourceRequestInitiators.h"
 #include "core/platform/text/SegmentedString.h"
 
 namespace WebCore {
diff --git a/Source/core/html/parser/HTMLConstructionSite.cpp b/Source/core/html/parser/HTMLConstructionSite.cpp
index 96d3025..e6566a3 100644
--- a/Source/core/html/parser/HTMLConstructionSite.cpp
+++ b/Source/core/html/parser/HTMLConstructionSite.cpp
@@ -34,24 +34,18 @@
 #include "core/dom/DocumentType.h"
 #include "core/dom/Element.h"
 #include "core/dom/Text.h"
-#include "core/html/HTMLDocument.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLHtmlElement.h"
-#include "core/html/HTMLPlugInElement.h"
 #include "core/html/HTMLScriptElement.h"
 #include "core/html/HTMLTemplateElement.h"
 #include "core/html/parser/AtomicHTMLToken.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/parser/HTMLStackItem.h"
 #include "core/html/parser/HTMLToken.h"
-#include "core/html/parser/HTMLTokenizer.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/page/Frame.h"
-#include "core/page/Settings.h"
-#include "core/platform/LocalizedStrings.h"
 #include "core/platform/NotImplemented.h"
-#include "wtf/UnusedParam.h"
 #include <limits>
 
 namespace WebCore {
@@ -645,10 +639,14 @@
 PassRefPtr<Element> HTMLConstructionSite::createHTMLElement(AtomicHTMLToken* token)
 {
     QualifiedName tagName(nullAtom, token->name(), xhtmlNamespaceURI);
+    Document* document = ownerDocumentForCurrentNode();
+    // Only associate the element with the current form if we're creating the new element
+    // in a document with a browsing context (rather than in <template> contents).
+    HTMLFormElement* form = document->frame() ? m_form.get() : 0;
     // FIXME: This can't use HTMLConstructionSite::createElement because we
     // have to pass the current form element.  We should rework form association
     // to occur after construction to allow better code sharing here.
-    RefPtr<Element> element = HTMLElementFactory::createHTMLElement(tagName, ownerDocumentForCurrentNode(), form(), true);
+    RefPtr<Element> element = HTMLElementFactory::createHTMLElement(tagName, document, form, true);
     setAttributes(element.get(), token, m_parserContentPolicy);
     ASSERT(element->isHTMLElement());
     return element.release();
diff --git a/Source/core/html/parser/HTMLConstructionSite.h b/Source/core/html/parser/HTMLConstructionSite.h
index fb2e5e7..d24d489 100644
--- a/Source/core/html/parser/HTMLConstructionSite.h
+++ b/Source/core/html/parser/HTMLConstructionSite.h
@@ -27,14 +27,13 @@
 #ifndef HTMLConstructionSite_h
 #define HTMLConstructionSite_h
 
-#include "core/dom/FragmentScriptingPermission.h"
+#include "core/dom/ParserContentPolicy.h"
 #include "core/html/parser/HTMLElementStack.h"
 #include "core/html/parser/HTMLFormattingElementList.h"
-#include "core/platform/NotImplemented.h"
-#include <wtf/Noncopyable.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/Noncopyable.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/parser/HTMLDocumentParser.cpp b/Source/core/html/parser/HTMLDocumentParser.cpp
index 6961e26..e47d69c 100644
--- a/Source/core/html/parser/HTMLDocumentParser.cpp
+++ b/Source/core/html/parser/HTMLDocumentParser.cpp
@@ -29,7 +29,6 @@
 #include "HTMLNames.h"
 #include "core/dom/DocumentFragment.h"
 #include "core/dom/Element.h"
-#include "core/html/HTMLDocument.h"
 #include "core/html/parser/AtomicHTMLToken.h"
 #include "core/html/parser/BackgroundHTMLParser.h"
 #include "core/html/parser/CompactHTMLToken.h"
@@ -42,7 +41,7 @@
 #include "core/html/parser/HTMLTreeBuilder.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/Frame.h"
-#include <wtf/Functional.h>
+#include "wtf/Functional.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/parser/HTMLDocumentParser.h b/Source/core/html/parser/HTMLDocumentParser.h
index f32a3bb..a6c2349 100644
--- a/Source/core/html/parser/HTMLDocumentParser.h
+++ b/Source/core/html/parser/HTMLDocumentParser.h
@@ -26,7 +26,7 @@
 #ifndef HTMLDocumentParser_h
 #define HTMLDocumentParser_h
 
-#include "core/dom/FragmentScriptingPermission.h"
+#include "core/dom/ParserContentPolicy.h"
 #include "core/dom/ScriptableDocumentParser.h"
 #include "core/html/parser/BackgroundHTMLInputStream.h"
 #include "core/html/parser/CompactHTMLToken.h"
@@ -41,12 +41,11 @@
 #include "core/html/parser/XSSAuditor.h"
 #include "core/html/parser/XSSAuditorDelegate.h"
 #include "core/loader/cache/CachedResourceClient.h"
-#include "core/platform/Timer.h"
 #include "core/platform/text/SegmentedString.h"
-#include <wtf/Deque.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/text/TextPosition.h>
-#include <wtf/WeakPtr.h>
+#include "wtf/Deque.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/WeakPtr.h"
+#include "wtf/text/TextPosition.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/parser/HTMLElementStack.h b/Source/core/html/parser/HTMLElementStack.h
index 1a90a46..d9ad04c 100644
--- a/Source/core/html/parser/HTMLElementStack.h
+++ b/Source/core/html/parser/HTMLElementStack.h
@@ -27,13 +27,12 @@
 #ifndef HTMLElementStack_h
 #define HTMLElementStack_h
 
-#include "HTMLNames.h"
 #include "core/html/parser/HTMLStackItem.h"
-#include <wtf/Forward.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/RefPtr.h>
+#include "wtf/Forward.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/parser/HTMLIdentifier.cpp b/Source/core/html/parser/HTMLIdentifier.cpp
index 41b8ee7..8c5fa52 100644
--- a/Source/core/html/parser/HTMLIdentifier.cpp
+++ b/Source/core/html/parser/HTMLIdentifier.cpp
@@ -100,7 +100,7 @@
         IdentifierTable::AddResult addResult = table.add(hash, name);
         maxNameLength = std::max(maxNameLength, name->length());
         // Ensure we're using the same hashing algorithm to get and set.
-        ASSERT_UNUSED(addResult, !addResult.isNewEntry || HTMLIdentifier::findIfKnown(name->characters(), name->length()) == name);
+        ASSERT_UNUSED(addResult, !addResult.isNewEntry || HTMLIdentifier::findIfKnown(name->bloatedCharacters(), name->length()) == name);
         // We expect some hash collisions, but only for identical strings.
         // Since all of these names are AtomicStrings pointers should be equal.
         // Note: If you hit this ASSERT, then we had a hash collision among
diff --git a/Source/core/html/parser/HTMLParserIdioms.cpp b/Source/core/html/parser/HTMLParserIdioms.cpp
index 5ef401b..6baada9 100644
--- a/Source/core/html/parser/HTMLParserIdioms.cpp
+++ b/Source/core/html/parser/HTMLParserIdioms.cpp
@@ -29,10 +29,9 @@
 #include "core/dom/QualifiedName.h"
 #include "core/html/parser/HTMLIdentifier.h"
 #include "core/platform/Decimal.h"
-#include <wtf/MathExtras.h>
-#include <wtf/text/AtomicString.h>
-#include <wtf/text/StringBuilder.h>
-#include <wtf/text/StringHash.h>
+#include "wtf/MathExtras.h"
+#include "wtf/text/AtomicString.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
@@ -73,7 +72,7 @@
     if (string.is8Bit())
         return stripLeadingAndTrailingHTMLSpaces(string, string.characters8(), length);
 
-    return stripLeadingAndTrailingHTMLSpaces(string, string.characters(), length);
+    return stripLeadingAndTrailingHTMLSpaces(string, string.characters16(), length);
 }
 
 String serializeForNumberType(const Decimal& number)
@@ -208,12 +207,12 @@
     // Step 1
     // Step 2
     unsigned length = input.length();
-    if (length && input.is8Bit()) {
+    if (!length || input.is8Bit()) {
         const LChar* start = input.characters8();
         return parseHTMLIntegerInternal(start, start + length, value);
     }
 
-    const UChar* start = input.characters();
+    const UChar* start = input.characters16();
     return parseHTMLIntegerInternal(start, start + length, value);
 }
 
@@ -274,7 +273,7 @@
         return parseHTMLNonNegativeIntegerInternal(start, start + length, value);
     }
     
-    const UChar* start = input.characters();
+    const UChar* start = input.characters16();
     return parseHTMLNonNegativeIntegerInternal(start, start + length, value);
 }
 
diff --git a/Source/core/html/parser/HTMLParserIdioms.h b/Source/core/html/parser/HTMLParserIdioms.h
index 3c6903e..70db795 100644
--- a/Source/core/html/parser/HTMLParserIdioms.h
+++ b/Source/core/html/parser/HTMLParserIdioms.h
@@ -27,9 +27,8 @@
 
 #include "core/dom/QualifiedName.h"
 #include "core/html/parser/HTMLIdentifier.h"
-#include <wtf/Forward.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/unicode/Unicode.h>
+#include "wtf/Forward.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/parser/HTMLParserScheduler.cpp b/Source/core/html/parser/HTMLParserScheduler.cpp
index 19baf9c..1dbd927 100644
--- a/Source/core/html/parser/HTMLParserScheduler.cpp
+++ b/Source/core/html/parser/HTMLParserScheduler.cpp
@@ -39,8 +39,7 @@
 
 // parserTimeLimit is the seconds the parser will run in one write() call
 // before yielding. Inline <script> execution can cause it to exceed the limit.
-// FIXME: We would like this value to be 0.2.
-const double HTMLParserScheduler::parserTimeLimit = 0.500;
+const double HTMLParserScheduler::parserTimeLimit = 0.2;
 
 ActiveParserSession::ActiveParserSession(Document* document)
     : m_document(document)
diff --git a/Source/core/html/parser/HTMLParserScheduler.h b/Source/core/html/parser/HTMLParserScheduler.h
index 722c284..01624b7 100644
--- a/Source/core/html/parser/HTMLParserScheduler.h
+++ b/Source/core/html/parser/HTMLParserScheduler.h
@@ -26,12 +26,11 @@
 #ifndef HTMLParserScheduler_h
 #define HTMLParserScheduler_h
 
-#include <limits.h>
 #include "core/html/parser/NestingLevelIncrementer.h"
 #include "core/platform/Timer.h"
-#include <wtf/CurrentTime.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/RefPtr.h>
+#include "wtf/CurrentTime.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/parser/HTMLPreloadScanner.cpp b/Source/core/html/parser/HTMLPreloadScanner.cpp
index 1b19991..c48575a 100644
--- a/Source/core/html/parser/HTMLPreloadScanner.cpp
+++ b/Source/core/html/parser/HTMLPreloadScanner.cpp
@@ -33,8 +33,7 @@
 #include "core/html/LinkRelAttribute.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/html/parser/HTMLTokenizer.h"
-#include <wtf/Functional.h>
-#include <wtf/MainThread.h>
+#include "wtf/MainThread.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/parser/HTMLScriptRunner.cpp b/Source/core/html/parser/HTMLScriptRunner.cpp
index d5ca07c..0429e96 100644
--- a/Source/core/html/parser/HTMLScriptRunner.cpp
+++ b/Source/core/html/parser/HTMLScriptRunner.cpp
@@ -27,11 +27,10 @@
 #include "core/html/parser/HTMLScriptRunner.h"
 
 #include "bindings/v8/ScriptSourceCode.h"
-#include "core/dom/CustomElementRegistry.h"
 #include "core/dom/Element.h"
 #include "core/dom/Event.h"
 #include "core/dom/IgnoreDestructiveWriteCountIncrementer.h"
-#include "core/dom/MutationObserver.h"
+#include "core/dom/Microtask.h"
 #include "core/dom/ScriptElement.h"
 #include "core/html/parser/HTMLInputStream.h"
 #include "core/html/parser/HTMLScriptRunnerHost.h"
@@ -126,10 +125,8 @@
     if (pendingScript.cachedScript() && pendingScript.watchingForLoad())
         stopWatchingForLoad(pendingScript);
 
-    if (!isExecutingScript()) {
-        CustomElementRegistry::deliverAllLifecycleCallbacks();
-        MutationObserver::deliverAllMutations();
-    }
+    if (!isExecutingScript())
+        Microtask::performCheckpoint();
 
     // Clear the pending script before possible rentrancy from executeScript()
     RefPtr<Element> element = pendingScript.releaseElementAndClear();
@@ -292,10 +289,8 @@
         // every script element, even if it's not ready to execute yet. There's
         // unfortuantely no obvious way to tell if prepareScript is going to
         // execute the script from out here.
-        if (!isExecutingScript()) {
-            CustomElementRegistry::deliverAllLifecycleCallbacks();
-            MutationObserver::deliverAllMutations();
-        }
+        if (!isExecutingScript())
+            Microtask::performCheckpoint();
 
         InsertionPointRecord insertionPointRecord(m_host->inputStream());
         NestingLevelIncrementer nestingLevelIncrementer(m_scriptNestingLevel);
diff --git a/Source/core/html/parser/HTMLSourceTracker.h b/Source/core/html/parser/HTMLSourceTracker.h
index 79b4aca..63fec2b 100644
--- a/Source/core/html/parser/HTMLSourceTracker.h
+++ b/Source/core/html/parser/HTMLSourceTracker.h
@@ -28,7 +28,6 @@
 
 #include "core/html/parser/HTMLToken.h"
 #include "core/platform/text/SegmentedString.h"
-#include <wtf/text/StringBuilder.h>
 
 namespace WebCore {
 
diff --git a/Source/core/html/parser/HTMLTokenizer.cpp b/Source/core/html/parser/HTMLTokenizer.cpp
index 5775af9..cc75625 100644
--- a/Source/core/html/parser/HTMLTokenizer.cpp
+++ b/Source/core/html/parser/HTMLTokenizer.cpp
@@ -34,12 +34,9 @@
 #include "core/html/parser/HTMLTreeBuilder.h"
 #include "core/platform/NotImplemented.h"
 #include "core/xml/parser/MarkupTokenizerInlines.h"
-#include <wtf/ASCIICType.h>
-#include <wtf/CurrentTime.h>
-#include <wtf/text/AtomicString.h>
-#include <wtf/text/CString.h>
-#include <wtf/unicode/Unicode.h>
-#include <wtf/UnusedParam.h>
+#include "wtf/ASCIICType.h"
+#include "wtf/text/AtomicString.h"
+#include "wtf/unicode/Unicode.h"
 
 using namespace WTF;
 
diff --git a/Source/core/html/parser/HTMLTreeBuilder.cpp b/Source/core/html/parser/HTMLTreeBuilder.cpp
index 764afdc..2f3e37e 100644
--- a/Source/core/html/parser/HTMLTreeBuilder.cpp
+++ b/Source/core/html/parser/HTMLTreeBuilder.cpp
@@ -34,7 +34,6 @@
 #include "XMLNSNames.h"
 #include "XMLNames.h"
 #include "core/dom/DocumentFragment.h"
-#include "core/html/HTMLDocument.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/parser/AtomicHTMLToken.h"
 #include "core/html/parser/HTMLDocumentParser.h"
@@ -44,8 +43,8 @@
 #include "core/html/parser/HTMLTokenizer.h"
 #include "core/platform/LocalizedStrings.h"
 #include "core/platform/NotImplemented.h"
-#include <wtf/MainThread.h>
-#include <wtf/unicode/CharacterNames.h>
+#include "wtf/MainThread.h"
+#include "wtf/unicode/CharacterNames.h"
 
 namespace WebCore {
 
@@ -137,7 +136,7 @@
     ASSERT(isMainThread());
     while (element) {
         if (element->hasTagName(formTag))
-            return static_cast<HTMLFormElement*>(element);
+            return toHTMLFormElement(element);
         ContainerNode* parent = element->parentNode();
         if (!parent || !parent->isElementNode())
             return 0;
diff --git a/Source/core/html/parser/HTMLTreeBuilder.h b/Source/core/html/parser/HTMLTreeBuilder.h
index d5fdd86..ae4fbc5 100644
--- a/Source/core/html/parser/HTMLTreeBuilder.h
+++ b/Source/core/html/parser/HTMLTreeBuilder.h
@@ -30,14 +30,13 @@
 #include "core/html/parser/HTMLConstructionSite.h"
 #include "core/html/parser/HTMLElementStack.h"
 #include "core/html/parser/HTMLParserOptions.h"
-#include <wtf/Noncopyable.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/StringBuilder.h>
-#include <wtf/text/TextPosition.h>
-#include <wtf/unicode/Unicode.h>
-#include <wtf/Vector.h>
+#include "wtf/Noncopyable.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/text/StringBuilder.h"
+#include "wtf/text/TextPosition.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/parser/HTMLTreeBuilderSimulator.h b/Source/core/html/parser/HTMLTreeBuilderSimulator.h
index 4b73eb5..a09eb99 100644
--- a/Source/core/html/parser/HTMLTreeBuilderSimulator.h
+++ b/Source/core/html/parser/HTMLTreeBuilderSimulator.h
@@ -27,8 +27,7 @@
 #define HTMLTreeBuilderSimulator_h
 
 #include "core/html/parser/HTMLParserOptions.h"
-#include <wtf/PassOwnPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/parser/XSSAuditor.cpp b/Source/core/html/parser/XSSAuditor.cpp
index ec7983c..a92133c 100644
--- a/Source/core/html/parser/XSSAuditor.cpp
+++ b/Source/core/html/parser/XSSAuditor.cpp
@@ -31,30 +31,20 @@
 #include "SVGNames.h"
 #include "XLinkNames.h"
 #include "core/dom/Document.h"
-#include "core/html/FormDataList.h"
 #include "core/html/HTMLParamElement.h"
 #include "core/html/parser/HTMLDocumentParser.h"
 #include "core/html/parser/HTMLParserIdioms.h"
-#include "core/html/parser/HTMLTokenizer.h"
 #include "core/html/parser/XSSAuditorDelegate.h"
-#include "core/inspector/InspectorInstrumentation.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/loader/DocumentLoader.h"
-#include "core/loader/FrameLoaderClient.h"
-#include "core/loader/PingLoader.h"
 #include "core/loader/TextResourceDecoder.h"
-#include "core/page/Console.h"
 #include "core/page/ContentSecurityPolicy.h"
-#include "core/page/DOMWindow.h"
 #include "core/page/Frame.h"
 #include "core/page/Settings.h"
+#include "core/platform/JSONValues.h"
 #include "core/platform/network/FormData.h"
 #include "core/platform/text/DecodeEscapeSequences.h"
 #include "weborigin/KURL.h"
-#include "weborigin/SecurityOrigin.h"
-#include "wtf/Functional.h"
 #include "wtf/MainThread.h"
-#include "wtf/text/CString.h"
 #include "wtf/text/TextEncoding.h"
 
 namespace WebCore {
diff --git a/Source/core/html/parser/XSSAuditorDelegate.cpp b/Source/core/html/parser/XSSAuditorDelegate.cpp
index a9e7b25..bc435c5 100644
--- a/Source/core/html/parser/XSSAuditorDelegate.cpp
+++ b/Source/core/html/parser/XSSAuditorDelegate.cpp
@@ -26,16 +26,16 @@
 #include "config.h"
 #include "core/html/parser/XSSAuditorDelegate.h"
 
-#include <wtf/text/StringBuilder.h>
 #include "core/dom/Document.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/loader/PingLoader.h"
 #include "core/page/Frame.h"
+#include "core/platform/JSONValues.h"
 #include "core/platform/network/FormData.h"
 #include "weborigin/SecurityOrigin.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
@@ -79,11 +79,11 @@
             httpBody = formData->flattenToString();
     }
 
-    RefPtr<InspectorObject> reportDetails = InspectorObject::create();
+    RefPtr<JSONObject> reportDetails = JSONObject::create();
     reportDetails->setString("request-url", m_document->url().string());
     reportDetails->setString("request-body", httpBody);
 
-    RefPtr<InspectorObject> reportObject = InspectorObject::create();
+    RefPtr<JSONObject> reportObject = JSONObject::create();
     reportObject->setObject("xss-report", reportDetails.release());
 
     return FormData::create(reportObject->toJSONString().utf8().data());
diff --git a/Source/core/html/parser/XSSAuditorDelegate.h b/Source/core/html/parser/XSSAuditorDelegate.h
index 1ee8dd5..896ef26 100644
--- a/Source/core/html/parser/XSSAuditorDelegate.h
+++ b/Source/core/html/parser/XSSAuditorDelegate.h
@@ -31,7 +31,6 @@
 #include "wtf/PassOwnPtr.h"
 #include "wtf/Vector.h"
 #include "wtf/text/TextPosition.h"
-#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/shadow/ClearButtonElement.cpp b/Source/core/html/shadow/ClearButtonElement.cpp
index 58acf52..3ac4628 100644
--- a/Source/core/html/shadow/ClearButtonElement.cpp
+++ b/Source/core/html/shadow/ClearButtonElement.cpp
@@ -85,7 +85,7 @@
         return;
     }
 
-    if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && static_cast<MouseEvent*>(event)->button() == LeftButton) {
+    if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (renderer() && renderer()->visibleToHitTesting()) {
             if (Frame* frame = document()->frame()) {
                 frame->eventHandler()->setCapturingMouseEventsNode(this);
@@ -95,7 +95,7 @@
         m_clearButtonOwner->focusAndSelectClearButtonOwner();
         event->setDefaultHandled();
     }
-    if (event->type() == eventNames().mouseupEvent && event->isMouseEvent() && static_cast<MouseEvent*>(event)->button() == LeftButton) {
+    if (event->type() == eventNames().mouseupEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (m_capturing) {
             if (Frame* frame = document()->frame()) {
                 frame->eventHandler()->setCapturingMouseEventsNode(0);
diff --git a/Source/core/html/shadow/DateTimeEditElement.cpp b/Source/core/html/shadow/DateTimeEditElement.cpp
index 07b774d..6194d2c 100644
--- a/Source/core/html/shadow/DateTimeEditElement.cpp
+++ b/Source/core/html/shadow/DateTimeEditElement.cpp
@@ -28,22 +28,18 @@
 #include "core/html/shadow/DateTimeEditElement.h"
 
 #include "HTMLNames.h"
-#include "core/dom/KeyboardEvent.h"
 #include "core/dom/MouseEvent.h"
 #include "core/dom/Text.h"
 #include "core/html/DateTimeFieldsState.h"
 #include "core/html/shadow/DateTimeFieldElements.h"
-#include "core/html/shadow/DateTimeSymbolicFieldElement.h"
 #include "core/html/shadow/ShadowElementNames.h"
-#include "core/page/EventHandler.h"
 #include "core/platform/DateComponents.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/text/DateTimeFormat.h"
 #include "core/platform/text/PlatformLocale.h"
 #include "core/rendering/style/RenderStyle.h"
 #include "core/rendering/style/StyleInheritedData.h"
-#include <wtf/DateMath.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/DateMath.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/shadow/DateTimeFieldElement.cpp b/Source/core/html/shadow/DateTimeFieldElement.cpp
index db8f421..a53010a 100644
--- a/Source/core/html/shadow/DateTimeFieldElement.cpp
+++ b/Source/core/html/shadow/DateTimeFieldElement.cpp
@@ -57,7 +57,7 @@
         didFocus();
 
     if (event->isKeyboardEvent()) {
-        KeyboardEvent* keyboardEvent = static_cast<KeyboardEvent*>(event);
+        KeyboardEvent* keyboardEvent = toKeyboardEvent(event);
         if (!isDisabled() && !isFieldOwnerDisabled() && !isFieldOwnerReadOnly()) {
             handleKeyboardEvent(keyboardEvent);
             if (keyboardEvent->defaultHandled())
diff --git a/Source/core/html/shadow/DetailsMarkerControl.cpp b/Source/core/html/shadow/DetailsMarkerControl.cpp
index 84fa604..3d139df 100644
--- a/Source/core/html/shadow/DetailsMarkerControl.cpp
+++ b/Source/core/html/shadow/DetailsMarkerControl.cpp
@@ -44,9 +44,9 @@
 {
 }
 
-RenderObject* DetailsMarkerControl::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* DetailsMarkerControl::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderDetailsMarker(this);
+    return new (document()->renderArena()) RenderDetailsMarker(this);
 }
 
 bool DetailsMarkerControl::rendererIsNeeded(const NodeRenderingContext& context)
diff --git a/Source/core/html/shadow/DetailsMarkerControl.h b/Source/core/html/shadow/DetailsMarkerControl.h
index 9cd6e66..168491f 100644
--- a/Source/core/html/shadow/DetailsMarkerControl.h
+++ b/Source/core/html/shadow/DetailsMarkerControl.h
@@ -44,7 +44,7 @@
     static PassRefPtr<DetailsMarkerControl> create(Document*);
 
 private:
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool rendererIsNeeded(const NodeRenderingContext&);
 
     HTMLSummaryElement* summaryElement();
diff --git a/Source/core/html/shadow/HTMLContentElement.cpp b/Source/core/html/shadow/HTMLContentElement.cpp
index 514855d..79d4f95 100644
--- a/Source/core/html/shadow/HTMLContentElement.cpp
+++ b/Source/core/html/shadow/HTMLContentElement.cpp
@@ -31,7 +31,6 @@
 #include "core/css/CSSParser.h"
 #include "core/dom/QualifiedName.h"
 #include "core/dom/shadow/ShadowRoot.h"
-#include <wtf/StdLibExtras.h>
 
 namespace WebCore {
 
diff --git a/Source/core/html/shadow/HTMLContentElement.h b/Source/core/html/shadow/HTMLContentElement.h
index 6f30076..a7864a2 100644
--- a/Source/core/html/shadow/HTMLContentElement.h
+++ b/Source/core/html/shadow/HTMLContentElement.h
@@ -33,7 +33,6 @@
 
 #include "core/css/CSSSelectorList.h"
 #include "core/dom/shadow/InsertionPoint.h"
-#include <wtf/Forward.h>
 
 namespace WebCore {
 
diff --git a/Source/core/html/shadow/HTMLShadowElement.cpp b/Source/core/html/shadow/HTMLShadowElement.cpp
index 3c69757..71f8ef0 100644
--- a/Source/core/html/shadow/HTMLShadowElement.cpp
+++ b/Source/core/html/shadow/HTMLShadowElement.cpp
@@ -33,7 +33,6 @@
 
 #include "HTMLNames.h"
 #include "core/dom/shadow/ShadowRoot.h"
-#include <wtf/text/AtomicString.h>
 
 namespace WebCore {
 
diff --git a/Source/core/html/shadow/MediaControlElementTypes.cpp b/Source/core/html/shadow/MediaControlElementTypes.cpp
index bd2f257..c012642 100644
--- a/Source/core/html/shadow/MediaControlElementTypes.cpp
+++ b/Source/core/html/shadow/MediaControlElementTypes.cpp
@@ -167,7 +167,7 @@
 void MediaControlVolumeSliderElement::defaultEventHandler(Event* event)
 {
     // Left button is 0. Rejects mouse events not from left button.
-    if (event->isMouseEvent() && static_cast<MouseEvent*>(event)->button())
+    if (event->isMouseEvent() && toMouseEvent(event)->button())
         return;
 
     if (!attached())
diff --git a/Source/core/html/shadow/MediaControlElements.cpp b/Source/core/html/shadow/MediaControlElements.cpp
index 243144a..8e22f60 100644
--- a/Source/core/html/shadow/MediaControlElements.cpp
+++ b/Source/core/html/shadow/MediaControlElements.cpp
@@ -32,7 +32,6 @@
 #include "core/html/shadow/MediaControlElements.h"
 
 #include "core/dom/EventNames.h"
-#include "core/dom/EventTarget.h"
 #include "core/dom/ExceptionCodePlaceholder.h"
 #include "core/dom/FullscreenController.h"
 #include "core/dom/MouseEvent.h"
@@ -40,21 +39,14 @@
 #include "core/html/HTMLVideoElement.h"
 #include "core/html/shadow/MediaControls.h"
 #include "core/html/track/TextTrack.h"
-#include "core/html/track/TextTrackList.h"
-#include "core/html/track/TextTrackRegionList.h"
 #include "core/page/EventHandler.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
-#include "core/page/PageGroup.h"
 #include "core/page/Settings.h"
-#include "core/platform/LocalizedStrings.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderMediaControlElements.h"
 #include "core/rendering/RenderSlider.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderVideo.h"
-#include "core/rendering/RenderView.h"
 
 namespace WebCore {
 
@@ -224,7 +216,7 @@
     MediaControlDivElement::defaultEventHandler(event);
 
     if (event->isMouseEvent()) {
-        LayoutPoint location = static_cast<MouseEvent*>(event)->absoluteLocation();
+        LayoutPoint location = toMouseEvent(event)->absoluteLocation();
         if (event->type() == eventNames().mousedownEvent && event->target() == this) {
             startDrag(location);
             event->setDefaultHandled();
@@ -490,7 +482,7 @@
 void MediaControlTimelineElement::defaultEventHandler(Event* event)
 {
     // Left button is 0. Rejects mouse events not from left button.
-    if (event->isMouseEvent() && static_cast<MouseEvent*>(event)->button())
+    if (event->isMouseEvent() && toMouseEvent(event)->button())
         return;
 
     if (!attached())
@@ -672,9 +664,9 @@
     return element.release();
 }
 
-RenderObject* MediaControlTextTrackContainerElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* MediaControlTextTrackContainerElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderTextTrackContainerElement(this);
+    return new (document()->renderArena()) RenderTextTrackContainerElement(this);
 }
 
 const AtomicString& MediaControlTextTrackContainerElement::textTrackContainerElementShadowPseudoId()
@@ -757,7 +749,7 @@
             // WebVTT region whose region identifier is identical to cue's text
             // track cue region identifier, run the following substeps:
 #endif
-            if (displayBox->hasChildNodes() && !contains(static_cast<Node*>(displayBox.get())))
+            if (displayBox->hasChildNodes() && !contains(displayBox.get()))
                 // Note: the display tree of a cue is removed when the active flag of the cue is unset.
                 appendChild(displayBox, ASSERT_NO_EXCEPTION, AttachNow);
 #if ENABLE(WEBVTT_REGIONS)
diff --git a/Source/core/html/shadow/MediaControlElements.h b/Source/core/html/shadow/MediaControlElements.h
index 7a4f3b7..712ccbb 100644
--- a/Source/core/html/shadow/MediaControlElements.h
+++ b/Source/core/html/shadow/MediaControlElements.h
@@ -259,7 +259,7 @@
     explicit MediaControlTextTrackContainerElement(Document*);
     virtual const AtomicString& shadowPseudoId() const OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     IntRect m_videoDisplaySize;
     float m_fontSize;
diff --git a/Source/core/html/shadow/MediaControls.cpp b/Source/core/html/shadow/MediaControls.cpp
index 37a0418..4e3ff07 100644
--- a/Source/core/html/shadow/MediaControls.cpp
+++ b/Source/core/html/shadow/MediaControls.cpp
@@ -342,7 +342,7 @@
 {
     if (!event->isMouseEvent())
         return false;
-    EventTarget* relatedTarget = static_cast<MouseEvent*>(event)->relatedTarget();
+    EventTarget* relatedTarget = toMouseEvent(event)->relatedTarget();
     if (!relatedTarget)
         return false;
     return contains(relatedTarget->toNode());
diff --git a/Source/core/html/shadow/MediaControls.h b/Source/core/html/shadow/MediaControls.h
index b83157f..cb65516 100644
--- a/Source/core/html/shadow/MediaControls.h
+++ b/Source/core/html/shadow/MediaControls.h
@@ -27,18 +27,11 @@
 #ifndef MediaControls_h
 #define MediaControls_h
 
-#include "HTMLNames.h"
 #include "core/dom/MouseEvent.h"
-#include "core/dom/Text.h"
 #include "core/html/HTMLDivElement.h"
-#include "core/html/HTMLMediaElement.h"
 #include "core/html/shadow/MediaControlElements.h"
-#include "core/page/Chrome.h"
 #include "core/page/Page.h"
 #include "core/rendering/RenderTheme.h"
-#include <wtf/RefPtr.h>
-
-#include "core/html/track/TextTrackCue.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/shadow/MeterShadowElement.cpp b/Source/core/html/shadow/MeterShadowElement.cpp
index 482c4eb..df0220b 100644
--- a/Source/core/html/shadow/MeterShadowElement.cpp
+++ b/Source/core/html/shadow/MeterShadowElement.cpp
@@ -79,9 +79,9 @@
     return render && !render->theme()->supportsMeter(render->style()->appearance()) && HTMLDivElement::rendererIsNeeded(context);
 }
 
-RenderObject* MeterInnerElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* MeterInnerElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderMeter(this);
+    return new (document()->renderArena()) RenderMeter(this);
 }
 
 inline MeterBarElement::MeterBarElement(Document* document)
diff --git a/Source/core/html/shadow/MeterShadowElement.h b/Source/core/html/shadow/MeterShadowElement.h
index e076515..a7b644c 100644
--- a/Source/core/html/shadow/MeterShadowElement.h
+++ b/Source/core/html/shadow/MeterShadowElement.h
@@ -55,7 +55,7 @@
 private:
     MeterInnerElement(Document*);
     virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 };
 
 class MeterBarElement FINAL : public MeterShadowElement {
diff --git a/Source/core/html/shadow/PickerIndicatorElement.cpp b/Source/core/html/shadow/PickerIndicatorElement.cpp
index 37531e4..3fedf69 100644
--- a/Source/core/html/shadow/PickerIndicatorElement.cpp
+++ b/Source/core/html/shadow/PickerIndicatorElement.cpp
@@ -64,9 +64,9 @@
     ASSERT(!m_chooser);
 }
 
-RenderObject* PickerIndicatorElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* PickerIndicatorElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderDetailsMarker(this);
+    return new (document()->renderArena()) RenderDetailsMarker(this);
 }
 
 void PickerIndicatorElement::defaultEventHandler(Event* event)
diff --git a/Source/core/html/shadow/PickerIndicatorElement.h b/Source/core/html/shadow/PickerIndicatorElement.h
index 496d151..29aff6e 100644
--- a/Source/core/html/shadow/PickerIndicatorElement.h
+++ b/Source/core/html/shadow/PickerIndicatorElement.h
@@ -35,7 +35,6 @@
 #include "core/html/HTMLDivElement.h"
 #include "core/platform/DateTimeChooser.h"
 #include "core/platform/DateTimeChooserClient.h"
-#include <wtf/OwnPtr.h>
 
 namespace WebCore {
 
@@ -67,7 +66,7 @@
 
 private:
     PickerIndicatorElement(Document*, PickerIndicatorOwner&);
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
     virtual void defaultEventHandler(Event*) OVERRIDE;
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual bool isPickerIndicatorElement() const OVERRIDE;
diff --git a/Source/core/html/shadow/ProgressShadowElement.cpp b/Source/core/html/shadow/ProgressShadowElement.cpp
index f7fdc8a..6411544 100644
--- a/Source/core/html/shadow/ProgressShadowElement.cpp
+++ b/Source/core/html/shadow/ProgressShadowElement.cpp
@@ -70,9 +70,9 @@
     return element.release();
 }
 
-RenderObject* ProgressInnerElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* ProgressInnerElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderProgress(this);
+    return new (document()->renderArena()) RenderProgress(this);
 }
 
 bool ProgressInnerElement::rendererIsNeeded(const NodeRenderingContext& context)
diff --git a/Source/core/html/shadow/ProgressShadowElement.h b/Source/core/html/shadow/ProgressShadowElement.h
index db6e4d2..68b5f64 100644
--- a/Source/core/html/shadow/ProgressShadowElement.h
+++ b/Source/core/html/shadow/ProgressShadowElement.h
@@ -54,7 +54,7 @@
 
     static PassRefPtr<ProgressInnerElement> create(Document*);
 private:
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
     virtual bool rendererIsNeeded(const NodeRenderingContext&);
 };
 
diff --git a/Source/core/html/shadow/SliderThumbElement.cpp b/Source/core/html/shadow/SliderThumbElement.cpp
index 3579d9a..24d35eb 100644
--- a/Source/core/html/shadow/SliderThumbElement.cpp
+++ b/Source/core/html/shadow/SliderThumbElement.cpp
@@ -44,7 +44,6 @@
 #include "core/rendering/RenderFlexibleBox.h"
 #include "core/rendering/RenderSlider.h"
 #include "core/rendering/RenderTheme.h"
-#include <wtf/MathExtras.h>
 
 using namespace std;
 
@@ -220,9 +219,9 @@
         renderer()->setNeedsLayout(true);
 }
 
-RenderObject* SliderThumbElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SliderThumbElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSliderThumb(this);
+    return new (document()->renderArena()) RenderSliderThumb(this);
 }
 
 bool SliderThumbElement::isDisabledFormControl() const
@@ -348,7 +347,7 @@
         return;
     }
 
-    MouseEvent* mouseEvent = static_cast<MouseEvent*>(event);
+    MouseEvent* mouseEvent = toMouseEvent(event);
     bool isLeftButton = mouseEvent->button() == LeftButton;
     const AtomicString& eventType = event->type();
 
@@ -448,9 +447,9 @@
     return adoptRef(new SliderContainerElement(document));
 }
 
-RenderObject* SliderContainerElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SliderContainerElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSliderContainer(this);
+    return new (document()->renderArena()) RenderSliderContainer(this);
 }
 
 const AtomicString& SliderContainerElement::shadowPseudoId() const
diff --git a/Source/core/html/shadow/SliderThumbElement.h b/Source/core/html/shadow/SliderThumbElement.h
index 983d44b..e6ddcf7 100644
--- a/Source/core/html/shadow/SliderThumbElement.h
+++ b/Source/core/html/shadow/SliderThumbElement.h
@@ -34,10 +34,8 @@
 
 #include "HTMLNames.h"
 #include "core/html/HTMLDivElement.h"
-#include "core/platform/graphics/FloatPoint.h"
 #include "core/rendering/RenderBlock.h"
-#include "core/rendering/style/RenderStyleConstants.h"
-#include <wtf/Forward.h>
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
@@ -63,7 +61,7 @@
 
 private:
     SliderThumbElement(Document*);
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual PassRefPtr<Element> cloneElementWithoutAttributesAndChildren();
     virtual bool isDisabledFormControl() const OVERRIDE;
     virtual bool matchesReadOnlyPseudoClass() const OVERRIDE;
@@ -121,7 +119,7 @@
 
 private:
     SliderContainerElement(Document*);
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual const AtomicString& shadowPseudoId() const;
 };
 
diff --git a/Source/core/html/shadow/SpinButtonElement.cpp b/Source/core/html/shadow/SpinButtonElement.cpp
index f82212f..17c1d41 100644
--- a/Source/core/html/shadow/SpinButtonElement.cpp
+++ b/Source/core/html/shadow/SpinButtonElement.cpp
@@ -88,7 +88,7 @@
         return;
     }
 
-    MouseEvent* mouseEvent = static_cast<MouseEvent*>(event);
+    MouseEvent* mouseEvent = toMouseEvent(event);
     IntPoint local = roundedIntPoint(box->absoluteToLocal(mouseEvent->absoluteLocation(), UseTransforms));
     if (mouseEvent->type() == eventNames().mousedownEvent && mouseEvent->button() == LeftButton) {
         if (box->pixelSnappedBorderBoxRect().contains(local)) {
diff --git a/Source/core/html/shadow/TextControlInnerElements.cpp b/Source/core/html/shadow/TextControlInnerElements.cpp
index 0eb551d..def5731 100644
--- a/Source/core/html/shadow/TextControlInnerElements.cpp
+++ b/Source/core/html/shadow/TextControlInnerElements.cpp
@@ -29,23 +29,19 @@
 
 #include "HTMLNames.h"
 #include "bindings/v8/ScriptController.h"
-#include "core/dom/BeforeTextInsertedEvent.h"
 #include "core/dom/Document.h"
 #include "core/dom/EventNames.h"
 #include "core/dom/MouseEvent.h"
 #include "core/dom/TextEvent.h"
 #include "core/dom/TextEventInputType.h"
 #include "core/html/HTMLInputElement.h"
-#include "core/html/HTMLTextAreaElement.h"
 #include "core/page/EventHandler.h"
 #include "core/page/Frame.h"
-#include "core/page/Page.h"
 #include "core/page/SpeechInput.h"
 #include "core/page/SpeechInputEvent.h"
 #include "core/rendering/RenderSearchField.h"
 #include "core/rendering/RenderTextControl.h"
 #include "core/rendering/RenderView.h"
-#include "core/rendering/style/StyleInheritedData.h"
 
 namespace WebCore {
 
@@ -61,9 +57,9 @@
     return adoptRef(new TextControlInnerContainer(document));
 }
     
-RenderObject* TextControlInnerContainer::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* TextControlInnerContainer::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderTextControlInnerContainer(this);
+    return new (document()->renderArena()) RenderTextControlInnerContainer(this);
 }
 
 TextControlInnerElement::TextControlInnerElement(Document* document)
@@ -115,9 +111,9 @@
         HTMLDivElement::defaultEventHandler(event);
 }
 
-RenderObject* TextControlInnerTextElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* TextControlInnerTextElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderTextControlInnerBlock(this);
+    return new (document()->renderArena()) RenderTextControlInnerBlock(this);
 }
 
 PassRefPtr<RenderStyle> TextControlInnerTextElement::customStyleForRenderer()
@@ -157,7 +153,7 @@
 {
     // On mousedown, focus the search field
     HTMLInputElement* input = toHTMLInputElement(shadowHost());
-    if (input && event->type() == eventNames().mousedownEvent && event->isMouseEvent() && static_cast<MouseEvent*>(event)->button() == LeftButton) {
+    if (input && event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         input->focus();
         input->select();
         RenderSearchField* renderer = toRenderSearchField(input->renderer());
@@ -208,7 +204,7 @@
         return;
     }
 
-    if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && static_cast<MouseEvent*>(event)->button() == LeftButton) {
+    if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (renderer() && renderer()->visibleToHitTesting()) {
             if (Frame* frame = document()->frame()) {
                 frame->eventHandler()->setCapturingMouseEventsNode(this);
@@ -219,7 +215,7 @@
         input->select();
         event->setDefaultHandled();
     }
-    if (event->type() == eventNames().mouseupEvent && event->isMouseEvent() && static_cast<MouseEvent*>(event)->button() == LeftButton) {
+    if (event->type() == eventNames().mouseupEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (m_capturing) {
             if (Frame* frame = document()->frame()) {
                 frame->eventHandler()->setCapturingMouseEventsNode(0);
@@ -296,7 +292,7 @@
     }
 
     // On mouse down, select the text and set focus.
-    if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && static_cast<MouseEvent*>(event)->button() == LeftButton) {
+    if (event->type() == eventNames().mousedownEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (renderer() && renderer()->visibleToHitTesting()) {
             if (Frame* frame = document()->frame()) {
                 frame->eventHandler()->setCapturingMouseEventsNode(this);
@@ -309,7 +305,7 @@
         event->setDefaultHandled();
     }
     // On mouse up, release capture cleanly.
-    if (event->type() == eventNames().mouseupEvent && event->isMouseEvent() && static_cast<MouseEvent*>(event)->button() == LeftButton) {
+    if (event->type() == eventNames().mouseupEvent && event->isMouseEvent() && toMouseEvent(event)->button() == LeftButton) {
         if (m_capturing && renderer() && renderer()->visibleToHitTesting()) {
             if (Frame* frame = document()->frame()) {
                 frame->eventHandler()->setCapturingMouseEventsNode(0);
diff --git a/Source/core/html/shadow/TextControlInnerElements.h b/Source/core/html/shadow/TextControlInnerElements.h
index 78ad561..2bb6e24 100644
--- a/Source/core/html/shadow/TextControlInnerElements.h
+++ b/Source/core/html/shadow/TextControlInnerElements.h
@@ -40,7 +40,7 @@
     static PassRefPtr<TextControlInnerContainer> create(Document*);
 protected:
     TextControlInnerContainer(Document*);
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 };
 
 class TextControlInnerElement FINAL : public HTMLDivElement {
@@ -63,7 +63,7 @@
 
 private:
     TextControlInnerTextElement(Document*);
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual PassRefPtr<RenderStyle> customStyleForRenderer() OVERRIDE;
     virtual bool isMouseFocusable() const { return false; }
 };
diff --git a/Source/core/html/shadow/TextFieldDecorationElement.cpp b/Source/core/html/shadow/TextFieldDecorationElement.cpp
index f281d43..5020fc7 100644
--- a/Source/core/html/shadow/TextFieldDecorationElement.cpp
+++ b/Source/core/html/shadow/TextFieldDecorationElement.cpp
@@ -111,10 +111,10 @@
     ASSERT(existingRoot);
     RefPtr<HTMLDivElement> box = HTMLDivElement::create(input->document());
     decorationRoot->appendChild(box);
-    box->setInlineStyleProperty(CSSPropertyDisplay, CSSValueWebkitFlex);
-    box->setInlineStyleProperty(CSSPropertyWebkitAlignItems, CSSValueCenter);
+    box->setInlineStyleProperty(CSSPropertyDisplay, CSSValueFlex);
+    box->setInlineStyleProperty(CSSPropertyAlignItems, CSSValueCenter);
     ASSERT(existingRoot->childNodeCount() == 1);
-    toHTMLElement(existingRoot->firstChild())->setInlineStyleProperty(CSSPropertyWebkitFlexGrow, 1.0, CSSPrimitiveValue::CSS_NUMBER);
+    toHTMLElement(existingRoot->firstChild())->setInlineStyleProperty(CSSPropertyFlexGrow, 1.0, CSSPrimitiveValue::CSS_NUMBER);
     box->appendChild(HTMLShadowElement::create(HTMLNames::shadowTag, input->document()));
     setInlineStyleProperty(CSSPropertyDisplay, visible ? CSSValueBlock : CSSValueNone);
     box->appendChild(this);
@@ -162,9 +162,9 @@
     return style.release();
 }
 
-RenderObject* TextFieldDecorationElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* TextFieldDecorationElement::createRenderer(RenderStyle*)
 {
-    RenderImage* image = new (arena) RenderImage(this);
+    RenderImage* image = new (document()->renderArena()) RenderImage(this);
     image->setImageResource(RenderImageResource::create());
     return image;
 }
diff --git a/Source/core/html/shadow/TextFieldDecorationElement.h b/Source/core/html/shadow/TextFieldDecorationElement.h
index 5222044..e4cd73b 100644
--- a/Source/core/html/shadow/TextFieldDecorationElement.h
+++ b/Source/core/html/shadow/TextFieldDecorationElement.h
@@ -79,7 +79,7 @@
     TextFieldDecorationElement(Document*, TextFieldDecorator*);
     virtual bool isTextFieldDecoration() const OVERRIDE;
     virtual PassRefPtr<RenderStyle> customStyleForRenderer() OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual void detach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual bool isMouseFocusable() const OVERRIDE;
diff --git a/Source/core/html/track/InbandTextTrack.h b/Source/core/html/track/InbandTextTrack.h
index db73064..236d5de 100644
--- a/Source/core/html/track/InbandTextTrack.h
+++ b/Source/core/html/track/InbandTextTrack.h
@@ -27,9 +27,8 @@
 #define InbandTextTrack_h
 
 #include "core/html/track/TextTrack.h"
-#include "core/platform/graphics/InbandTextTrackPrivate.h"
 #include "core/platform/graphics/InbandTextTrackPrivateClient.h"
-#include <wtf/RefPtr.h>
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/track/LoadableTextTrack.cpp b/Source/core/html/track/LoadableTextTrack.cpp
index 06c5c92..a856d17 100644
--- a/Source/core/html/track/LoadableTextTrack.cpp
+++ b/Source/core/html/track/LoadableTextTrack.cpp
@@ -29,7 +29,6 @@
 
 #include "core/html/HTMLTrackElement.h"
 #include "core/html/track/TextTrackCueList.h"
-#include "core/html/track/TextTrackRegionList.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/track/LoadableTextTrack.h b/Source/core/html/track/LoadableTextTrack.h
index a8ffc9e..4ac4c1f 100644
--- a/Source/core/html/track/LoadableTextTrack.h
+++ b/Source/core/html/track/LoadableTextTrack.h
@@ -28,8 +28,7 @@
 
 #include "core/html/track/TextTrack.h"
 #include "core/loader/TextTrackLoader.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/track/TextTrack.h b/Source/core/html/track/TextTrack.h
index c033f74..655eb31 100644
--- a/Source/core/html/track/TextTrack.h
+++ b/Source/core/html/track/TextTrack.h
@@ -30,9 +30,7 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/html/track/TrackBase.h"
-#include <wtf/PassOwnPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/html/track/TextTrack.idl b/Source/core/html/track/TextTrack.idl
index 00a44a8..c1b39ff 100644
--- a/Source/core/html/track/TextTrack.idl
+++ b/Source/core/html/track/TextTrack.idl
@@ -40,11 +40,9 @@
     void addCue(TextTrackCue cue);
     [RaisesException] void removeCue(TextTrackCue cue);
 
-#if defined(ENABLE_WEBVTT_REGIONS) && ENABLE_WEBVTT_REGIONS
-    readonly attribute TextTrackRegionList regions;
-    void addRegion(TextTrackRegion region);
-    [RaisesException] void removeRegion(TextTrackRegion region);
-#endif
+    [Conditional=WEBVTT_REGIONS] readonly attribute TextTrackRegionList regions;
+    [Conditional=WEBVTT_REGIONS] void addRegion(TextTrackRegion region);
+    [RaisesException, Conditional=WEBVTT_REGIONS] void removeRegion(TextTrackRegion region);
 
     // EventTarget interface
     void addEventListener(DOMString type,
diff --git a/Source/core/html/track/TextTrackCue.cpp b/Source/core/html/track/TextTrackCue.cpp
index feddf70..96083de 100644
--- a/Source/core/html/track/TextTrackCue.cpp
+++ b/Source/core/html/track/TextTrackCue.cpp
@@ -41,12 +41,11 @@
 #include "core/html/HTMLDivElement.h"
 #include "core/html/track/TextTrack.h"
 #include "core/html/track/TextTrackCueList.h"
-#include "core/html/track/TextTrackRegionList.h"
 #include "core/html/track/WebVTTElement.h"
 #include "core/html/track/WebVTTParser.h"
 #include "core/rendering/RenderTextTrackCue.h"
-#include <wtf/MathExtras.h>
-#include <wtf/text/StringBuilder.h>
+#include "wtf/MathExtras.h"
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
@@ -179,9 +178,9 @@
     return trackDisplayBoxShadowPseudoId;
 }
 
-RenderObject* TextTrackCueBox::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* TextTrackCueBox::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderTextTrackCue(this);
+    return new (document()->renderArena()) RenderTextTrackCue(this);
 }
 
 // ----------------------------
@@ -480,8 +479,11 @@
 
 int TextTrackCue::cueIndex()
 {
-    if (m_cueIndex == invalidCueIndex)
-        m_cueIndex = track()->cues()->getCueIndex(this);
+    if (m_cueIndex == invalidCueIndex) {
+        TextTrackCueList* cues = track()->cues();
+        if (cues)
+            m_cueIndex = cues->getCueIndex(this);
+    }
 
     return m_cueIndex;
 }
@@ -760,7 +762,7 @@
             toWebVTTElement(child)->setIsPastNode(isPastNode);
             // Make an elemenet id match a cue id for style matching purposes.
             if (!m_id.isEmpty())
-                toElement(child)->setIdAttribute(AtomicString(m_id.characters(), m_id.length()));
+                toElement(child)->setIdAttribute(m_id);
         }
     }
 }
diff --git a/Source/core/html/track/TextTrackCue.h b/Source/core/html/track/TextTrackCue.h
index eeb7880..8c29667 100644
--- a/Source/core/html/track/TextTrackCue.h
+++ b/Source/core/html/track/TextTrackCue.h
@@ -35,10 +35,7 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/dom/EventTarget.h"
 #include "core/html/HTMLDivElement.h"
-#include "core/html/HTMLElement.h"
-#include "core/html/track/TextTrack.h"
-#include <wtf/PassOwnPtr.h>
-#include <wtf/RefCounted.h>
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
@@ -64,7 +61,7 @@
 protected:
     TextTrackCueBox(Document*, TextTrackCue*);
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     TextTrackCue* m_cue;
 };
diff --git a/Source/core/html/track/TextTrackCue.idl b/Source/core/html/track/TextTrackCue.idl
index 7933a53..962f695 100644
--- a/Source/core/html/track/TextTrackCue.idl
+++ b/Source/core/html/track/TextTrackCue.idl
@@ -58,8 +58,6 @@
                              optional boolean useCapture);
     [RaisesException] boolean dispatchEvent(Event evt);
 
-#if defined(ENABLE_WEBVTT_REGIONS) && ENABLE_WEBVTT_REGIONS
-    attribute DOMString regionId;
-#endif
+    [Conditional=WEBVTT_REGIONS] attribute DOMString regionId;
 };
 
diff --git a/Source/core/html/track/TextTrackCueGeneric.h b/Source/core/html/track/TextTrackCueGeneric.h
index 821fa7c..4997e86 100644
--- a/Source/core/html/track/TextTrackCueGeneric.h
+++ b/Source/core/html/track/TextTrackCueGeneric.h
@@ -28,7 +28,6 @@
 
 #include "core/html/track/TextTrackCue.h"
 #include "core/platform/graphics/Color.h"
-#include <wtf/RefCounted.h>
 
 namespace WebCore {
 
diff --git a/Source/core/html/track/TextTrackList.h b/Source/core/html/track/TextTrackList.h
index 9876406..1d55351 100644
--- a/Source/core/html/track/TextTrackList.h
+++ b/Source/core/html/track/TextTrackList.h
@@ -34,8 +34,6 @@
 #include "wtf/RefCounted.h"
 #include "wtf/Vector.h"
 
-#include <algorithm>
-
 namespace WebCore {
 
 class HTMLMediaElement;
diff --git a/Source/core/html/track/TextTrackRegion.cpp b/Source/core/html/track/TextTrackRegion.cpp
index d63a2cd..17bf8db 100644
--- a/Source/core/html/track/TextTrackRegion.cpp
+++ b/Source/core/html/track/TextTrackRegion.cpp
@@ -70,7 +70,7 @@
 static const float scrollTime = 0.433;
 
 TextTrackRegion::TextTrackRegion(ScriptExecutionContext* context)
-    : ContextDestructionObserver(context)
+    : ContextLifecycleObserver(context)
     , m_id(emptyString())
     , m_width(defaultWidth)
     , m_heightInLines(defaultHeightInLines)
diff --git a/Source/core/html/track/TextTrackRegion.h b/Source/core/html/track/TextTrackRegion.h
index 168c87a..30b8568 100644
--- a/Source/core/html/track/TextTrackRegion.h
+++ b/Source/core/html/track/TextTrackRegion.h
@@ -33,7 +33,7 @@
 
 #if ENABLE(WEBVTT_REGIONS)
 
-#include "core/dom/ContextDestructionObserver.h"
+#include "core/dom/ContextLifecycleObserver.h"
 #include "core/dom/Document.h"
 #include "core/html/track/TextTrack.h"
 #include "core/platform/graphics/FloatPoint.h"
@@ -45,7 +45,7 @@
 class HTMLDivElement;
 class TextTrackCueBox;
 
-class TextTrackRegion : public RefCounted<TextTrackRegion>, public ContextDestructionObserver {
+class TextTrackRegion : public RefCounted<TextTrackRegion>, public ContextLifecycleObserver {
 public:
     static PassRefPtr<TextTrackRegion> create(ScriptExecutionContext* context)
     {
diff --git a/Source/core/inspector/CodeGeneratorInspector.py b/Source/core/inspector/CodeGeneratorInspector.py
index a718464..4c81796 100755
--- a/Source/core/inspector/CodeGeneratorInspector.py
+++ b/Source/core/inspector/CodeGeneratorInspector.py
@@ -226,7 +226,11 @@
 
         @classmethod
         def get_raw_validator_call_text(cls):
-            return "RuntimeCastHelper::assertType<InspectorValue::Type%s>" % cls.get_validate_method_params().template_type
+            return "RuntimeCastHelper::assertType<JSONValue::Type%s>" % cls.get_validate_method_params().template_type
+
+        @staticmethod
+        def get_validate_method_params():
+            raise Exception("Abstract method")
 
     class String(BaseType):
         @staticmethod
@@ -393,7 +397,7 @@
 
         @staticmethod
         def get_c_initializer():
-            return "InspectorObject::create()"
+            return "JSONObject::create()"
 
         @staticmethod
         def get_output_argument_prefix():
@@ -415,7 +419,7 @@
 
         @staticmethod
         def get_array_item_raw_c_type_text():
-            return "InspectorObject"
+            return "JSONObject"
 
         @staticmethod
         def get_raw_type_model():
@@ -450,7 +454,7 @@
 
         @staticmethod
         def get_array_item_raw_c_type_text():
-            return "InspectorValue"
+            return "JSONValue"
 
         @staticmethod
         def get_raw_type_model():
@@ -471,7 +475,7 @@
 
         @staticmethod
         def get_c_initializer():
-            return "InspectorArray::create()"
+            return "JSONArray::create()"
 
         @staticmethod
         def get_output_argument_prefix():
@@ -493,7 +497,7 @@
 
         @staticmethod
         def get_array_item_raw_c_type_text():
-            return "InspectorArray"
+            return "JSONArray"
 
         @staticmethod
         def get_raw_type_model():
@@ -690,14 +694,14 @@
             cls.Int = cls.ValueType("int", False)
         cls.Number = cls.ValueType("double", False)
         cls.String = cls.ValueType("String", True,)
-        cls.Object = cls.RefPtrBased("InspectorObject")
-        cls.Array = cls.RefPtrBased("InspectorArray")
-        cls.Any = cls.RefPtrBased("InspectorValue")
+        cls.Object = cls.RefPtrBased("JSONObject")
+        cls.Array = cls.RefPtrBased("JSONArray")
+        cls.Any = cls.RefPtrBased("JSONValue")
 
 TypeModel.init_class()
 
 
-# Collection of InspectorObject class methods that are likely to be overloaded in generated class.
+# Collection of JSONObject class methods that are likely to be overloaded in generated class.
 # We must explicitly import all overloaded methods or they won't be available to user.
 INSPECTOR_OBJECT_SETTER_NAMES = frozenset(["setValue", "setBoolean", "setNumber", "setString", "setValue", "setObject", "setArray"])
 
@@ -893,14 +897,14 @@
 
                                 if enum_binding_cls.need_internal_runtime_cast_:
                                     writer.append("#if %s\n" % VALIDATOR_IFDEF_NAME)
-                                    writer.newline("    static void assertCorrectValue(InspectorValue* value);\n")
+                                    writer.newline("    static void assertCorrectValue(JSONValue* value);\n")
                                     writer.append("#endif  // %s\n" % VALIDATOR_IFDEF_NAME)
 
                                     validator_writer = generate_context.validator_writer
 
                                     domain_fixes = DomainNameFixes.get_fixed_data(context_domain_name)
 
-                                    validator_writer.newline("void %s%s::assertCorrectValue(InspectorValue* value)\n" % (helper.full_name_prefix_for_impl, enum_name))
+                                    validator_writer.newline("void %s%s::assertCorrectValue(JSONValue* value)\n" % (helper.full_name_prefix_for_impl, enum_name))
                                     validator_writer.newline("{\n")
                                     validator_writer.newline("    WTF::String s;\n")
                                     validator_writer.newline("    bool cast_res = value->asString(&s);\n")
@@ -1131,9 +1135,9 @@
                                 writer.append(class_name)
                                 writer.append(" : public ")
                                 if is_open_type:
-                                    writer.append("InspectorObject")
+                                    writer.append("JSONObject")
                                 else:
-                                    writer.append("InspectorObjectBase")
+                                    writer.append("JSONObjectBase")
                                 writer.append(" {\n")
                                 writer.newline("public:\n")
                                 ad_hoc_type_writer = writer.insert_writer("    ")
@@ -1210,25 +1214,25 @@
 
 
                                     if setter_name in INSPECTOR_OBJECT_SETTER_NAMES:
-                                        writer.newline("    using InspectorObjectBase::%s;\n\n" % setter_name)
+                                        writer.newline("    using JSONObjectBase::%s;\n\n" % setter_name)
 
                                 if class_binding_cls.need_user_runtime_cast_:
-                                    writer.newline("    static PassRefPtr<%s> runtimeCast(PassRefPtr<InspectorValue> value)\n" % class_name)
+                                    writer.newline("    static PassRefPtr<%s> runtimeCast(PassRefPtr<JSONValue> value)\n" % class_name)
                                     writer.newline("    {\n")
-                                    writer.newline("        RefPtr<InspectorObject> object;\n")
+                                    writer.newline("        RefPtr<JSONObject> object;\n")
                                     writer.newline("        bool castRes = value->asObject(&object);\n")
                                     writer.newline("        ASSERT_UNUSED(castRes, castRes);\n")
                                     writer.append("#if %s\n" % VALIDATOR_IFDEF_NAME)
                                     writer.newline("        assertCorrectValue(object.get());\n")
                                     writer.append("#endif  // %s\n" % VALIDATOR_IFDEF_NAME)
-                                    writer.newline("        COMPILE_ASSERT(sizeof(%s) == sizeof(InspectorObjectBase), type_cast_problem);\n" % class_name)
-                                    writer.newline("        return static_cast<%s*>(static_cast<InspectorObjectBase*>(object.get()));\n" % class_name)
+                                    writer.newline("        COMPILE_ASSERT(sizeof(%s) == sizeof(JSONObjectBase), type_cast_problem);\n" % class_name)
+                                    writer.newline("        return static_cast<%s*>(static_cast<JSONObjectBase*>(object.get()));\n" % class_name)
                                     writer.newline("    }\n")
                                     writer.append("\n")
 
                                 if class_binding_cls.need_internal_runtime_cast_:
                                     writer.append("#if %s\n" % VALIDATOR_IFDEF_NAME)
-                                    writer.newline("    static void assertCorrectValue(InspectorValue* value);\n")
+                                    writer.newline("    static void assertCorrectValue(JSONValue* value);\n")
                                     writer.append("#endif  // %s\n" % VALIDATOR_IFDEF_NAME)
 
                                     closed_field_set = (context_domain_name + "." + class_name) not in TYPES_WITH_OPEN_FIELD_LIST_SET
@@ -1237,15 +1241,15 @@
 
                                     domain_fixes = DomainNameFixes.get_fixed_data(context_domain_name)
 
-                                    validator_writer.newline("void %s%s::assertCorrectValue(InspectorValue* value)\n" % (helper.full_name_prefix_for_impl, class_name))
+                                    validator_writer.newline("void %s%s::assertCorrectValue(JSONValue* value)\n" % (helper.full_name_prefix_for_impl, class_name))
                                     validator_writer.newline("{\n")
-                                    validator_writer.newline("    RefPtr<InspectorObject> object;\n")
+                                    validator_writer.newline("    RefPtr<JSONObject> object;\n")
                                     validator_writer.newline("    bool castRes = value->asObject(&object);\n")
                                     validator_writer.newline("    ASSERT_UNUSED(castRes, castRes);\n")
                                     for prop_data in resolve_data.main_properties:
                                         validator_writer.newline("    {\n")
                                         it_name = "%sPos" % prop_data.p["name"]
-                                        validator_writer.newline("        InspectorObject::iterator %s;\n" % it_name)
+                                        validator_writer.newline("        JSONObject::iterator %s;\n" % it_name)
                                         validator_writer.newline("        %s = object->find(\"%s\");\n" % (it_name, prop_data.p["name"]))
                                         validator_writer.newline("        ASSERT(%s != object->end());\n" % it_name)
                                         validator_writer.newline("        %s(%s->value.get());\n" % (prop_data.param_type_binding.get_validator_call_text(), it_name))
@@ -1257,7 +1261,7 @@
                                     for prop_data in resolve_data.optional_properties:
                                         validator_writer.newline("    {\n")
                                         it_name = "%sPos" % prop_data.p["name"]
-                                        validator_writer.newline("        InspectorObject::iterator %s;\n" % it_name)
+                                        validator_writer.newline("        JSONObject::iterator %s;\n" % it_name)
                                         validator_writer.newline("        %s = object->find(\"%s\");\n" % (it_name, prop_data.p["name"]))
                                         validator_writer.newline("        if (%s != object->end()) {\n" % it_name)
                                         validator_writer.newline("            %s(%s->value.get());\n" % (prop_data.param_type_binding.get_validator_call_text(), it_name))
@@ -1368,7 +1372,7 @@
 
                     @staticmethod
                     def get_validator_call_text():
-                        return "RuntimeCastHelper::assertType<InspectorValue::TypeObject>"
+                        return "RuntimeCastHelper::assertType<JSONValue::TypeObject>"
 
                     @classmethod
                     def get_array_item_c_type_text(cls):
@@ -1868,7 +1872,7 @@
     class EventMethodStructTemplate:
         @staticmethod
         def append_prolog(line_list):
-            line_list.append("    RefPtr<InspectorObject> paramsObject = InspectorObject::create();\n")
+            line_list.append("    RefPtr<JSONObject> paramsObject = JSONObject::create();\n")
 
         @staticmethod
         def append_epilog(line_list):
@@ -1884,7 +1888,7 @@
 
         Generator.method_name_enum_list.append("        %s," % cmd_enum_name)
         Generator.method_handler_list.append("            &InspectorBackendDispatcherImpl::%s_%s," % (domain_name, json_command_name))
-        Generator.backend_method_declaration_list.append("    void %s_%s(long callId, InspectorObject* requestMessageObject);" % (domain_name, json_command_name))
+        Generator.backend_method_declaration_list.append("    void %s_%s(long callId, JSONObject* requestMessageObject);" % (domain_name, json_command_name))
 
         ad_hoc_type_output = []
         Generator.backend_agent_interface_list.append(ad_hoc_type_output)
diff --git a/Source/core/inspector/CodeGeneratorInspectorStrings.py b/Source/core/inspector/CodeGeneratorInspectorStrings.py
index 8131ff2..8759b2f 100644
--- a/Source/core/inspector/CodeGeneratorInspectorStrings.py
+++ b/Source/core/inspector/CodeGeneratorInspectorStrings.py
@@ -44,16 +44,16 @@
 """)
 
 backend_method = (
-"""void InspectorBackendDispatcherImpl::${domainName}_$methodName(long callId, InspectorObject*$requestMessageObject)
+"""void InspectorBackendDispatcherImpl::${domainName}_$methodName(long callId, JSONObject*$requestMessageObject)
 {
-    RefPtr<InspectorArray> protocolErrors = InspectorArray::create();
+    RefPtr<JSONArray> protocolErrors = JSONArray::create();
 
     if (!$agentField)
         protocolErrors->pushString("${domainName} handler is not available.");
 $methodOutCode
 $methodInCode
-    RefPtr<InspectorObject> result = InspectorObject::create();
-    RefPtr<InspectorValue> resultErrorData;
+    RefPtr<JSONObject> result = JSONObject::create();
+    RefPtr<JSONValue> resultErrorData;
     ErrorString error;
     if (!protocolErrors->length()) {
         $agentField->$methodName(&error$agentCallParams);
@@ -66,7 +66,7 @@
 
 frontend_method = ("""void InspectorFrontend::$domainName::$eventName($parameters)
 {
-    RefPtr<InspectorObject> jsonMessage = InspectorObject::create();
+    RefPtr<JSONObject> jsonMessage = JSONObject::create();
     jsonMessage->setString("method", "$domainName.$eventName");
 $code    if (m_inspectorFrontendChannel)
         m_inspectorFrontendChannel->sendMessageToFrontend(jsonMessage->toJSONString());
@@ -78,8 +78,8 @@
 
 void InspectorBackendDispatcher::$agentName::$callbackName::sendSuccess($parameters)
 {
-    RefPtr<InspectorObject> jsonMessage = InspectorObject::create();
-$code    sendIfActive(jsonMessage, ErrorString(), PassRefPtr<InspectorValue>());
+    RefPtr<JSONObject> jsonMessage = JSONObject::create();
+$code    sendIfActive(jsonMessage, ErrorString(), PassRefPtr<JSONValue>());
 }
 """)
 
@@ -87,7 +87,7 @@
 """void InspectorBackendDispatcher::$agentName::$callbackName::sendFailure(const ErrorString& error, $parameter)
 {
     ASSERT(error.length());
-    RefPtr<InspectorValue> errorDataValue;
+    RefPtr<JSONValue> errorDataValue;
     if (error) {
         errorDataValue = $argument;
     }
@@ -101,9 +101,9 @@
 #define InspectorFrontend_h
 
 #include "InspectorTypeBuilder.h"
-#include "core/inspector/InspectorValues.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/text/WTFString.h>
+#include "core/platform/JSONValues.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -137,8 +137,8 @@
 namespace WebCore {
 
 class InspectorAgent;
-class InspectorObject;
-class InspectorArray;
+class JSONObject;
+class JSONArray;
 class InspectorFrontendChannel;
 
 typedef String ErrorString;
@@ -158,7 +158,7 @@
         bool isActive();
 
     protected:
-        void sendIfActive(PassRefPtr<InspectorObject> partialMessage, const ErrorString& invocationError, PassRefPtr<InspectorValue> errorData);
+        void sendIfActive(PassRefPtr<JSONObject> partialMessage, const ErrorString& invocationError, PassRefPtr<JSONValue> errorData);
 
     private:
         void disable() { m_alreadySent = true; }
@@ -186,7 +186,7 @@
     };
 
     void reportProtocolError(const long* const callId, CommonErrorCode, const String& errorMessage) const;
-    virtual void reportProtocolError(const long* const callId, CommonErrorCode, const String& errorMessage, PassRefPtr<InspectorValue> data) const = 0;
+    virtual void reportProtocolError(const long* const callId, CommonErrorCode, const String& errorMessage, PassRefPtr<JSONValue> data) const = 0;
     virtual void dispatch(const String& message) = 0;
     static bool getCommandName(const String& message, String* result);
 
@@ -211,12 +211,12 @@
 #include "config.h"
 #include "InspectorBackendDispatcher.h"
 
-
 #include "core/inspector/InspectorAgent.h"
 #include "core/inspector/InspectorFrontendChannel.h"
-#include "core/inspector/InspectorValues.h"
-#include <wtf/text/CString.h>
-#include <wtf/text/WTFString.h>
+#include "core/inspector/JSONParser.h"
+#include "core/platform/JSONValues.h"
+#include "wtf/text/CString.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -234,10 +234,10 @@
 
     virtual void clearFrontend() { m_inspectorFrontendChannel = 0; }
     virtual void dispatch(const String& message);
-    virtual void reportProtocolError(const long* const callId, CommonErrorCode, const String& errorMessage, PassRefPtr<InspectorValue> data) const;
+    virtual void reportProtocolError(const long* const callId, CommonErrorCode, const String& errorMessage, PassRefPtr<JSONValue> data) const;
     using InspectorBackendDispatcher::reportProtocolError;
 
-    void sendResponse(long callId, PassRefPtr<InspectorObject> result, const ErrorString&invocationError, PassRefPtr<InspectorValue> errorData);
+    void sendResponse(long callId, PassRefPtr<JSONObject> result, const ErrorString&invocationError, PassRefPtr<JSONValue> errorData);
     bool isActive() { return m_inspectorFrontendChannel; }
 
 $setters
@@ -248,16 +248,16 @@
 $fieldDeclarations
 
     template<typename R, typename V, typename V0>
-    static R getPropertyValueImpl(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors, V0 initial_value, bool (*as_method)(InspectorValue*, V*), const char* type_name);
+    static R getPropertyValueImpl(JSONObject* object, const String& name, bool* valueFound, JSONArray* protocolErrors, V0 initial_value, bool (*as_method)(JSONValue*, V*), const char* type_name);
 
-    static int getInt(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors);
-    static double getDouble(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors);
-    static String getString(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors);
-    static bool getBoolean(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors);
-    static PassRefPtr<InspectorObject> getObject(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors);
-    static PassRefPtr<InspectorArray> getArray(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors);
+    static int getInt(JSONObject* object, const String& name, bool* valueFound, JSONArray* protocolErrors);
+    static double getDouble(JSONObject* object, const String& name, bool* valueFound, JSONArray* protocolErrors);
+    static String getString(JSONObject* object, const String& name, bool* valueFound, JSONArray* protocolErrors);
+    static bool getBoolean(JSONObject* object, const String& name, bool* valueFound, JSONArray* protocolErrors);
+    static PassRefPtr<JSONObject> getObject(JSONObject* object, const String& name, bool* valueFound, JSONArray* protocolErrors);
+    static PassRefPtr<JSONArray> getArray(JSONObject* object, const String& name, bool* valueFound, JSONArray* protocolErrors);
 
-    void sendResponse(long callId, PassRefPtr<InspectorObject> result, const char* commandName, PassRefPtr<InspectorArray> protocolErrors, ErrorString invocationError, PassRefPtr<InspectorValue> errorData);
+    void sendResponse(long callId, PassRefPtr<JSONObject> result, const char* commandName, PassRefPtr<JSONArray> protocolErrors, ErrorString invocationError, PassRefPtr<JSONValue> errorData);
 
 };
 
@@ -272,7 +272,7 @@
 void InspectorBackendDispatcherImpl::dispatch(const String& message)
 {
     RefPtr<InspectorBackendDispatcher> protect = this;
-    typedef void (InspectorBackendDispatcherImpl::*CallHandler)(long callId, InspectorObject* messageObject);
+    typedef void (InspectorBackendDispatcherImpl::*CallHandler)(long callId, JSONObject* messageObject);
     typedef HashMap<String, CallHandler> DispatchMap;
     DEFINE_STATIC_LOCAL(DispatchMap, dispatchMap, );
     long callId = 0;
@@ -286,19 +286,19 @@
             dispatchMap.add(commandNames[i], handlers[i]);
     }
 
-    RefPtr<InspectorValue> parsedMessage = InspectorValue::parseJSON(message);
+    RefPtr<JSONValue> parsedMessage = parseJSON(message);
     if (!parsedMessage) {
         reportProtocolError(0, ParseError, "Message must be in JSON format");
         return;
     }
 
-    RefPtr<InspectorObject> messageObject = parsedMessage->asObject();
+    RefPtr<JSONObject> messageObject = parsedMessage->asObject();
     if (!messageObject) {
         reportProtocolError(0, InvalidRequest, "Message must be a JSONified object");
         return;
     }
 
-    RefPtr<InspectorValue> callIdValue = messageObject->get("id");
+    RefPtr<JSONValue> callIdValue = messageObject->get("id");
     if (!callIdValue) {
         reportProtocolError(0, InvalidRequest, "'id' property was not found");
         return;
@@ -309,7 +309,7 @@
         return;
     }
 
-    RefPtr<InspectorValue> methodValue = messageObject->get("method");
+    RefPtr<JSONValue> methodValue = messageObject->get("method");
     if (!methodValue) {
         reportProtocolError(&callId, InvalidRequest, "'method' property wasn't found");
         return;
@@ -330,7 +330,7 @@
     ((*this).*it->value)(callId, messageObject.get());
 }
 
-void InspectorBackendDispatcherImpl::sendResponse(long callId, PassRefPtr<InspectorObject> result, const char* commandName, PassRefPtr<InspectorArray> protocolErrors, ErrorString invocationError, PassRefPtr<InspectorValue> errorData)
+void InspectorBackendDispatcherImpl::sendResponse(long callId, PassRefPtr<JSONObject> result, const char* commandName, PassRefPtr<JSONArray> protocolErrors, ErrorString invocationError, PassRefPtr<JSONValue> errorData)
 {
     if (protocolErrors->length()) {
         String errorMessage = String::format("Some arguments of method '%s' can't be processed", commandName);
@@ -340,14 +340,14 @@
     sendResponse(callId, result, invocationError, errorData);
 }
 
-void InspectorBackendDispatcherImpl::sendResponse(long callId, PassRefPtr<InspectorObject> result, const ErrorString& invocationError, PassRefPtr<InspectorValue> errorData)
+void InspectorBackendDispatcherImpl::sendResponse(long callId, PassRefPtr<JSONObject> result, const ErrorString& invocationError, PassRefPtr<JSONValue> errorData)
 {
     if (invocationError.length()) {
         reportProtocolError(&callId, ServerError, invocationError, errorData);
         return;
     }
 
-    RefPtr<InspectorObject> responseMessage = InspectorObject::create();
+    RefPtr<JSONObject> responseMessage = JSONObject::create();
     responseMessage->setObject("result", result);
     responseMessage->setNumber("id", callId);
     if (m_inspectorFrontendChannel)
@@ -356,10 +356,10 @@
 
 void InspectorBackendDispatcher::reportProtocolError(const long* const callId, CommonErrorCode code, const String& errorMessage) const
 {
-    reportProtocolError(callId, code, errorMessage, PassRefPtr<InspectorValue>());
+    reportProtocolError(callId, code, errorMessage, PassRefPtr<JSONValue>());
 }
 
-void InspectorBackendDispatcherImpl::reportProtocolError(const long* const callId, CommonErrorCode code, const String& errorMessage, PassRefPtr<InspectorValue> data) const
+void InspectorBackendDispatcherImpl::reportProtocolError(const long* const callId, CommonErrorCode code, const String& errorMessage, PassRefPtr<JSONValue> data) const
 {
     DEFINE_STATIC_LOCAL(Vector<int>,s_commonErrors,);
     if (!s_commonErrors.size()) {
@@ -373,24 +373,24 @@
     ASSERT(code >=0);
     ASSERT((unsigned)code < s_commonErrors.size());
     ASSERT(s_commonErrors[code]);
-    RefPtr<InspectorObject> error = InspectorObject::create();
+    RefPtr<JSONObject> error = JSONObject::create();
     error->setNumber("code", s_commonErrors[code]);
     error->setString("message", errorMessage);
     ASSERT(error);
     if (data)
         error->setValue("data", data);
-    RefPtr<InspectorObject> message = InspectorObject::create();
+    RefPtr<JSONObject> message = JSONObject::create();
     message->setObject("error", error);
     if (callId)
         message->setNumber("id", *callId);
     else
-        message->setValue("id", InspectorValue::null());
+        message->setValue("id", JSONValue::null());
     if (m_inspectorFrontendChannel)
         m_inspectorFrontendChannel->sendMessageToFrontend(message->toJSONString());
 }
 
 template<typename R, typename V, typename V0>
-R InspectorBackendDispatcherImpl::getPropertyValueImpl(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors, V0 initial_value, bool (*as_method)(InspectorValue*, V*), const char* type_name)
+R InspectorBackendDispatcherImpl::getPropertyValueImpl(JSONObject* object, const String& name, bool* valueFound, JSONArray* protocolErrors, V0 initial_value, bool (*as_method)(JSONValue*, V*), const char* type_name)
 {
     ASSERT(protocolErrors);
 
@@ -407,8 +407,8 @@
         return value;
     }
 
-    InspectorObject::const_iterator end = object->end();
-    InspectorObject::const_iterator valueIterator = object->find(name);
+    JSONObject::const_iterator end = object->end();
+    JSONObject::const_iterator valueIterator = object->find(name);
 
     if (valueIterator == end) {
         if (!valueFound)
@@ -425,51 +425,51 @@
 }
 
 struct AsMethodBridges {
-    static bool asInt(InspectorValue* value, int* output) { return value->asNumber(output); }
-    static bool asDouble(InspectorValue* value, double* output) { return value->asNumber(output); }
-    static bool asString(InspectorValue* value, String* output) { return value->asString(output); }
-    static bool asBoolean(InspectorValue* value, bool* output) { return value->asBoolean(output); }
-    static bool asObject(InspectorValue* value, RefPtr<InspectorObject>* output) { return value->asObject(output); }
-    static bool asArray(InspectorValue* value, RefPtr<InspectorArray>* output) { return value->asArray(output); }
+    static bool asInt(JSONValue* value, int* output) { return value->asNumber(output); }
+    static bool asDouble(JSONValue* value, double* output) { return value->asNumber(output); }
+    static bool asString(JSONValue* value, String* output) { return value->asString(output); }
+    static bool asBoolean(JSONValue* value, bool* output) { return value->asBoolean(output); }
+    static bool asObject(JSONValue* value, RefPtr<JSONObject>* output) { return value->asObject(output); }
+    static bool asArray(JSONValue* value, RefPtr<JSONArray>* output) { return value->asArray(output); }
 };
 
-int InspectorBackendDispatcherImpl::getInt(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors)
+int InspectorBackendDispatcherImpl::getInt(JSONObject* object, const String& name, bool* valueFound, JSONArray* protocolErrors)
 {
     return getPropertyValueImpl<int, int, int>(object, name, valueFound, protocolErrors, 0, AsMethodBridges::asInt, "Number");
 }
 
-double InspectorBackendDispatcherImpl::getDouble(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors)
+double InspectorBackendDispatcherImpl::getDouble(JSONObject* object, const String& name, bool* valueFound, JSONArray* protocolErrors)
 {
     return getPropertyValueImpl<double, double, double>(object, name, valueFound, protocolErrors, 0, AsMethodBridges::asDouble, "Number");
 }
 
-String InspectorBackendDispatcherImpl::getString(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors)
+String InspectorBackendDispatcherImpl::getString(JSONObject* object, const String& name, bool* valueFound, JSONArray* protocolErrors)
 {
     return getPropertyValueImpl<String, String, String>(object, name, valueFound, protocolErrors, "", AsMethodBridges::asString, "String");
 }
 
-bool InspectorBackendDispatcherImpl::getBoolean(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors)
+bool InspectorBackendDispatcherImpl::getBoolean(JSONObject* object, const String& name, bool* valueFound, JSONArray* protocolErrors)
 {
     return getPropertyValueImpl<bool, bool, bool>(object, name, valueFound, protocolErrors, false, AsMethodBridges::asBoolean, "Boolean");
 }
 
-PassRefPtr<InspectorObject> InspectorBackendDispatcherImpl::getObject(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors)
+PassRefPtr<JSONObject> InspectorBackendDispatcherImpl::getObject(JSONObject* object, const String& name, bool* valueFound, JSONArray* protocolErrors)
 {
-    return getPropertyValueImpl<PassRefPtr<InspectorObject>, RefPtr<InspectorObject>, InspectorObject*>(object, name, valueFound, protocolErrors, 0, AsMethodBridges::asObject, "Object");
+    return getPropertyValueImpl<PassRefPtr<JSONObject>, RefPtr<JSONObject>, JSONObject*>(object, name, valueFound, protocolErrors, 0, AsMethodBridges::asObject, "Object");
 }
 
-PassRefPtr<InspectorArray> InspectorBackendDispatcherImpl::getArray(InspectorObject* object, const String& name, bool* valueFound, InspectorArray* protocolErrors)
+PassRefPtr<JSONArray> InspectorBackendDispatcherImpl::getArray(JSONObject* object, const String& name, bool* valueFound, JSONArray* protocolErrors)
 {
-    return getPropertyValueImpl<PassRefPtr<InspectorArray>, RefPtr<InspectorArray>, InspectorArray*>(object, name, valueFound, protocolErrors, 0, AsMethodBridges::asArray, "Array");
+    return getPropertyValueImpl<PassRefPtr<JSONArray>, RefPtr<JSONArray>, JSONArray*>(object, name, valueFound, protocolErrors, 0, AsMethodBridges::asArray, "Array");
 }
 
 bool InspectorBackendDispatcher::getCommandName(const String& message, String* result)
 {
-    RefPtr<InspectorValue> value = InspectorValue::parseJSON(message);
+    RefPtr<JSONValue> value = parseJSON(message);
     if (!value)
         return false;
 
-    RefPtr<InspectorObject> object = value->asObject();
+    RefPtr<JSONObject> object = value->asObject();
     if (!object)
         return false;
 
@@ -487,7 +487,7 @@
 void InspectorBackendDispatcher::CallbackBase::sendFailure(const ErrorString& error)
 {
     ASSERT(error.length());
-    sendIfActive(0, error, PassRefPtr<InspectorValue>());
+    sendIfActive(0, error, PassRefPtr<JSONValue>());
 }
 
 bool InspectorBackendDispatcher::CallbackBase::isActive()
@@ -495,7 +495,7 @@
     return !m_alreadySent && m_backendImpl->isActive();
 }
 
-void InspectorBackendDispatcher::CallbackBase::sendIfActive(PassRefPtr<InspectorObject> partialMessage, const ErrorString& invocationError, PassRefPtr<InspectorValue> errorData)
+void InspectorBackendDispatcher::CallbackBase::sendIfActive(PassRefPtr<JSONObject> partialMessage, const ErrorString& invocationError, PassRefPtr<JSONValue> errorData)
 {
     if (m_alreadySent)
         return;
@@ -513,13 +513,12 @@
 """
 
 #include "config.h"
-
 #include "InspectorFrontend.h"
-#include "core/inspector/InspectorFrontendChannel.h"
-#include "core/inspector/InspectorValues.h"
 
-#include <wtf/text/CString.h>
-#include <wtf/text/WTFString.h>
+#include "core/inspector/InspectorFrontendChannel.h"
+#include "core/platform/JSONValues.h"
+#include "wtf/text/CString.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -538,10 +537,9 @@
 #ifndef InspectorTypeBuilder_h
 #define InspectorTypeBuilder_h
 
-#include "core/inspector/InspectorValues.h"
-
-#include <wtf/Assertions.h>
-#include <wtf/PassRefPtr.h>
+#include "core/platform/JSONValues.h"
+#include "wtf/Assertions.h"
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
@@ -600,13 +598,13 @@
 class RuntimeCastHelper {
 public:
 #if $validatorIfdefName
-    template<InspectorValue::Type TYPE>
-    static void assertType(InspectorValue* value)
+    template<JSONValue::Type TYPE>
+    static void assertType(JSONValue* value)
     {
         ASSERT(value->type() == TYPE);
     }
-    static void assertAny(InspectorValue*);
-    static void assertInt(InspectorValue* value);
+    static void assertAny(JSONValue*);
+    static void assertInt(JSONValue* value);
 #endif
 };
 
@@ -619,13 +617,13 @@
 };
 
 template<typename T>
-class Array : public InspectorArrayBase {
+class Array : public JSONArrayBase {
 private:
     Array() { }
 
-    InspectorArray* openAccessors() {
-        COMPILE_ASSERT(sizeof(InspectorArray) == sizeof(Array<T>), cannot_cast);
-        return static_cast<InspectorArray*>(static_cast<InspectorArrayBase*>(this));
+    JSONArray* openAccessors() {
+        COMPILE_ASSERT(sizeof(JSONArray) == sizeof(Array<T>), cannot_cast);
+        return static_cast<JSONArray*>(static_cast<JSONArrayBase*>(this));
     }
 
 public:
@@ -644,22 +642,22 @@
         return adoptRef(new Array<T>());
     }
 
-    static PassRefPtr<Array<T> > runtimeCast(PassRefPtr<InspectorValue> value)
+    static PassRefPtr<Array<T> > runtimeCast(PassRefPtr<JSONValue> value)
     {
-        RefPtr<InspectorArray> array;
+        RefPtr<JSONArray> array;
         bool castRes = value->asArray(&array);
         ASSERT_UNUSED(castRes, castRes);
 #if $validatorIfdefName
         assertCorrectValue(array.get());
 #endif  // $validatorIfdefName
-        COMPILE_ASSERT(sizeof(Array<T>) == sizeof(InspectorArray), type_cast_problem);
-        return static_cast<Array<T>*>(static_cast<InspectorArrayBase*>(array.get()));
+        COMPILE_ASSERT(sizeof(Array<T>) == sizeof(JSONArray), type_cast_problem);
+        return static_cast<Array<T>*>(static_cast<JSONArrayBase*>(array.get()));
     }
 
 #if $validatorIfdefName
-    static void assertCorrectValue(InspectorValue* value)
+    static void assertCorrectValue(JSONValue* value)
     {
-        RefPtr<InspectorArray> array;
+        RefPtr<JSONArray> array;
         bool castRes = value->asArray(&array);
         ASSERT_UNUSED(castRes, castRes);
         for (unsigned i = 0; i < array->length(); i++)
@@ -670,14 +668,14 @@
 };
 
 struct StructItemTraits {
-    static void pushRefPtr(InspectorArray* array, PassRefPtr<InspectorValue> value)
+    static void pushRefPtr(JSONArray* array, PassRefPtr<JSONValue> value)
     {
         array->pushValue(value);
     }
 
 #if $validatorIfdefName
     template<typename T>
-    static void assertCorrectValue(InspectorValue* value) {
+    static void assertCorrectValue(JSONValue* value) {
         T::assertCorrectValue(value);
     }
 #endif  // $validatorIfdefName
@@ -686,15 +684,15 @@
 template<>
 struct ArrayItemHelper<String> {
     struct Traits {
-        static void pushRaw(InspectorArray* array, const String& value)
+        static void pushRaw(JSONArray* array, const String& value)
         {
             array->pushString(value);
         }
 
 #if $validatorIfdefName
         template<typename T>
-        static void assertCorrectValue(InspectorValue* value) {
-            RuntimeCastHelper::assertType<InspectorValue::TypeString>(value);
+        static void assertCorrectValue(JSONValue* value) {
+            RuntimeCastHelper::assertType<JSONValue::TypeString>(value);
         }
 #endif  // $validatorIfdefName
     };
@@ -703,14 +701,14 @@
 template<>
 struct ArrayItemHelper<int> {
     struct Traits {
-        static void pushRaw(InspectorArray* array, int value)
+        static void pushRaw(JSONArray* array, int value)
         {
             array->pushInt(value);
         }
 
 #if $validatorIfdefName
         template<typename T>
-        static void assertCorrectValue(InspectorValue* value) {
+        static void assertCorrectValue(JSONValue* value) {
             RuntimeCastHelper::assertInt(value);
         }
 #endif  // $validatorIfdefName
@@ -720,15 +718,15 @@
 template<>
 struct ArrayItemHelper<double> {
     struct Traits {
-        static void pushRaw(InspectorArray* array, double value)
+        static void pushRaw(JSONArray* array, double value)
         {
             array->pushNumber(value);
         }
 
 #if $validatorIfdefName
         template<typename T>
-        static void assertCorrectValue(InspectorValue* value) {
-            RuntimeCastHelper::assertType<InspectorValue::TypeNumber>(value);
+        static void assertCorrectValue(JSONValue* value) {
+            RuntimeCastHelper::assertType<JSONValue::TypeNumber>(value);
         }
 #endif  // $validatorIfdefName
     };
@@ -737,31 +735,31 @@
 template<>
 struct ArrayItemHelper<bool> {
     struct Traits {
-        static void pushRaw(InspectorArray* array, bool value)
+        static void pushRaw(JSONArray* array, bool value)
         {
             array->pushBoolean(value);
         }
 
 #if $validatorIfdefName
         template<typename T>
-        static void assertCorrectValue(InspectorValue* value) {
-            RuntimeCastHelper::assertType<InspectorValue::TypeBoolean>(value);
+        static void assertCorrectValue(JSONValue* value) {
+            RuntimeCastHelper::assertType<JSONValue::TypeBoolean>(value);
         }
 #endif  // $validatorIfdefName
     };
 };
 
 template<>
-struct ArrayItemHelper<InspectorValue> {
+struct ArrayItemHelper<JSONValue> {
     struct Traits {
-        static void pushRefPtr(InspectorArray* array, PassRefPtr<InspectorValue> value)
+        static void pushRefPtr(JSONArray* array, PassRefPtr<JSONValue> value)
         {
             array->pushValue(value);
         }
 
 #if $validatorIfdefName
         template<typename T>
-        static void assertCorrectValue(InspectorValue* value) {
+        static void assertCorrectValue(JSONValue* value) {
             RuntimeCastHelper::assertAny(value);
         }
 #endif  // $validatorIfdefName
@@ -769,34 +767,34 @@
 };
 
 template<>
-struct ArrayItemHelper<InspectorObject> {
+struct ArrayItemHelper<JSONObject> {
     struct Traits {
-        static void pushRefPtr(InspectorArray* array, PassRefPtr<InspectorValue> value)
+        static void pushRefPtr(JSONArray* array, PassRefPtr<JSONValue> value)
         {
             array->pushValue(value);
         }
 
 #if $validatorIfdefName
         template<typename T>
-        static void assertCorrectValue(InspectorValue* value) {
-            RuntimeCastHelper::assertType<InspectorValue::TypeObject>(value);
+        static void assertCorrectValue(JSONValue* value) {
+            RuntimeCastHelper::assertType<JSONValue::TypeObject>(value);
         }
 #endif  // $validatorIfdefName
     };
 };
 
 template<>
-struct ArrayItemHelper<InspectorArray> {
+struct ArrayItemHelper<JSONArray> {
     struct Traits {
-        static void pushRefPtr(InspectorArray* array, PassRefPtr<InspectorArray> value)
+        static void pushRefPtr(JSONArray* array, PassRefPtr<JSONArray> value)
         {
             array->pushArray(value);
         }
 
 #if $validatorIfdefName
         template<typename T>
-        static void assertCorrectValue(InspectorValue* value) {
-            RuntimeCastHelper::assertType<InspectorValue::TypeArray>(value);
+        static void assertCorrectValue(JSONValue* value) {
+            RuntimeCastHelper::assertType<JSONValue::TypeArray>(value);
         }
 #endif  // $validatorIfdefName
     };
@@ -805,14 +803,14 @@
 template<typename T>
 struct ArrayItemHelper<TypeBuilder::Array<T> > {
     struct Traits {
-        static void pushRefPtr(InspectorArray* array, PassRefPtr<TypeBuilder::Array<T> > value)
+        static void pushRefPtr(JSONArray* array, PassRefPtr<TypeBuilder::Array<T> > value)
         {
             array->pushValue(value);
         }
 
 #if $validatorIfdefName
         template<typename S>
-        static void assertCorrectValue(InspectorValue* value) {
+        static void assertCorrectValue(JSONValue* value) {
             S::assertCorrectValue(value);
         }
 #endif  // $validatorIfdefName
@@ -839,8 +837,7 @@
 #include "config.h"
 
 #include "InspectorTypeBuilder.h"
-
-#include <wtf/text/CString.h>
+#include "wtf/text/CString.h"
 
 namespace WebCore {
 
@@ -859,13 +856,13 @@
 
 #if $validatorIfdefName
 
-void TypeBuilder::RuntimeCastHelper::assertAny(InspectorValue*)
+void TypeBuilder::RuntimeCastHelper::assertAny(JSONValue*)
 {
     // No-op.
 }
 
 
-void TypeBuilder::RuntimeCastHelper::assertInt(InspectorValue* value)
+void TypeBuilder::RuntimeCastHelper::assertInt(JSONValue* value)
 {
     double v;
     bool castRes = value->asNumber(&v);
@@ -882,9 +879,9 @@
 """)
 
 param_container_access_code = """
-    RefPtr<InspectorObject> paramsContainer = requestMessageObject->getObject("params");
-    InspectorObject* paramsContainerPtr = paramsContainer.get();
-    InspectorArray* protocolErrorsPtr = protocolErrors.get();
+    RefPtr<JSONObject> paramsContainer = requestMessageObject->getObject("params");
+    JSONObject* paramsContainerPtr = paramsContainer.get();
+    JSONArray* protocolErrorsPtr = protocolErrors.get();
 """
 
 class_binding_builder_part_1 = (
@@ -894,14 +891,14 @@
     template<int STATE>
     class Builder {
     private:
-        RefPtr<InspectorObject> m_result;
+        RefPtr<JSONObject> m_result;
 
         template<int STEP> Builder<STATE | STEP>& castState()
         {
             return *reinterpret_cast<Builder<STATE | STEP>*>(this);
         }
 
-        Builder(PassRefPtr</*%s*/InspectorObject> ptr)
+        Builder(PassRefPtr</*%s*/JSONObject> ptr)
         {
             COMPILE_ASSERT(STATE == NoFieldsSet, builder_created_in_non_init_state);
             m_result = ptr;
@@ -923,7 +920,7 @@
         operator RefPtr<%s>& ()
         {
             COMPILE_ASSERT(STATE == AllFieldsSet, result_is_not_ready);
-            COMPILE_ASSERT(sizeof(%s) == sizeof(InspectorObject), cannot_cast);
+            COMPILE_ASSERT(sizeof(%s) == sizeof(JSONObject), cannot_cast);
             return *reinterpret_cast<RefPtr<%s>*>(&m_result);
         }
 
@@ -938,6 +935,6 @@
 class_binding_builder_part_4 = (
 """    static Builder<NoFieldsSet> create()
     {
-        return Builder<NoFieldsSet>(InspectorObject::create());
+        return Builder<NoFieldsSet>(JSONObject::create());
     }
 """)
diff --git a/Source/core/inspector/CodeGeneratorInstrumentation.py b/Source/core/inspector/CodeGeneratorInstrumentation.py
index 372d141..b72cb5d 100644
--- a/Source/core/inspector/CodeGeneratorInstrumentation.py
+++ b/Source/core/inspector/CodeGeneratorInstrumentation.py
@@ -277,6 +277,10 @@
         else:
             fast_return = ""
 
+        for param in self.params:
+            if "FastReturn" in param.options:
+                fast_return += "\n    if (!%s)\n        return %s;" % (param.name, self.default_return_value)
+
         if self.accepts_cookie:
             condition = "%s.isValid()" % self.params_impl[0].name
             template = template_inline
diff --git a/Source/core/inspector/ConsoleMessage.cpp b/Source/core/inspector/ConsoleMessage.cpp
index fed5016..7ce1741 100644
--- a/Source/core/inspector/ConsoleMessage.cpp
+++ b/Source/core/inspector/ConsoleMessage.cpp
@@ -42,9 +42,7 @@
 #include "core/inspector/ScriptArguments.h"
 #include "core/inspector/ScriptCallFrame.h"
 #include "core/inspector/ScriptCallStack.h"
-#include "core/page/Console.h"
 #include "wtf/CurrentTime.h"
-#include "wtf/MainThread.h"
 
 namespace WebCore {
 
@@ -55,6 +53,7 @@
     , m_message(message)
     , m_url()
     , m_line(0)
+    , m_column(0)
     , m_repeatCount(1)
     , m_requestId(IdentifiersFactory::requestId(0))
     , m_timestamp(WTF::currentTime())
@@ -62,13 +61,14 @@
     autogenerateMetadata(canGenerateCallStack);
 }
 
-ConsoleMessage::ConsoleMessage(bool canGenerateCallStack, MessageSource source, MessageType type, MessageLevel level, const String& message, const String& url, unsigned line, ScriptState* state, unsigned long requestIdentifier)
+ConsoleMessage::ConsoleMessage(bool canGenerateCallStack, MessageSource source, MessageType type, MessageLevel level, const String& message, const String& url, unsigned line, unsigned column, ScriptState* state, unsigned long requestIdentifier)
     : m_source(source)
     , m_type(type)
     , m_level(level)
     , m_message(message)
     , m_url(url)
     , m_line(line)
+    , m_column(column)
     , m_repeatCount(1)
     , m_requestId(IdentifiersFactory::requestId(requestIdentifier))
     , m_timestamp(WTF::currentTime())
@@ -83,6 +83,7 @@
     , m_message(message)
     , m_arguments(0)
     , m_line(0)
+    , m_column(0)
     , m_repeatCount(1)
     , m_requestId(IdentifiersFactory::requestId(requestIdentifier))
     , m_timestamp(WTF::currentTime())
@@ -91,6 +92,7 @@
         const ScriptCallFrame& frame = callStack->at(0);
         m_url = frame.sourceURL();
         m_line = frame.lineNumber();
+        m_column = frame.columnNumber();
     }
     m_callStack = callStack;
 }
@@ -103,6 +105,7 @@
     , m_arguments(arguments)
     , m_url()
     , m_line(0)
+    , m_column(0)
     , m_repeatCount(1)
     , m_requestId(IdentifiersFactory::requestId(requestIdentifier))
     , m_timestamp(WTF::currentTime())
@@ -130,6 +133,7 @@
         const ScriptCallFrame& frame = m_callStack->at(0);
         m_url = frame.sourceURL();
         m_line = frame.lineNumber();
+        m_column = frame.columnNumber();
         return;
     }
 
@@ -195,6 +199,7 @@
     // FIXME: only send out type for ConsoleAPI source messages.
     jsonObj->setType(messageTypeValue(m_type));
     jsonObj->setLine(static_cast<int>(m_line));
+    jsonObj->setColumn(static_cast<int>(m_column));
     jsonObj->setUrl(m_url);
     jsonObj->setRepeatCount(static_cast<int>(m_repeatCount));
     if (m_source == NetworkMessageSource && !m_requestId.isEmpty())
@@ -265,6 +270,7 @@
         && msg->m_level == m_level
         && msg->m_message == m_message
         && msg->m_line == m_line
+        && msg->m_column == m_column
         && msg->m_url == m_url
         && msg->m_requestId == m_requestId;
 }
diff --git a/Source/core/inspector/ConsoleMessage.h b/Source/core/inspector/ConsoleMessage.h
index 4ea2bdd..78f4f9f 100644
--- a/Source/core/inspector/ConsoleMessage.h
+++ b/Source/core/inspector/ConsoleMessage.h
@@ -35,15 +35,13 @@
 #include "bindings/v8/ScriptState.h"
 #include "core/inspector/ConsoleAPITypes.h"
 #include "core/page/ConsoleTypes.h"
-#include <wtf/Forward.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
 class DOMWindow;
 class InjectedScriptManager;
 class InspectorFrontend;
-class InspectorObject;
 class ScriptArguments;
 class ScriptCallFrame;
 class ScriptCallStack;
@@ -53,7 +51,7 @@
     WTF_MAKE_NONCOPYABLE(ConsoleMessage); WTF_MAKE_FAST_ALLOCATED;
 public:
     ConsoleMessage(bool canGenerateCallStack, MessageSource, MessageType, MessageLevel, const String& message);
-    ConsoleMessage(bool canGenerateCallStack, MessageSource, MessageType, MessageLevel, const String& message, const String& url, unsigned line, ScriptState*, unsigned long requestIdentifier);
+    ConsoleMessage(bool canGenerateCallStack, MessageSource, MessageType, MessageLevel, const String& message, const String& url, unsigned line, unsigned column, ScriptState*, unsigned long requestIdentifier);
     ConsoleMessage(bool canGenerateCallStack, MessageSource, MessageType, MessageLevel, const String& message, PassRefPtr<ScriptCallStack>, unsigned long requestIdentifier);
     ConsoleMessage(bool canGenerateCallStack, MessageSource, MessageType, MessageLevel, const String& message, PassRefPtr<ScriptArguments>, ScriptState*, unsigned long requestIdentifier);
     ~ConsoleMessage();
@@ -83,6 +81,7 @@
     RefPtr<ScriptCallStack> m_callStack;
     String m_url;
     unsigned m_line;
+    unsigned m_column;
     unsigned m_repeatCount;
     String m_requestId;
     double m_timestamp;
diff --git a/Source/core/inspector/ContentSearchUtils.cpp b/Source/core/inspector/ContentSearchUtils.cpp
index 64dc152..86c79ea 100644
--- a/Source/core/inspector/ContentSearchUtils.cpp
+++ b/Source/core/inspector/ContentSearchUtils.cpp
@@ -31,7 +31,6 @@
 #include "core/inspector/ContentSearchUtils.h"
 
 #include "core/platform/text/RegularExpression.h"
-#include <wtf/StdLibExtras.h>
 
 using namespace std;
 
@@ -46,45 +45,28 @@
 static String createSearchRegexSource(const String& text)
 {
     String result;
-    const UChar* characters = text.characters();
     String specials(regexSpecialCharacters);
 
     for (unsigned i = 0; i < text.length(); i++) {
-        if (specials.find(characters[i]) != notFound)
+        if (specials.find(text[i]) != notFound)
             result.append("\\");
-        result.append(characters[i]);
+        result.append(text[i]);
     }
 
     return result;
 }
 
-static inline size_t sizetExtractor(const size_t* value)
-{
-    return *value;
-}
-
-TextPosition textPositionFromOffset(size_t offset, const Vector<size_t>& lineEndings)
-{
-    const size_t* foundLineEnding = approximateBinarySearch<size_t, size_t>(lineEndings, lineEndings.size(), offset, sizetExtractor);
-    size_t lineIndex = foundLineEnding - &lineEndings.at(0);
-    if (offset > *foundLineEnding)
-        ++lineIndex;
-    size_t lineStartOffset = lineIndex > 0 ? lineEndings.at(lineIndex - 1) + 1 : 0;
-    size_t column = offset - lineStartOffset;
-    return TextPosition(OrdinalNumber::fromZeroBasedInt(lineIndex), OrdinalNumber::fromZeroBasedInt(column));
-}
-
 static Vector<pair<int, String> > getRegularExpressionMatchesByLines(const RegularExpression* regex, const String& text)
 {
     Vector<pair<int, String> > result;
     if (text.isEmpty())
         return result;
 
-    OwnPtr<Vector<size_t> > endings(lineEndings(text));
-    size_t size = endings->size();
+    OwnPtr<Vector<unsigned> > endings(lineEndings(text));
+    unsigned size = endings->size();
     unsigned start = 0;
-    for (size_t lineNumber = 0; lineNumber < size; ++lineNumber) {
-        size_t lineEnd = endings->at(lineNumber);
+    for (unsigned lineNumber = 0; lineNumber < size; ++lineNumber) {
+        unsigned lineEnd = endings->at(lineNumber);
         String line = text.substring(start, lineEnd - start);
         if (line.endsWith('\r'))
             line = line.left(line.length() - 1);
@@ -98,24 +80,6 @@
     return result;
 }
 
-PassOwnPtr<Vector<size_t> > lineEndings(const String& text)
-{
-    OwnPtr<Vector<size_t> > result(adoptPtr(new Vector<size_t>()));
-
-    unsigned start = 0;
-    while (start < text.length()) {
-        size_t lineEnd = text.find('\n', start);
-        if (lineEnd == notFound)
-            break;
-
-        result->append(lineEnd);
-        start = lineEnd + 1;
-    }
-    result->append(text.length());
-
-    return result.release();
-}
-
 static PassRefPtr<TypeBuilder::Page::SearchMatch> buildObjectForSearchMatch(int lineNumber, const String& lineContent)
 {
     return TypeBuilder::Page::SearchMatch::create()
diff --git a/Source/core/inspector/ContentSearchUtils.h b/Source/core/inspector/ContentSearchUtils.h
index 6691d39..eb189ae 100644
--- a/Source/core/inspector/ContentSearchUtils.h
+++ b/Source/core/inspector/ContentSearchUtils.h
@@ -38,7 +38,6 @@
 
 namespace WebCore {
 
-class InspectorArray;
 class RegularExpression;
 
 namespace ContentSearchUtils {
@@ -51,8 +50,6 @@
 PassOwnPtr<RegularExpression> createSearchRegex(const String& query, bool caseSensitive, bool isRegex);
 int countRegularExpressionMatches(const RegularExpression*, const String&);
 PassRefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchMatch> > searchInTextByLines(const String& text, const String& query, const bool caseSensitive, const bool isRegex);
-TextPosition textPositionFromOffset(size_t offset, const Vector<size_t>& lineEndings);
-PassOwnPtr<Vector<size_t> > lineEndings(const String&);
 
 String findSourceURL(const String& content, MagicCommentType, bool* deprecated);
 String findSourceMapURL(const String& content, MagicCommentType, bool* deprecated);
diff --git a/Source/core/inspector/DOMEditor.cpp b/Source/core/inspector/DOMEditor.cpp
index 3140edd..55fc766 100644
--- a/Source/core/inspector/DOMEditor.cpp
+++ b/Source/core/inspector/DOMEditor.cpp
@@ -33,6 +33,7 @@
 
 #include "core/inspector/DOMEditor.h"
 
+#include "core/dom/DOMException.h"
 #include "core/dom/Element.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/Node.h"
@@ -399,10 +400,8 @@
 
 static void populateErrorString(const ExceptionCode& ec, ErrorString* errorString)
 {
-    if (ec) {
-        ExceptionCodeDescription description(ec);
-        *errorString = description.name;
-    }
+    if (ec)
+        *errorString = DOMException::getErrorName(ec);
 }
 
 bool DOMEditor::insertBefore(Node* parentNode, PassRefPtr<Node> node, Node* anchorNode, ErrorString* errorString)
diff --git a/Source/core/inspector/HeapGraphSerializer.cpp b/Source/core/inspector/HeapGraphSerializer.cpp
index 41d1824..f159e05 100644
--- a/Source/core/inspector/HeapGraphSerializer.cpp
+++ b/Source/core/inspector/HeapGraphSerializer.cpp
@@ -34,11 +34,11 @@
 #include "core/inspector/HeapGraphSerializer.h"
 
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/MemoryInstrumentationVector.h>
-#include <wtf/MemoryObjectInfo.h>
-#include <wtf/text/CString.h>
-#include <wtf/text/WTFString.h>
+#include "core/inspector/JSONParser.h"
+#include "wtf/MemoryInstrumentationHashMap.h"
+#include "wtf/MemoryInstrumentationVector.h"
+#include "wtf/MemoryObjectInfo.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -49,7 +49,7 @@
     , m_nodeEdgesCount(0)
     , m_nodes(Nodes::create())
     , m_baseToRealNodeIdMap(BaseToRealNodeIdMap::create())
-    , m_typeStrings(InspectorObject::create())
+    , m_typeStrings(JSONObject::create())
     , m_leafCount(0)
 {
     ASSERT(m_client);
@@ -157,7 +157,7 @@
     m_baseToRealNodeIdMap->addItem(toNodeId(real));
 }
 
-PassRefPtr<InspectorObject> HeapGraphSerializer::finish()
+PassRefPtr<JSONObject> HeapGraphSerializer::finish()
 {
     addRootNode();
     pushUpdate();
@@ -189,8 +189,8 @@
             "]"
         "}";
 
-    RefPtr<InspectorValue> metaValue = InspectorValue::parseJSON(metaString);
-    RefPtr<InspectorObject> meta;
+    RefPtr<JSONValue> metaValue = parseJSON(metaString);
+    RefPtr<JSONObject> meta;
     metaValue->asObject(&meta);
     ASSERT(meta);
     meta->setObject("type_strings", m_typeStrings);
diff --git a/Source/core/inspector/HeapGraphSerializer.h b/Source/core/inspector/HeapGraphSerializer.h
index 6669805..e1be9f4 100644
--- a/Source/core/inspector/HeapGraphSerializer.h
+++ b/Source/core/inspector/HeapGraphSerializer.h
@@ -60,7 +60,7 @@
     void reportBaseAddress(const void*, const void*);
     int registerString(const char*);
 
-    PassRefPtr<InspectorObject> finish();
+    PassRefPtr<JSONObject> finish();
 
     void reportMemoryUsage(MemoryObjectInfo*) const;
 
@@ -100,7 +100,7 @@
     Address2NodeId m_address2NodeIdMap;
 
     Vector<const void*> m_roots;
-    RefPtr<InspectorObject> m_typeStrings;
+    RefPtr<JSONObject> m_typeStrings;
 
     size_t m_edgeTypes[WTF::LastMemberTypeEntry];
     int m_unknownClassNameId;
diff --git a/Source/core/inspector/InjectedScript.cpp b/Source/core/inspector/InjectedScript.cpp
index 79b0980..43422c8 100644
--- a/Source/core/inspector/InjectedScript.cpp
+++ b/Source/core/inspector/InjectedScript.cpp
@@ -35,8 +35,8 @@
 
 #include "bindings/v8/ScriptFunctionCall.h"
 #include "core/inspector/InjectedScriptHost.h"
-#include "core/inspector/InspectorValues.h"
-#include <wtf/text/WTFString.h>
+#include "core/platform/JSONValues.h"
+#include "wtf/text/WTFString.h"
 
 using WebCore::TypeBuilder::Array;
 using WebCore::TypeBuilder::Debugger::CallFrame;
@@ -92,19 +92,19 @@
     makeEvalCall(errorString, function, result, wasThrown);
 }
 
-void InjectedScript::restartFrame(ErrorString* errorString, const ScriptValue& callFrames, const String& callFrameId, RefPtr<InspectorObject>* result)
+void InjectedScript::restartFrame(ErrorString* errorString, const ScriptValue& callFrames, const String& callFrameId, RefPtr<JSONObject>* result)
 {
     ScriptFunctionCall function(injectedScriptObject(), "restartFrame");
     function.appendArgument(callFrames);
     function.appendArgument(callFrameId);
-    RefPtr<InspectorValue> resultValue;
+    RefPtr<JSONValue> resultValue;
     makeCall(function, &resultValue);
     if (resultValue) {
-        if (resultValue->type() == InspectorValue::TypeString) {
+        if (resultValue->type() == JSONValue::TypeString) {
             resultValue->asString(errorString);
             return;
         }
-        if (resultValue->type() == InspectorValue::TypeObject) {
+        if (resultValue->type() == JSONValue::TypeObject) {
             *result = resultValue->asObject();
             return;
         }
@@ -129,13 +129,13 @@
     function.appendArgument(scopeNumber);
     function.appendArgument(variableName);
     function.appendArgument(newValueStr);
-    RefPtr<InspectorValue> resultValue;
+    RefPtr<JSONValue> resultValue;
     makeCall(function, &resultValue);
     if (!resultValue) {
         *errorString = "Internal error";
         return;
     }
-    if (resultValue->type() == InspectorValue::TypeString) {
+    if (resultValue->type() == JSONValue::TypeString) {
         resultValue->asString(errorString);
         return;
     }
@@ -146,9 +146,9 @@
 {
     ScriptFunctionCall function(injectedScriptObject(), "getFunctionDetails");
     function.appendArgument(functionId);
-    RefPtr<InspectorValue> resultValue;
+    RefPtr<JSONValue> resultValue;
     makeCall(function, &resultValue);
-    if (!resultValue || resultValue->type() != InspectorValue::TypeObject) {
+    if (!resultValue || resultValue->type() != JSONValue::TypeObject) {
         if (!resultValue->asString(errorString))
             *errorString = "Internal error";
         return;
@@ -163,9 +163,9 @@
     function.appendArgument(ownProperties);
     function.appendArgument(accessorPropertiesOnly);
 
-    RefPtr<InspectorValue> result;
+    RefPtr<JSONValue> result;
     makeCall(function, &result);
-    if (!result || result->type() != InspectorValue::TypeArray) {
+    if (!result || result->type() != JSONValue::TypeArray) {
         *errorString = "Internal error";
         return;
     }
@@ -177,9 +177,9 @@
     ScriptFunctionCall function(injectedScriptObject(), "getInternalProperties");
     function.appendArgument(objectId);
 
-    RefPtr<InspectorValue> result;
+    RefPtr<JSONValue> result;
     makeCall(function, &result);
-    if (!result || result->type() != InspectorValue::TypeArray) {
+    if (!result || result->type() != JSONValue::TypeArray) {
         *errorString = "Internal error";
         return;
     }
@@ -207,7 +207,7 @@
 {
     ScriptFunctionCall function(injectedScriptObject(), "releaseObject");
     function.appendArgument(objectId);
-    RefPtr<InspectorValue> result;
+    RefPtr<JSONValue> result;
     makeCall(function, &result);
 }
 
@@ -219,8 +219,8 @@
     bool hadException = false;
     ScriptValue callFramesValue = callFunctionWithEvalEnabled(function, hadException);
     ASSERT(!hadException);
-    RefPtr<InspectorValue> result = callFramesValue.toInspectorValue(scriptState());
-    if (result->type() == InspectorValue::TypeArray)
+    RefPtr<JSONValue> result = callFramesValue.toJSONValue(scriptState());
+    if (result->type() == JSONValue::TypeArray)
         return Array<CallFrame>::runtimeCast(result);
     return Array<CallFrame>::create();
 }
@@ -237,7 +237,7 @@
     ScriptValue r = callFunctionWithEvalEnabled(wrapFunction, hadException);
     if (hadException)
         return 0;
-    RefPtr<InspectorObject> rawResult = r.toInspectorValue(scriptState())->asObject();
+    RefPtr<JSONObject> rawResult = r.toJSONValue(scriptState())->asObject();
     return TypeBuilder::Runtime::RemoteObject::runtimeCast(rawResult);
 }
 
@@ -255,7 +255,7 @@
     ScriptValue r = callFunctionWithEvalEnabled(wrapFunction, hadException);
     if (hadException)
         return 0;
-    RefPtr<InspectorObject> rawResult = r.toInspectorValue(scriptState())->asObject();
+    RefPtr<JSONObject> rawResult = r.toJSONValue(scriptState())->asObject();
     return TypeBuilder::Runtime::RemoteObject::runtimeCast(rawResult);
 }
 
@@ -281,7 +281,7 @@
     ASSERT(!hasNoValue());
     ScriptFunctionCall function(injectedScriptObject(), "inspectNode");
     function.appendArgument(nodeAsScriptValue(node));
-    RefPtr<InspectorValue> result;
+    RefPtr<JSONValue> result;
     makeCall(function, &result);
 }
 
diff --git a/Source/core/inspector/InjectedScript.h b/Source/core/inspector/InjectedScript.h
index 2e4347b..609efd2 100644
--- a/Source/core/inspector/InjectedScript.h
+++ b/Source/core/inspector/InjectedScript.h
@@ -36,10 +36,7 @@
 #include "core/inspector/InjectedScriptBase.h"
 #include "core/inspector/InjectedScriptManager.h"
 #include "core/inspector/ScriptArguments.h"
-#include <wtf/Forward.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
@@ -79,7 +76,7 @@
                              bool generatePreview,
                              RefPtr<TypeBuilder::Runtime::RemoteObject>* result,
                              TypeBuilder::OptOutput<bool>* wasThrown);
-    void restartFrame(ErrorString*, const ScriptValue& callFrames, const String& callFrameId, RefPtr<InspectorObject>* result);
+    void restartFrame(ErrorString*, const ScriptValue& callFrames, const String& callFrameId, RefPtr<JSONObject>* result);
     void setVariableValue(ErrorString*, const ScriptValue& callFrames, const String* callFrameIdOpt, const String* functionObjectIdOpt, int scopeNumber, const String& variableName, const String& newValueStr);
     void getFunctionDetails(ErrorString*, const String& functionId, RefPtr<TypeBuilder::Debugger::FunctionDetails>* result);
     void getProperties(ErrorString*, const String& objectId, bool ownProperties, bool accessorPropertiesOnly, RefPtr<TypeBuilder::Array<TypeBuilder::Runtime::PropertyDescriptor> >* result);
diff --git a/Source/core/inspector/InjectedScriptBase.cpp b/Source/core/inspector/InjectedScriptBase.cpp
index 1ffa72f..2f246a8 100644
--- a/Source/core/inspector/InjectedScriptBase.cpp
+++ b/Source/core/inspector/InjectedScriptBase.cpp
@@ -35,8 +35,8 @@
 
 #include "bindings/v8/ScriptFunctionCall.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/inspector/InspectorValues.h"
-#include <wtf/text/WTFString.h>
+#include "core/platform/JSONValues.h"
+#include "wtf/text/WTFString.h"
 
 using WebCore::TypeBuilder::Runtime::RemoteObject;
 
@@ -94,10 +94,10 @@
     return resultValue;
 }
 
-void InjectedScriptBase::makeCall(ScriptFunctionCall& function, RefPtr<InspectorValue>* result)
+void InjectedScriptBase::makeCall(ScriptFunctionCall& function, RefPtr<JSONValue>* result)
 {
     if (hasNoValue() || !canAccessInspectedWindow()) {
-        *result = InspectorValue::null();
+        *result = JSONValue::null();
         return;
     }
 
@@ -106,32 +106,33 @@
 
     ASSERT(!hadException);
     if (!hadException) {
-        *result = resultValue.toInspectorValue(m_injectedScriptObject.scriptState());
+        *result = resultValue.toJSONValue(m_injectedScriptObject.scriptState());
         if (!*result)
-            *result = InspectorString::create(String::format("Object has too long reference chain(must not be longer than %d)", InspectorValue::maxDepth));
-    } else
-        *result = InspectorString::create("Exception while making a call.");
+            *result = JSONString::create(String::format("Object has too long reference chain(must not be longer than %d)", JSONValue::maxDepth));
+    } else {
+        *result = JSONString::create("Exception while making a call.");
+    }
 }
 
 void InjectedScriptBase::makeEvalCall(ErrorString* errorString, ScriptFunctionCall& function, RefPtr<TypeBuilder::Runtime::RemoteObject>* objectResult, TypeBuilder::OptOutput<bool>* wasThrown)
 {
-    RefPtr<InspectorValue> result;
+    RefPtr<JSONValue> result;
     makeCall(function, &result);
     if (!result) {
         *errorString = "Internal error: result value is empty";
         return;
     }
-    if (result->type() == InspectorValue::TypeString) {
+    if (result->type() == JSONValue::TypeString) {
         result->asString(errorString);
         ASSERT(errorString->length());
         return;
     }
-    RefPtr<InspectorObject> resultPair = result->asObject();
+    RefPtr<JSONObject> resultPair = result->asObject();
     if (!resultPair) {
         *errorString = "Internal error: result is not an Object";
         return;
     }
-    RefPtr<InspectorObject> resultObj = resultPair->getObject("result");
+    RefPtr<JSONObject> resultObj = resultPair->getObject("result");
     bool wasThrownVal = false;
     if (!resultObj || !resultPair->getBoolean("wasThrown", &wasThrownVal)) {
         *errorString = "Internal error: result is not a pair of value and wasThrown flag";
diff --git a/Source/core/inspector/InjectedScriptBase.h b/Source/core/inspector/InjectedScriptBase.h
index 17b8ca3..194d022 100644
--- a/Source/core/inspector/InjectedScriptBase.h
+++ b/Source/core/inspector/InjectedScriptBase.h
@@ -33,12 +33,11 @@
 
 #include "InspectorTypeBuilder.h"
 #include "bindings/v8/ScriptObject.h"
-#include <wtf/Forward.h>
-#include <wtf/RefPtr.h>
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
-class InspectorValue;
+class JSONValue;
 class ScriptFunctionCall;
 
 typedef String ErrorString;
@@ -61,7 +60,7 @@
     bool canAccessInspectedWindow() const;
     const ScriptObject& injectedScriptObject() const;
     ScriptValue callFunctionWithEvalEnabled(ScriptFunctionCall&, bool& hadException) const;
-    void makeCall(ScriptFunctionCall&, RefPtr<InspectorValue>* result);
+    void makeCall(ScriptFunctionCall&, RefPtr<JSONValue>* result);
     void makeEvalCall(ErrorString*, ScriptFunctionCall&, RefPtr<TypeBuilder::Runtime::RemoteObject>* result, TypeBuilder::OptOutput<bool>* wasThrown);
 
 private:
diff --git a/Source/core/inspector/InjectedScriptCanvasModule.cpp b/Source/core/inspector/InjectedScriptCanvasModule.cpp
index 618fee6..ec892d4 100644
--- a/Source/core/inspector/InjectedScriptCanvasModule.cpp
+++ b/Source/core/inspector/InjectedScriptCanvasModule.cpp
@@ -29,8 +29,6 @@
  */
 
 #include "config.h"
-
-
 #include "core/inspector/InjectedScriptCanvasModule.h"
 
 #include "InjectedScriptCanvasModuleSource.h"
@@ -43,6 +41,7 @@
 using WebCore::TypeBuilder::Canvas::ResourceState;
 using WebCore::TypeBuilder::Canvas::TraceLog;
 using WebCore::TypeBuilder::Canvas::TraceLogId;
+using WebCore::TypeBuilder::Runtime::RemoteObject;
 
 namespace WebCore {
 
@@ -89,7 +88,7 @@
 void InjectedScriptCanvasModule::markFrameEnd()
 {
     ScriptFunctionCall function(injectedScriptObject(), "markFrameEnd");
-    RefPtr<InspectorValue> resultValue;
+    RefPtr<JSONValue> resultValue;
     makeCall(function, &resultValue);
     ASSERT(resultValue);
 }
@@ -107,9 +106,9 @@
 void InjectedScriptCanvasModule::callStartCapturingFunction(const String& functionName, ErrorString* errorString, TraceLogId* traceLogId)
 {
     ScriptFunctionCall function(injectedScriptObject(), functionName);
-    RefPtr<InspectorValue> resultValue;
+    RefPtr<JSONValue> resultValue;
     makeCall(function, &resultValue);
-    if (!resultValue || resultValue->type() != InspectorValue::TypeString || !resultValue->asString(traceLogId))
+    if (!resultValue || resultValue->type() != JSONValue::TypeString || !resultValue->asString(traceLogId))
         *errorString = "Internal error: " + functionName;
 }
 
@@ -142,9 +141,9 @@
         function.appendArgument(*startOffset);
     if (maxLength)
         function.appendArgument(*maxLength);
-    RefPtr<InspectorValue> resultValue;
+    RefPtr<JSONValue> resultValue;
     makeCall(function, &resultValue);
-    if (!resultValue || resultValue->type() != InspectorValue::TypeObject) {
+    if (!resultValue || resultValue->type() != JSONValue::TypeObject) {
         if (!resultValue->asString(errorString))
             *errorString = "Internal error: traceLog";
         return;
@@ -157,9 +156,9 @@
     ScriptFunctionCall function(injectedScriptObject(), "replayTraceLog");
     function.appendArgument(traceLogId);
     function.appendArgument(stepNo);
-    RefPtr<InspectorValue> resultValue;
+    RefPtr<JSONValue> resultValue;
     makeCall(function, &resultValue);
-    if (!resultValue || resultValue->type() != InspectorValue::TypeObject) {
+    if (!resultValue || resultValue->type() != JSONValue::TypeObject) {
         if (!resultValue->asString(errorString))
             *errorString = "Internal error: replayTraceLog";
         return;
@@ -171,9 +170,9 @@
 {
     ScriptFunctionCall function(injectedScriptObject(), "resourceInfo");
     function.appendArgument(resourceId);
-    RefPtr<InspectorValue> resultValue;
+    RefPtr<JSONValue> resultValue;
     makeCall(function, &resultValue);
-    if (!resultValue || resultValue->type() != InspectorValue::TypeObject) {
+    if (!resultValue || resultValue->type() != JSONValue::TypeObject) {
         if (!resultValue->asString(errorString))
             *errorString = "Internal error: resourceInfo";
         return;
@@ -186,9 +185,9 @@
     ScriptFunctionCall function(injectedScriptObject(), "resourceState");
     function.appendArgument(traceLogId);
     function.appendArgument(resourceId);
-    RefPtr<InspectorValue> resultValue;
+    RefPtr<JSONValue> resultValue;
     makeCall(function, &resultValue);
-    if (!resultValue || resultValue->type() != InspectorValue::TypeObject) {
+    if (!resultValue || resultValue->type() != JSONValue::TypeObject) {
         if (!resultValue->asString(errorString))
             *errorString = "Internal error: resourceState";
         return;
@@ -196,5 +195,29 @@
     *result = ResourceState::runtimeCast(resultValue);
 }
 
-} // namespace WebCore
+void InjectedScriptCanvasModule::evaluateTraceLogCallArgument(ErrorString* errorString, const TraceLogId& traceLogId, int callIndex, int argumentIndex, const String& objectGroup, RefPtr<RemoteObject>* result, RefPtr<ResourceState>* resourceState)
+{
+    ScriptFunctionCall function(injectedScriptObject(), "evaluateTraceLogCallArgument");
+    function.appendArgument(traceLogId);
+    function.appendArgument(callIndex);
+    function.appendArgument(argumentIndex);
+    function.appendArgument(objectGroup);
+    RefPtr<JSONValue> resultValue;
+    makeCall(function, &resultValue);
+    if (!resultValue || resultValue->type() != JSONValue::TypeObject) {
+        if (!resultValue->asString(errorString))
+            *errorString = "Internal error: evaluateTraceLogCallArgument";
+        return;
+    }
+    RefPtr<JSONObject> resultObject = resultValue->asObject();
+    RefPtr<JSONObject> remoteObject = resultObject->getObject("result");
+    if (remoteObject)
+        *result = RemoteObject::runtimeCast(remoteObject);
+    RefPtr<JSONObject> resourceStateObject = resultObject->getObject("resourceState");
+    if (resourceStateObject)
+        *resourceState = ResourceState::runtimeCast(resourceStateObject);
+    if (!remoteObject && !resourceStateObject)
+        *errorString = "Internal error: no result and no resource state";
+}
 
+} // namespace WebCore
diff --git a/Source/core/inspector/InjectedScriptCanvasModule.h b/Source/core/inspector/InjectedScriptCanvasModule.h
index 8999373..c34aab8 100644
--- a/Source/core/inspector/InjectedScriptCanvasModule.h
+++ b/Source/core/inspector/InjectedScriptCanvasModule.h
@@ -33,7 +33,7 @@
 
 #include "bindings/v8/ScriptState.h"
 #include "core/inspector/InjectedScriptModule.h"
-#include <wtf/text/WTFString.h>
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -61,6 +61,7 @@
     void replayTraceLog(ErrorString*, const TypeBuilder::Canvas::TraceLogId&, int, RefPtr<TypeBuilder::Canvas::ResourceState>*);
     void resourceInfo(ErrorString*, const TypeBuilder::Canvas::ResourceId&, RefPtr<TypeBuilder::Canvas::ResourceInfo>*);
     void resourceState(ErrorString*, const TypeBuilder::Canvas::TraceLogId&, const TypeBuilder::Canvas::ResourceId&, RefPtr<TypeBuilder::Canvas::ResourceState>*);
+    void evaluateTraceLogCallArgument(ErrorString*, const TypeBuilder::Canvas::TraceLogId&, int, int, const String&, RefPtr<TypeBuilder::Runtime::RemoteObject>*, RefPtr<TypeBuilder::Canvas::ResourceState>*);
 
 private:
     ScriptObject callWrapContextFunction(const String&, const ScriptObject&);
diff --git a/Source/core/inspector/InjectedScriptCanvasModuleSource.js b/Source/core/inspector/InjectedScriptCanvasModuleSource.js
index ffc22b0..98c489e 100644
--- a/Source/core/inspector/InjectedScriptCanvasModuleSource.js
+++ b/Source/core/inspector/InjectedScriptCanvasModuleSource.js
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -29,11 +29,12 @@
  */
 
 /**
- * @param {InjectedScriptHost} InjectedScriptHost
+ * @param {InjectedScriptHostClass} InjectedScriptHost
  * @param {Window} inspectedWindow
  * @param {number} injectedScriptId
+ * @param {!InjectedScript} injectedScript
  */
-(function (InjectedScriptHost, inspectedWindow, injectedScriptId) {
+(function (InjectedScriptHost, inspectedWindow, injectedScriptId, injectedScript) {
 
 var TypeUtils = {
     /**
@@ -542,6 +543,24 @@
     },
 
     /**
+     * @return {string}
+     */
+    propertyName: function()
+    {
+        console.assert(this.isPropertySetter());
+        return /** @type {string} */ (this._args[0]);
+    },
+
+    /**
+     * @return {*}
+     */
+    propertyValue: function()
+    {
+        console.assert(this.isPropertySetter());
+        return this._args[1];
+    },
+
+    /**
      * @return {Array.<ReplayableResource|*>}
      */
     args: function()
@@ -583,7 +602,7 @@
     },
 
     /**
-     * @param {Cache} cache
+     * @param {!Cache} cache
      * @return {!Call}
      */
     replay: function(cache)
@@ -2663,8 +2682,8 @@
             if (this._drawingMethodNames[functionName])
                 result.isDrawingCall = true;
         } else {
-            result.property = replayableCall.args()[0];
-            result.value = this.formatValue(replayableCall.args()[1]);
+            result.property = replayableCall.propertyName();
+            result.value = this.formatValue(replayableCall.propertyValue());
         }
         return result;
     },
@@ -2675,11 +2694,23 @@
      */
     formatValue: function(value)
     {
-        if (value instanceof ReplayableResource)
-            var description = value.description();
-        else
-            var description = "" + value;
-        return { description: description };
+        if (value instanceof ReplayableResource) {
+            return {
+                description: value.description(),
+                resourceId: CallFormatter.makeStringResourceId(value.id())
+            };
+        }
+
+        var remoteObject = injectedScript.wrapObject(value, "", true, false);
+        var result = {
+            description: remoteObject.description || ("" + value),
+            type: /** @type {CanvasAgent.CallArgumentType} */ (remoteObject.type)
+        };
+        if (remoteObject.subtype)
+            result.subtype = /** @type {CanvasAgent.CallArgumentSubtype} */ (remoteObject.subtype);
+        if (remoteObject.objectId)
+            injectedScript.releaseObject(remoteObject.objectId);
+        return result;
     }
 }
 
@@ -2714,6 +2745,15 @@
 }
 
 /**
+ * @param {number} resourceId
+ * @return {CanvasAgent.ResourceId}
+ */
+CallFormatter.makeStringResourceId = function(resourceId)
+{
+    return "{\"injectedScriptId\":" + injectedScriptId + ",\"resourceId\":" + resourceId + "}";
+}
+
+/**
  * @constructor
  * @extends {CallFormatter}
  * @param {!Object.<string, boolean>} drawingMethodNames
@@ -2761,12 +2801,12 @@
     {"aname": "getBufferParameter", "enum": [0, 1]},
     {"aname": "getError", "hints": ["NO_ERROR"], "returnType": "enum"},
     {"aname": "getFramebufferAttachmentParameter", "enum": [0, 1, 2]},
-    {"aname": "getParameter", "enum": [0], "hints": ["ZERO", "ONE"]},
+    {"aname": "getParameter", "enum": [0]},
     {"aname": "getProgramParameter", "enum": [1]},
     {"aname": "getRenderbufferParameter", "enum": [0, 1]},
     {"aname": "getShaderParameter", "enum": [1]},
     {"aname": "getShaderPrecisionFormat", "enum": [0, 1]},
-    {"aname": "getTexParameter", "enum": [0, 1]},
+    {"aname": "getTexParameter", "enum": [0, 1], "returnType": "enum"},
     {"aname": "getVertexAttrib", "enum": [1]},
     {"aname": "getVertexAttribOffset", "enum": [1]},
     {"aname": "hint", "enum": [0, 1]},
@@ -3408,7 +3448,7 @@
             var stackTrace = call.stackTrace();
             var callFrame = stackTrace ? stackTrace.callFrame(0) || {} : {};
             var item = CallFormatter.formatCall(call);
-            item.contextId = this._makeStringResourceId(contextResource.id());
+            item.contextId = CallFormatter.makeStringResourceId(contextResource.id());
             item.sourceURL = callFrame.sourceURL;
             item.lineNumber = callFrame.lineNumber;
             item.columnNumber = callFrame.columnNumber;
@@ -3419,19 +3459,6 @@
     },
 
     /**
-     * @param {*} obj
-     * @return {!CanvasAgent.CallArgument}
-     */
-    _makeCallArgument: function(obj)
-    {
-        if (obj instanceof ReplayableResource)
-            var description = obj.description();
-        else
-            var description = "" + obj;
-        return { description: description };
-    },
-
-    /**
      * @param {CanvasAgent.TraceLogId} traceLogId
      * @param {number} stepNo
      * @return {!CanvasAgent.ResourceState|string}
@@ -3449,7 +3476,7 @@
             resource = resource.contextResource();
             dataURL = resource.toDataURL();
         }
-        return this._makeResourceState(this._makeStringResourceId(resource.id()), traceLogId, dataURL);
+        return this._makeResourceState(CallFormatter.makeStringResourceId(resource.id()), traceLogId, dataURL);
     },
 
     /**
@@ -3506,6 +3533,46 @@
     },
 
     /**
+     * @param {CanvasAgent.TraceLogId} traceLogId
+     * @param {number} callIndex
+     * @param {number} argumentIndex
+     * @param {string} objectGroup
+     * @return {!Object|string}
+     */
+    evaluateTraceLogCallArgument: function(traceLogId, callIndex, argumentIndex, objectGroup)
+    {
+        var traceLog = this._traceLogs[traceLogId];
+        if (!traceLog)
+            return "Error: Trace log with the given ID not found.";
+
+        var replayableCall = traceLog.replayableCalls()[callIndex];
+        if (!replayableCall)
+            return "Error: No call found at index " + callIndex;
+
+        var value;
+        if (replayableCall.isPropertySetter())
+            value = replayableCall.propertyValue();
+        else if (argumentIndex === -1)
+            value = replayableCall.result();
+        else {
+            var args = replayableCall.args();
+            if (argumentIndex < 0 || argumentIndex >= args.length)
+                return "Error: No argument found at index " + argumentIndex + " for call at index " + callIndex;
+            value = args[argumentIndex];
+        }
+
+        if (value instanceof ReplayableResource) {
+            var traceLogPlayer = this._traceLogPlayers[traceLogId];
+            var resource = traceLogPlayer && traceLogPlayer.replayWorldResource(value.id());
+            var resourceState = this._makeResourceState(CallFormatter.makeStringResourceId(value.id()), traceLogId, resource ? resource.toDataURL() : "");
+            return { resourceState: resourceState };
+        }
+
+        var remoteObject = injectedScript.wrapObject(value, objectGroup, true, false);
+        return { result: remoteObject };
+    },
+
+    /**
      * @return {CanvasAgent.TraceLogId}
      */
     _makeTraceLogId: function()
@@ -3514,15 +3581,6 @@
     },
 
     /**
-     * @param {number} resourceId
-     * @return {CanvasAgent.ResourceId}
-     */
-    _makeStringResourceId: function(resourceId)
-    {
-        return "{\"injectedScriptId\":" + injectedScriptId + ",\"resourceId\":" + resourceId + "}";
-    },
-
-    /**
      * @param {CanvasAgent.ResourceId} stringResourceId
      * @param {string} description
      * @return {!CanvasAgent.ResourceInfo}
diff --git a/Source/core/inspector/InjectedScriptExterns.js b/Source/core/inspector/InjectedScriptExterns.js
index 3306627..3076568 100644
--- a/Source/core/inspector/InjectedScriptExterns.js
+++ b/Source/core/inspector/InjectedScriptExterns.js
@@ -38,78 +38,76 @@
 /**
  * @constructor
  */
-function InjectedScriptHost() { }
-InjectedScriptHost.prototype.storageId = function(object) { }
-InjectedScriptHost.prototype.getInternalProperties = function(object) { }
+function InjectedScriptHostClass() { }
+InjectedScriptHostClass.prototype.storageId = function(object) { }
+InjectedScriptHostClass.prototype.getInternalProperties = function(object) { }
 /**
  * @param {Function} func
  */
-InjectedScriptHost.prototype.functionDetails = function(func) { }
+InjectedScriptHostClass.prototype.functionDetails = function(func) { }
 /**
  * @param {*} object
  */
-InjectedScriptHost.prototype.isHTMLAllCollection = function(object) { }
+InjectedScriptHostClass.prototype.isHTMLAllCollection = function(object) { }
 /**
  * @param {*} object
  */
-InjectedScriptHost.prototype.internalConstructorName = function(object) { }
+InjectedScriptHostClass.prototype.internalConstructorName = function(object) { }
 /**
  * @param {*} object
  */
-InjectedScriptHost.prototype.copyText = function(object) { }
-InjectedScriptHost.prototype.clearConsoleMessages = function() { }
+InjectedScriptHostClass.prototype.copyText = function(object) { }
+InjectedScriptHostClass.prototype.clearConsoleMessages = function() { }
 /**
  * @param {number} index
  */
-InjectedScriptHost.prototype.inspectedObject = function(index) { }
+InjectedScriptHostClass.prototype.inspectedObject = function(index) { }
 /**
  * @param {*} object
  * @return {number}
  */
-InjectedScriptHost.prototype.objectId = function(object) { }
+InjectedScriptHostClass.prototype.objectId = function(object) { }
 /**
  * @param {*} object
  */
-InjectedScriptHost.prototype.releaseObjectId = function(object) { }
+InjectedScriptHostClass.prototype.releaseObjectId = function(object) { }
 /**
  * @param {*} object
  */
-InjectedScriptHost.prototype.databaseId = function(object) { }
+InjectedScriptHostClass.prototype.databaseId = function(object) { }
 /**
  * @param {*} object
  * @param {Object} hints
  */
-InjectedScriptHost.prototype.inspect = function(object, hints) { }
+InjectedScriptHostClass.prototype.inspect = function(object, hints) { }
 /**
  * @param {*} object
  */
-InjectedScriptHost.prototype.type = function(object) { }
+InjectedScriptHostClass.prototype.type = function(object) { }
 /**
  * @param {*} object
  */
-InjectedScriptHost.prototype.getEventListeners = function(object) { }
+InjectedScriptHostClass.prototype.getEventListeners = function(object) { }
 /**
  * @param {string} expression
  */
-InjectedScriptHost.prototype.evaluate = function(expression) { }
+InjectedScriptHostClass.prototype.evaluate = function(expression) { }
 /**
  * @param {*} fn
  */
-InjectedScriptHost.prototype.debugFunction = function(fn) { }
+InjectedScriptHostClass.prototype.debugFunction = function(fn) { }
 /**
  * @param {*} fn
  */
-InjectedScriptHost.prototype.undebugFunction = function(fn) { }
+InjectedScriptHostClass.prototype.undebugFunction = function(fn) { }
 /**
  * @param {*} fn
  */
-InjectedScriptHost.prototype.monitorFunction = function(fn) { }
+InjectedScriptHostClass.prototype.monitorFunction = function(fn) { }
 /**
  * @param {*} fn
  */
-InjectedScriptHost.prototype.unmonitorFunction = function(fn) { }
-
-
+InjectedScriptHostClass.prototype.unmonitorFunction = function(fn) { }
 
 /**
  * @param {function(...)} fun
@@ -117,7 +115,14 @@
  * @param {string} variableName
  * @param {*} newValue
  */
-InjectedScriptHost.prototype.setFunctionVariableValue = function(fun, scopeNumber, variableName, newValue) { }
+InjectedScriptHostClass.prototype.setFunctionVariableValue = function(fun, scopeNumber, variableName, newValue) { }
+
+/** @type {!InjectedScriptHostClass} */
+var InjectedScriptHost;
+/** @type {!Window} */
+var inspectedWindow;
+/** @type {number} */
+var injectedScriptId;
 
 /**
  * @constructor
diff --git a/Source/core/inspector/InjectedScriptHost.cpp b/Source/core/inspector/InjectedScriptHost.cpp
index bafd14c..778221f 100644
--- a/Source/core/inspector/InjectedScriptHost.cpp
+++ b/Source/core/inspector/InjectedScriptHost.cpp
@@ -37,12 +37,11 @@
 #include "core/inspector/InspectorDOMStorageAgent.h"
 #include "core/inspector/InspectorDatabaseAgent.h"
 #include "core/inspector/InspectorDebuggerAgent.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/inspector/InstrumentingAgents.h"
+#include "core/platform/JSONValues.h"
 #include "core/platform/Pasteboard.h"
 
 #include "wtf/RefPtr.h"
-#include "wtf/StdLibExtras.h"
 #include "wtf/text/StringBuilder.h"
 
 using namespace std;
@@ -72,7 +71,7 @@
     m_scriptDebugServer = 0;
 }
 
-void InjectedScriptHost::inspectImpl(PassRefPtr<InspectorValue> object, PassRefPtr<InspectorValue> hints)
+void InjectedScriptHost::inspectImpl(PassRefPtr<JSONValue> object, PassRefPtr<JSONValue> hints)
 {
     if (InspectorAgent* inspectorAgent = m_instrumentingAgents ? m_instrumentingAgents->inspectorAgent() : 0) {
         RefPtr<TypeBuilder::Runtime::RemoteObject> remoteObject = TypeBuilder::Runtime::RemoteObject::runtimeCast(object);
diff --git a/Source/core/inspector/InjectedScriptHost.h b/Source/core/inspector/InjectedScriptHost.h
index 01cc55c..6a3729c 100644
--- a/Source/core/inspector/InjectedScriptHost.h
+++ b/Source/core/inspector/InjectedScriptHost.h
@@ -32,16 +32,15 @@
 
 #include "bindings/v8/ScriptState.h"
 #include "bindings/v8/ScriptWrappable.h"
-#include "core/page/ConsoleTypes.h"
-#include <wtf/RefCounted.h>
-#include <wtf/Vector.h>
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
 class Database;
 class InjectedScript;
-class InspectorValue;
 class InstrumentingAgents;
+class JSONValue;
 class Node;
 class ScriptDebugServer;
 class ScriptValue;
@@ -80,7 +79,7 @@
     void clearInspectedObjects();
     InspectableObject* inspectedObject(unsigned int num);
 
-    void inspectImpl(PassRefPtr<InspectorValue> objectToInspect, PassRefPtr<InspectorValue> hints);
+    void inspectImpl(PassRefPtr<JSONValue> objectToInspect, PassRefPtr<JSONValue> hints);
     void getEventListenersImpl(Node*, Vector<EventListenerInfo>& listenersArray);
 
     void clearConsoleMessages();
diff --git a/Source/core/inspector/InjectedScriptManager.cpp b/Source/core/inspector/InjectedScriptManager.cpp
index 16dd077..d7cec01 100644
--- a/Source/core/inspector/InjectedScriptManager.cpp
+++ b/Source/core/inspector/InjectedScriptManager.cpp
@@ -35,8 +35,9 @@
 #include "bindings/v8/ScriptObject.h"
 #include "core/inspector/InjectedScript.h"
 #include "core/inspector/InjectedScriptHost.h"
-#include "core/inspector/InspectorValues.h"
-#include <wtf/PassOwnPtr.h>
+#include "core/inspector/JSONParser.h"
+#include "core/platform/JSONValues.h"
+#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
@@ -47,7 +48,7 @@
 
 PassOwnPtr<InjectedScriptManager> InjectedScriptManager::createForWorker()
 {
-    return adoptPtr(new InjectedScriptManager(&InjectedScriptManager::canAccessInspectedWorkerContext));
+    return adoptPtr(new InjectedScriptManager(&InjectedScriptManager::canAccessInspectedWorkerGlobalScope));
 }
 
 InjectedScriptManager::InjectedScriptManager(InspectedStateAccessCheck accessCheck)
@@ -96,8 +97,8 @@
 
 InjectedScript InjectedScriptManager::injectedScriptForObjectId(const String& objectId)
 {
-    RefPtr<InspectorValue> parsedObjectId = InspectorValue::parseJSON(objectId);
-    if (parsedObjectId && parsedObjectId->type() == InspectorValue::TypeObject) {
+    RefPtr<JSONValue> parsedObjectId = parseJSON(objectId);
+    if (parsedObjectId && parsedObjectId->type() == JSONValue::TypeObject) {
         long injectedScriptId = 0;
         bool success = parsedObjectId->asObject()->getNumber("injectedScriptId", &injectedScriptId);
         if (success)
@@ -141,7 +142,7 @@
         m_scriptStateToId.remove(scriptStatesToRemove[i]);
 }
 
-bool InjectedScriptManager::canAccessInspectedWorkerContext(ScriptState*)
+bool InjectedScriptManager::canAccessInspectedWorkerGlobalScope(ScriptState*)
 {
     return true;
 }
diff --git a/Source/core/inspector/InjectedScriptManager.h b/Source/core/inspector/InjectedScriptManager.h
index 07faa59..6bd5958 100644
--- a/Source/core/inspector/InjectedScriptManager.h
+++ b/Source/core/inspector/InjectedScriptManager.h
@@ -40,7 +40,6 @@
 class DOMWindow;
 class InjectedScript;
 class InjectedScriptHost;
-class InspectorObject;
 class ScriptObject;
 
 class InjectedScriptManager {
@@ -73,7 +72,7 @@
     ScriptObject createInjectedScript(const String& source, ScriptState*, int id);
 
     static bool canAccessInspectedWindow(ScriptState*);
-    static bool canAccessInspectedWorkerContext(ScriptState*);
+    static bool canAccessInspectedWorkerGlobalScope(ScriptState*);
 
     int m_nextInjectedScriptId;
     typedef HashMap<int, InjectedScript> IdToInjectedScriptMap;
diff --git a/Source/core/inspector/InjectedScriptSource.js b/Source/core/inspector/InjectedScriptSource.js
index 5875cc7..c59c45e 100644
--- a/Source/core/inspector/InjectedScriptSource.js
+++ b/Source/core/inspector/InjectedScriptSource.js
@@ -1,5 +1,6 @@
 /*
  * Copyright (C) 2007 Apple Inc.  All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -33,8 +34,11 @@
  */
 (function (InjectedScriptHost, inspectedWindow, injectedScriptId) {
 
-// Protect against Object overwritten by the user code.
-var Object = {}.constructor;
+/**
+ * Protect against Object overwritten by the user code.
+ * @suppress {duplicate}
+ */
+var Object = /** @type {function(new:Object, *=)} */ ({}.constructor);
 
 /**
  * @param {Arguments} array
@@ -407,6 +411,8 @@
                             continue;
                     } else {
                         // Not all bindings provide proper descriptors. Fall back to the writable, configurable property.
+                        if (accessorPropertiesOnly)
+                            continue;
                         try {
                             descriptor = { name: name, value: o[name], writable: false, configurable: false, enumerable: false};
                             if (o === object) 
@@ -418,6 +424,8 @@
                         continue;
                     }
                 } catch (e) {
+                    if (accessorPropertiesOnly)
+                        continue;
                     var descriptor = {};
                     descriptor.value = e;
                     descriptor.wasThrown = true;
@@ -429,7 +437,7 @@
                 descriptors.push(descriptor);
             }
             if (ownProperties) {
-                if (object.__proto__)
+                if (object.__proto__ && !accessorPropertiesOnly)
                     descriptors.push({ name: "__proto__", value: object.__proto__, writable: true, configurable: true, enumerable: false, isOwn: true});
                 break;
             }
@@ -650,7 +658,7 @@
                 return "Could not find call frame with given id";
             setter = callFrame.setVariableValue.bind(callFrame);    
         } else {
-            var parsedFunctionId = this._parseObjectId(/** @type {string} */(functionObjectId));
+            var parsedFunctionId = this._parseObjectId(/** @type {string} */ (functionObjectId));
             var func = this._objectForId(parsedFunctionId);
             if (typeof func !== "function")
                 return "Cannot resolve function by id.";
@@ -744,7 +752,7 @@
             inspectedWindow.console.error("Web Inspector error: A function was expected for module %s evaluation", name);
             return null;
         }
-        var module = moduleFunction.call(inspectedWindow, InjectedScriptHost, inspectedWindow, injectedScriptId);
+        var module = moduleFunction.call(inspectedWindow, InjectedScriptHost, inspectedWindow, injectedScriptId, this);
         this._modules[name] = module;
         return module;
     },
@@ -769,7 +777,7 @@
     },
 
     /**
-     * @param {Object=} obj
+     * @param {*} obj
      * @return {string?}
      */
     _subtype: function(obj)
@@ -809,8 +817,6 @@
         if (this.isPrimitiveValue(obj))
             return null;
 
-        obj = /** @type {Object} */ (obj);
-
         // Type is object, get subtype.
         var subtype = this._subtype(obj);
 
@@ -868,7 +874,7 @@
 }
 
 /**
- * @type {InjectedScript}
+ * @type {!InjectedScript}
  * @const
  */
 var injectedScript = new InjectedScript();
@@ -886,15 +892,15 @@
     this.type = typeof object;
     if (injectedScript.isPrimitiveValue(object) || object === null || forceValueType) {
         // We don't send undefined values over JSON.
-        if (typeof object !== "undefined")
+        if (this.type !== "undefined")
             this.value = object;
 
-        // Null object is object with 'null' subtype'
+        // Null object is object with 'null' subtype.
         if (object === null)
             this.subtype = "null";
 
         // Provide user-friendly number values.
-        if (typeof object === "number")
+        if (this.type === "number")
             this.description = object + "";
         return;
     }
@@ -947,7 +953,7 @@
      */
     _generateProtoPreview: function(object, preview, propertiesThreshold, firstLevelKeys, secondLevelKeys)
     {
-        var propertyNames = firstLevelKeys ? firstLevelKeys : Object.keys(/** @type {!Object} */(object));
+        var propertyNames = firstLevelKeys ? firstLevelKeys : Object.keys(/** @type {!Object} */ (object));
         try {
             for (var i = 0; i < propertyNames.length; ++i) {
                 if (!propertiesThreshold.properties || !propertiesThreshold.indexes) {
@@ -959,7 +965,7 @@
                 if (this.subtype === "array" && name === "length")
                     continue;
 
-                var descriptor = Object.getOwnPropertyDescriptor(/** @type {!Object} */(object), name);
+                var descriptor = Object.getOwnPropertyDescriptor(/** @type {!Object} */ (object), name);
                 if (!("value" in descriptor) || !descriptor.enumerable) {
                     preview.lossless = false;
                     continue;
diff --git a/Source/core/inspector/InspectorAgent.cpp b/Source/core/inspector/InspectorAgent.cpp
index ee2b455..e6933cb 100644
--- a/Source/core/inspector/InspectorAgent.cpp
+++ b/Source/core/inspector/InspectorAgent.cpp
@@ -31,8 +31,6 @@
 #include "config.h"
 #include "core/inspector/InspectorAgent.h"
 
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
 #include "InspectorFrontend.h"
 #include "bindings/v8/DOMWrapperWorld.h"
 #include "bindings/v8/ScriptController.h"
@@ -41,11 +39,11 @@
 #include "core/inspector/InjectedScriptManager.h"
 #include "core/inspector/InspectorController.h"
 #include "core/inspector/InspectorState.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
+#include "core/platform/JSONValues.h"
 #include "weborigin/SecurityOrigin.h"
 
 using namespace std;
@@ -162,7 +160,7 @@
     m_injectedScriptForOrigin.set(origin, source);
 }
 
-void InspectorAgent::inspect(PassRefPtr<TypeBuilder::Runtime::RemoteObject> objectToInspect, PassRefPtr<InspectorObject> hints)
+void InspectorAgent::inspect(PassRefPtr<TypeBuilder::Runtime::RemoteObject> objectToInspect, PassRefPtr<JSONObject> hints)
 {
     if (m_state->getBoolean(InspectorAgentState::inspectorAgentEnabled) && m_frontend) {
         m_frontend->inspector()->inspect(objectToInspect, hints);
diff --git a/Source/core/inspector/InspectorAgent.h b/Source/core/inspector/InspectorAgent.h
index a84d9b6..d1e56c1 100644
--- a/Source/core/inspector/InspectorAgent.h
+++ b/Source/core/inspector/InspectorAgent.h
@@ -44,8 +44,8 @@
 class Frame;
 class InjectedScriptManager;
 class InspectorFrontend;
-class InspectorObject;
 class InstrumentingAgents;
+class JSONObject;
 class KURL;
 class Page;
 
@@ -86,7 +86,7 @@
 
     void setInjectedScriptForOrigin(const String& origin, const String& source);
 
-    void inspect(PassRefPtr<TypeBuilder::Runtime::RemoteObject> objectToInspect, PassRefPtr<InspectorObject> hints);
+    void inspect(PassRefPtr<TypeBuilder::Runtime::RemoteObject> objectToInspect, PassRefPtr<JSONObject> hints);
 
 private:
     InspectorAgent(Page*, InjectedScriptManager*, InstrumentingAgents*, InspectorCompositeState*);
@@ -102,7 +102,7 @@
     InjectedScriptManager* m_injectedScriptManager;
 
     Vector<pair<long, String> > m_pendingEvaluateTestCommands;
-    pair<RefPtr<TypeBuilder::Runtime::RemoteObject>, RefPtr<InspectorObject> > m_pendingInspectData;
+    pair<RefPtr<TypeBuilder::Runtime::RemoteObject>, RefPtr<JSONObject> > m_pendingInspectData;
     typedef HashMap<String, String> InjectedScriptForOriginMap;
     InjectedScriptForOriginMap m_injectedScriptForOrigin;
 };
diff --git a/Source/core/inspector/InspectorApplicationCacheAgent.h b/Source/core/inspector/InspectorApplicationCacheAgent.h
index 3855618..922c302 100644
--- a/Source/core/inspector/InspectorApplicationCacheAgent.h
+++ b/Source/core/inspector/InspectorApplicationCacheAgent.h
@@ -35,11 +35,8 @@
 namespace WebCore {
 
 class Frame;
-class InspectorArray;
 class InspectorFrontend;
-class InspectorObject;
 class InspectorPageAgent;
-class InspectorValue;
 class InspectorState;
 class InstrumentingAgents;
 class Page;
diff --git a/Source/core/inspector/InspectorCSSAgent.cpp b/Source/core/inspector/InspectorCSSAgent.cpp
index c4a236d..74059b5 100644
--- a/Source/core/inspector/InspectorCSSAgent.cpp
+++ b/Source/core/inspector/InspectorCSSAgent.cpp
@@ -31,7 +31,6 @@
 #include "core/css/CSSImportRule.h"
 #include "core/css/CSSMediaRule.h"
 #include "core/css/CSSParser.h"
-#include "core/css/CSSPropertySourceData.h"
 #include "core/css/CSSRule.h"
 #include "core/css/CSSRuleList.h"
 #include "core/css/CSSStyleRule.h"
@@ -50,23 +49,20 @@
 #include "core/dom/Node.h"
 #include "core/dom/NodeList.h"
 #include "core/html/HTMLHeadElement.h"
-#include "core/inspector/ContentSearchUtils.h"
 #include "core/inspector/InspectorDOMAgent.h"
 #include "core/inspector/InspectorHistory.h"
 #include "core/inspector/InspectorPageAgent.h"
 #include "core/inspector/InspectorState.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/loader/DocumentLoader.h"
-#include "core/loader/cache/CachedResource.h"
 #include "core/page/ContentSecurityPolicy.h"
+#include "core/platform/JSONValues.h"
 #include "core/rendering/RenderRegion.h"
-
-#include <wtf/CurrentTime.h>
-#include <wtf/HashSet.h>
-#include <wtf/text/CString.h>
-#include <wtf/text/StringConcatenate.h>
-#include <wtf/Vector.h>
+#include "wtf/CurrentTime.h"
+#include "wtf/HashSet.h"
+#include "wtf/Vector.h"
+#include "wtf/text/CString.h"
+#include "wtf/text/StringConcatenate.h"
 
 namespace CSSAgentState {
 static const char cssAgentEnabled[] = "cssAgentEnabled";
@@ -167,7 +163,7 @@
     Vector<CSSStyleSheet*>& m_result;
 };
 
-static unsigned computePseudoClassMask(InspectorArray* pseudoClassArray)
+static unsigned computePseudoClassMask(JSONArray* pseudoClassArray)
 {
     DEFINE_STATIC_LOCAL(String, active, (ASCIILiteral("active")));
     DEFINE_STATIC_LOCAL(String, hover, (ASCIILiteral("hover")));
@@ -178,7 +174,7 @@
 
     unsigned result = PseudoNone;
     for (size_t i = 0; i < pseudoClassArray->length(); ++i) {
-        RefPtr<InspectorValue> pseudoClassValue = pseudoClassArray->get(i);
+        RefPtr<JSONValue> pseudoClassValue = pseudoClassArray->get(i);
         String pseudoClass;
         bool success = pseudoClassValue->asString(&pseudoClass);
         if (!success)
@@ -323,6 +319,54 @@
         m_timer.startOneShot(0);
 }
 
+class ChangeRegionOversetTask {
+public:
+    ChangeRegionOversetTask(InspectorCSSAgent*);
+    void scheduleFor(NamedFlow*, int documentNodeId);
+    void unschedule(NamedFlow*);
+    void reset();
+    void onTimer(Timer<ChangeRegionOversetTask>*);
+
+private:
+    InspectorCSSAgent* m_cssAgent;
+    Timer<ChangeRegionOversetTask> m_timer;
+    HashMap<NamedFlow*, int> m_namedFlows;
+};
+
+ChangeRegionOversetTask::ChangeRegionOversetTask(InspectorCSSAgent* cssAgent)
+    : m_cssAgent(cssAgent)
+    , m_timer(this, &ChangeRegionOversetTask::onTimer)
+{
+}
+
+void ChangeRegionOversetTask::scheduleFor(NamedFlow* namedFlow, int documentNodeId)
+{
+    m_namedFlows.add(namedFlow, documentNodeId);
+
+    if (!m_timer.isActive())
+        m_timer.startOneShot(0);
+}
+
+void ChangeRegionOversetTask::unschedule(NamedFlow* namedFlow)
+{
+    m_namedFlows.remove(namedFlow);
+}
+
+void ChangeRegionOversetTask::reset()
+{
+    m_timer.stop();
+    m_namedFlows.clear();
+}
+
+void ChangeRegionOversetTask::onTimer(Timer<ChangeRegionOversetTask>*)
+{
+    // The timer is stopped on m_cssAgent destruction, so this method will never be called after m_cssAgent has been destroyed.
+    for (HashMap<NamedFlow*, int>::iterator it = m_namedFlows.begin(), end = m_namedFlows.end(); it != end; ++it)
+        m_cssAgent->regionOversetChanged(it->key, it->value);
+
+    m_namedFlows.clear();
+}
+
 class InspectorCSSAgent::StyleSheetAction : public InspectorHistory::Action {
     WTF_MAKE_NONCOPYABLE(StyleSheetAction);
 public:
@@ -608,28 +652,103 @@
     return static_cast<CSSStyleRule*>(rule);
 }
 
-template <typename CharType>
-static bool hasVendorSpecificPrefix(const CharType* string, size_t stringLength)
+template <typename CharType, size_t bufferLength>
+static size_t vendorPrefixLowerCase(const CharType* string, size_t stringLength, char (&buffer)[bufferLength])
 {
-    for (size_t i = 1; i < stringLength; ++i) {
-        int c = string[i];
-        if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z'))
-            return i >= 2 && c == '-';
+    static const char lowerCaseOffset = 'a' - 'A';
+
+    if (string[0] != '-')
+        return 0;
+
+    for (size_t i = 0; i < stringLength - 1; i++) {
+        CharType c = string[i + 1];
+        if (c == '-')
+            return i;
+        if (i == bufferLength)
+            break;
+        if (c < 'A' || c > 'z')
+            break;
+        if (c >= 'a')
+            buffer[i] = c;
+        else if (c <= 'Z')
+            buffer[i] = c + lowerCaseOffset;
+        else
+            break;
     }
-    return false;
+    return 0;
+}
+
+template <size_t patternLength>
+static bool equals(const char* prefix, size_t prefixLength, const char (&pattern)[patternLength])
+{
+    if (prefixLength != patternLength - 1)
+        return false;
+    for (size_t i = 0; i < patternLength - 1; i++) {
+        if (prefix[i] != pattern[i])
+            return false;
+    }
+    return true;
 }
 
 static bool hasNonWebkitVendorSpecificPrefix(const CSSParserString& string)
 {
+    // Known prefixes: http://wiki.csswg.org/spec/vendor-prefixes
     const size_t stringLength = string.length();
-    if (stringLength < 4 || string[0] != '-')
+    if (stringLength < 4)
         return false;
 
-    static const char webkitPrefix[] = "-webkit-";
-    if (stringLength > 8 && string.startsWithIgnoringCase(webkitPrefix))
+    char buffer[6];
+    size_t prefixLength = string.is8Bit() ?
+        vendorPrefixLowerCase(string.characters8(), stringLength, buffer) :
+        vendorPrefixLowerCase(string.characters16(), stringLength, buffer);
+
+    if (!prefixLength || prefixLength == stringLength - 2)
         return false;
 
-    return string.is8Bit() ? hasVendorSpecificPrefix(string.characters8(), stringLength) : hasVendorSpecificPrefix(string.characters16(), stringLength);
+    switch (buffer[0]) {
+    case 'a':
+        return (prefixLength == 2 && buffer[1] == 'h') || equals(buffer + 1, prefixLength - 1, "tsc");
+    case 'e':
+        return equals(buffer + 1, prefixLength - 1, "pub");
+    case 'h':
+        return prefixLength == 2 && buffer[1] == 'p';
+    case 'i':
+        return equals(buffer + 1, prefixLength - 1, "books");
+    case 'k':
+        return equals(buffer + 1, prefixLength - 1, "html");
+    case 'm':
+        if (prefixLength == 2)
+            return buffer[1] == 's';
+        if (prefixLength == 3)
+            return (buffer[1] == 'o' && buffer[2] == 'z') || (buffer[1] == 's' || buffer[2] == 'o');
+        break;
+    case 'o':
+        return prefixLength == 1;
+    case 'p':
+        return equals(buffer + 1, prefixLength - 1, "rince");
+    case 'r':
+        return (prefixLength == 2 && buffer[1] == 'o') || equals(buffer + 1, prefixLength - 1, "im");
+    case 't':
+        return prefixLength == 2 && buffer[1] == 'c';
+    case 'w':
+        return (prefixLength == 3 && buffer[1] == 'a' && buffer[2] == 'p') || equals(buffer + 1, prefixLength - 1, "easy");
+    case 'x':
+        return prefixLength == 2 && buffer[1] == 'v';
+    }
+    return false;
+}
+
+static bool isValidPropertyName(const CSSParserString& content)
+{
+    if (content.equalIgnoringCase("animation")
+        || content.equalIgnoringCase("font-size-adjust")
+        || content.equalIgnoringCase("transform")
+        || content.equalIgnoringCase("user-select")
+        || content.equalIgnoringCase("-webkit-flex-pack")
+        || content.equalIgnoringCase("-webkit-text-size-adjust"))
+        return true;
+
+    return false;
 }
 
 // static
@@ -646,6 +765,7 @@
         // The "filter" property is commonly used instead of "opacity" for IE9.
         if (propertyId == CSSPropertyFilter)
             return false;
+
         break;
 
     case CSSParser::InvalidPropertyValueError:
@@ -661,9 +781,29 @@
         if (propertyId == CSSPropertyCursor && content.equalIgnoringCase("hand"))
             return false;
 
-        // Ignore properties like "property: value \9". This trick used in bootsrtap for IE-only properies.
-        if (contentLength > 2 && content[contentLength - 2] == '\\' && content[contentLength - 1] == '9')
+        // Ignore properties like "property: value \9" (common IE hack) or "property: value \0" (IE 8 hack).
+        if (contentLength > 2 && content[contentLength - 2] == '\\' && (content[contentLength - 1] == '9' || content[contentLength - 1] == '0'))
             return false;
+
+        if (contentLength > 3) {
+
+            // property: value\0/;
+            if (content[contentLength - 3] == '\\' && content[contentLength - 2] == '0' && content[contentLength - 1] == '/')
+                return false;
+
+            // property: value !ie;
+            if (content[contentLength - 3] == '!' && content[contentLength - 2] == 'i' && content[contentLength - 1] == 'e')
+                return false;
+        }
+
+        // Popular value prefixes valid in other browsers.
+        if (content.startsWithIgnoringCase("linear-gradient"))
+            return false;
+        if (content.startsWithIgnoringCase("-webkit-flexbox"))
+            return false;
+        if (propertyId == CSSPropertyUnicodeBidi && content.startsWithIgnoringCase("isolate"))
+            return false;
+
         break;
 
     case CSSParser::InvalidPropertyError:
@@ -678,10 +818,20 @@
         if (content.startsWithIgnoringCase("scrollbar-"))
             return false;
 
-        // Unsupported standard property.
-        if (content.equalIgnoringCase("font-size-adjust"))
+        if (isValidPropertyName(content))
             return false;
+
         break;
+
+    case CSSParser::InvalidRuleError:
+        // Block error reporting for @-rules for now to avoid noise.
+        if (contentLength > 4 && content[0] == '@')
+            return false;
+        return true;
+
+    case CSSParser::InvalidSelectorPseudoError:
+        if (hasNonWebkitVendorSpecificPrefix(content))
+            return false;
     }
     return true;
 }
@@ -749,6 +899,8 @@
     m_namedFlowCollectionsRequested.clear();
     if (m_updateRegionLayoutTask)
         m_updateRegionLayoutTask->reset();
+    if (m_changeRegionOversetTask)
+        m_changeRegionOversetTask->reset();
     resetPseudoStates();
 }
 
@@ -830,6 +982,28 @@
     m_frontend->regionLayoutUpdated(buildObjectForNamedFlow(&errorString, namedFlow, documentNodeId));
 }
 
+void InspectorCSSAgent::didChangeRegionOverset(Document* document, NamedFlow* namedFlow)
+{
+    int documentNodeId = documentNodeWithRequestedFlowsId(document);
+    if (!documentNodeId)
+        return;
+
+    if (!m_changeRegionOversetTask)
+        m_changeRegionOversetTask = adoptPtr(new ChangeRegionOversetTask(this));
+    m_changeRegionOversetTask->scheduleFor(namedFlow, documentNodeId);
+}
+
+void InspectorCSSAgent::regionOversetChanged(NamedFlow* namedFlow, int documentNodeId)
+{
+    if (namedFlow->flowState() == NamedFlow::FlowStateNull)
+        return;
+
+    ErrorString errorString;
+    RefPtr<NamedFlow> protector(namedFlow);
+
+    m_frontend->regionOversetChanged(buildObjectForNamedFlow(&errorString, namedFlow, documentNodeId));
+}
+
 void InspectorCSSAgent::activeStyleSheetsUpdated(Document* document, const Vector<RefPtr<StyleSheet> >& newSheets)
 {
     HashSet<CSSStyleSheet*> removedSheets;
@@ -1037,7 +1211,7 @@
     *errorString = InspectorDOMAgent::toErrorString(ec);
 }
 
-void InspectorCSSAgent::setStyleText(ErrorString* errorString, const RefPtr<InspectorObject>& fullStyleId, const String& text, RefPtr<TypeBuilder::CSS::CSSStyle>& result)
+void InspectorCSSAgent::setStyleText(ErrorString* errorString, const RefPtr<JSONObject>& fullStyleId, const String& text, RefPtr<TypeBuilder::CSS::CSSStyle>& result)
 {
     InspectorCSSId compoundId(fullStyleId);
     ASSERT(!compoundId.isEmpty());
@@ -1053,7 +1227,7 @@
     *errorString = InspectorDOMAgent::toErrorString(ec);
 }
 
-void InspectorCSSAgent::setPropertyText(ErrorString* errorString, const RefPtr<InspectorObject>& fullStyleId, int propertyIndex, const String& text, bool overwrite, RefPtr<TypeBuilder::CSS::CSSStyle>& result)
+void InspectorCSSAgent::setPropertyText(ErrorString* errorString, const RefPtr<JSONObject>& fullStyleId, int propertyIndex, const String& text, bool overwrite, RefPtr<TypeBuilder::CSS::CSSStyle>& result)
 {
     InspectorCSSId compoundId(fullStyleId);
     ASSERT(!compoundId.isEmpty());
@@ -1069,7 +1243,7 @@
     *errorString = InspectorDOMAgent::toErrorString(ec);
 }
 
-void InspectorCSSAgent::toggleProperty(ErrorString* errorString, const RefPtr<InspectorObject>& fullStyleId, int propertyIndex, bool disable, RefPtr<TypeBuilder::CSS::CSSStyle>& result)
+void InspectorCSSAgent::toggleProperty(ErrorString* errorString, const RefPtr<JSONObject>& fullStyleId, int propertyIndex, bool disable, RefPtr<TypeBuilder::CSS::CSSStyle>& result)
 {
     InspectorCSSId compoundId(fullStyleId);
     ASSERT(!compoundId.isEmpty());
@@ -1085,7 +1259,7 @@
     *errorString = InspectorDOMAgent::toErrorString(ec);
 }
 
-void InspectorCSSAgent::setRuleSelector(ErrorString* errorString, const RefPtr<InspectorObject>& fullRuleId, const String& selector, RefPtr<TypeBuilder::CSS::CSSRule>& result)
+void InspectorCSSAgent::setRuleSelector(ErrorString* errorString, const RefPtr<JSONObject>& fullRuleId, const String& selector, RefPtr<TypeBuilder::CSS::CSSRule>& result)
 {
     InspectorCSSId compoundId(fullRuleId);
     ASSERT(!compoundId.isEmpty());
@@ -1154,7 +1328,7 @@
     cssProperties = properties.release();
 }
 
-void InspectorCSSAgent::forcePseudoState(ErrorString* errorString, int nodeId, const RefPtr<InspectorArray>& forcedPseudoClasses)
+void InspectorCSSAgent::forcePseudoState(ErrorString* errorString, int nodeId, const RefPtr<JSONArray>& forcedPseudoClasses)
 {
     Element* element = m_domAgent->assertElement(errorString, nodeId);
     if (!element)
@@ -1216,7 +1390,6 @@
 
     if (!sourceURL.isEmpty()) {
         mediaObject->setSourceURL(sourceURL);
-        mediaObject->setSourceLine(media->queries()->lastLine());
 
         CSSRule* parentRule = media->parentRule();
         if (!parentRule)
@@ -1573,7 +1746,7 @@
         return 0;
 
     // FIXME: Ugliness below.
-    StylePropertySet* attributeStyle = const_cast<StylePropertySet*>(static_cast<StyledElement*>(element)->presentationAttributeStyle());
+    StylePropertySet* attributeStyle = const_cast<StylePropertySet*>(element->presentationAttributeStyle());
     if (!attributeStyle)
         return 0;
 
@@ -1591,17 +1764,17 @@
     for (unsigned i = 0; i < regionList->length(); ++i) {
         TypeBuilder::CSS::Region::RegionOverset::Enum regionOverset;
 
-        switch (toElement(regionList->item(i))->renderRegion()->regionState()) {
-        case RenderRegion::RegionFit:
+        switch (toElement(regionList->item(i))->renderRegion()->regionOversetState()) {
+        case RegionFit:
             regionOverset = TypeBuilder::CSS::Region::RegionOverset::Fit;
             break;
-        case RenderRegion::RegionEmpty:
+        case RegionEmpty:
             regionOverset = TypeBuilder::CSS::Region::RegionOverset::Empty;
             break;
-        case RenderRegion::RegionOverset:
+        case RegionOverset:
             regionOverset = TypeBuilder::CSS::Region::RegionOverset::Overset;
             break;
-        case RenderRegion::RegionUndefined:
+        case RegionUndefined:
             continue;
         default:
             ASSERT_NOT_REACHED();
diff --git a/Source/core/inspector/InspectorCSSAgent.h b/Source/core/inspector/InspectorCSSAgent.h
index 5eafc00..8382c1a 100644
--- a/Source/core/inspector/InspectorCSSAgent.h
+++ b/Source/core/inspector/InspectorCSSAgent.h
@@ -30,18 +30,18 @@
 #include "core/inspector/InspectorBaseAgent.h"
 #include "core/inspector/InspectorDOMAgent.h"
 #include "core/inspector/InspectorStyleSheet.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/page/ContentSecurityPolicy.h"
-
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Vector.h>
+#include "core/platform/JSONValues.h"
+#include "wtf/HashMap.h"
+#include "wtf/HashSet.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
+class ChangeRegionOversetTask;
 struct CSSParserString;
 class CSSRule;
 class CSSRuleList;
@@ -118,8 +118,15 @@
     void mediaQueryResultChanged();
     void didCreateNamedFlow(Document*, NamedFlow*);
     void willRemoveNamedFlow(Document*, NamedFlow*);
-    void didUpdateRegionLayout(Document*, NamedFlow*);
+
+private:
     void regionLayoutUpdated(NamedFlow*, int documentNodeId);
+    void regionOversetChanged(NamedFlow*, int documentNodeId);
+
+public:
+    void didUpdateRegionLayout(Document*, NamedFlow*);
+    void didChangeRegionOverset(Document*, NamedFlow*);
+
     void activeStyleSheetsUpdated(Document*, const Vector<RefPtr<StyleSheet> >& newSheets);
     void frameDetachedFromParent(Frame*);
 
@@ -130,13 +137,13 @@
     virtual void getStyleSheet(ErrorString*, const String& styleSheetId, RefPtr<TypeBuilder::CSS::CSSStyleSheetBody>& result);
     virtual void getStyleSheetText(ErrorString*, const String& styleSheetId, String* result);
     virtual void setStyleSheetText(ErrorString*, const String& styleSheetId, const String& text);
-    virtual void setStyleText(ErrorString*, const RefPtr<InspectorObject>& styleId, const String& text, RefPtr<TypeBuilder::CSS::CSSStyle>& result);
-    virtual void setPropertyText(ErrorString*, const RefPtr<InspectorObject>& styleId, int propertyIndex, const String& text, bool overwrite, RefPtr<TypeBuilder::CSS::CSSStyle>& result);
-    virtual void toggleProperty(ErrorString*, const RefPtr<InspectorObject>& styleId, int propertyIndex, bool disable, RefPtr<TypeBuilder::CSS::CSSStyle>& result);
-    virtual void setRuleSelector(ErrorString*, const RefPtr<InspectorObject>& ruleId, const String& selector, RefPtr<TypeBuilder::CSS::CSSRule>& result);
+    virtual void setStyleText(ErrorString*, const RefPtr<JSONObject>& styleId, const String& text, RefPtr<TypeBuilder::CSS::CSSStyle>& result);
+    virtual void setPropertyText(ErrorString*, const RefPtr<JSONObject>& styleId, int propertyIndex, const String& text, bool overwrite, RefPtr<TypeBuilder::CSS::CSSStyle>& result);
+    virtual void toggleProperty(ErrorString*, const RefPtr<JSONObject>& styleId, int propertyIndex, bool disable, RefPtr<TypeBuilder::CSS::CSSStyle>& result);
+    virtual void setRuleSelector(ErrorString*, const RefPtr<JSONObject>& ruleId, const String& selector, RefPtr<TypeBuilder::CSS::CSSRule>& result);
     virtual void addRule(ErrorString*, int contextNodeId, const String& selector, RefPtr<TypeBuilder::CSS::CSSRule>& result);
     virtual void getSupportedCSSProperties(ErrorString*, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::CSSPropertyInfo> >& result);
-    virtual void forcePseudoState(ErrorString*, int nodeId, const RefPtr<InspectorArray>& forcedPseudoClasses);
+    virtual void forcePseudoState(ErrorString*, int nodeId, const RefPtr<JSONArray>& forcedPseudoClasses);
     virtual void getNamedFlowCollection(ErrorString*, int documentNodeId, RefPtr<TypeBuilder::Array<TypeBuilder::CSS::NamedFlow> >& result);
 
     virtual void startSelectorProfiler(ErrorString*);
@@ -207,13 +214,16 @@
     NodeIdToForcedPseudoState m_nodeIdToForcedPseudoState;
     HashSet<int> m_namedFlowCollectionsRequested;
     OwnPtr<UpdateRegionLayoutTask> m_updateRegionLayoutTask;
+    OwnPtr<ChangeRegionOversetTask> m_changeRegionOversetTask;
 
     int m_lastStyleSheetId;
     bool m_creatingViaInspectorStyleSheet;
 
     OwnPtr<SelectorProfile> m_currentSelectorProfile;
 
+    friend class ChangeRegionOversetTask;
     friend class StyleSheetBinder;
+    friend class UpdateRegionLayoutTask;
 };
 
 
diff --git a/Source/core/inspector/InspectorCanvasAgent.cpp b/Source/core/inspector/InspectorCanvasAgent.cpp
index eaa5314..64f6a08 100644
--- a/Source/core/inspector/InspectorCanvasAgent.cpp
+++ b/Source/core/inspector/InspectorCanvasAgent.cpp
@@ -55,6 +55,7 @@
 using WebCore::TypeBuilder::Canvas::TraceLog;
 using WebCore::TypeBuilder::Canvas::TraceLogId;
 using WebCore::TypeBuilder::Network::FrameId;
+using WebCore::TypeBuilder::Runtime::RemoteObject;
 
 namespace WebCore {
 
@@ -190,6 +191,13 @@
         module.resourceState(errorString, traceLogId, resourceId, &result);
 }
 
+void InspectorCanvasAgent::evaluateTraceLogCallArgument(ErrorString* errorString, const TraceLogId& traceLogId, int callIndex, int argumentIndex, const String* objectGroup, RefPtr<RemoteObject>& result, RefPtr<ResourceState>& resourceState)
+{
+    InjectedScriptCanvasModule module = injectedScriptCanvasModule(errorString, traceLogId);
+    if (!module.hasNoValue())
+        module.evaluateTraceLogCallArgument(errorString, traceLogId, callIndex, argumentIndex, objectGroup ? *objectGroup : String(), &result, &resourceState);
+}
+
 ScriptObject InspectorCanvasAgent::wrapCanvas2DRenderingContextForInstrumentation(const ScriptObject& context)
 {
     ErrorString error;
diff --git a/Source/core/inspector/InspectorCanvasAgent.h b/Source/core/inspector/InspectorCanvasAgent.h
index 0d8bf0c..b5a7fe0 100644
--- a/Source/core/inspector/InspectorCanvasAgent.h
+++ b/Source/core/inspector/InspectorCanvasAgent.h
@@ -36,10 +36,9 @@
 #include "InspectorTypeBuilder.h"
 #include "bindings/v8/ScriptState.h"
 #include "core/inspector/InspectorBaseAgent.h"
-#include <wtf/HashMap.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/HashMap.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -86,6 +85,7 @@
     virtual void replayTraceLog(ErrorString*, const TypeBuilder::Canvas::TraceLogId&, int, RefPtr<TypeBuilder::Canvas::ResourceState>&);
     virtual void getResourceInfo(ErrorString*, const TypeBuilder::Canvas::ResourceId&, RefPtr<TypeBuilder::Canvas::ResourceInfo>&);
     virtual void getResourceState(ErrorString*, const TypeBuilder::Canvas::TraceLogId&, const TypeBuilder::Canvas::ResourceId&, RefPtr<TypeBuilder::Canvas::ResourceState>&);
+    virtual void evaluateTraceLogCallArgument(ErrorString*, const TypeBuilder::Canvas::TraceLogId&, int, int, const String*, RefPtr<TypeBuilder::Runtime::RemoteObject>&, RefPtr<TypeBuilder::Canvas::ResourceState>&);
 
 private:
     InspectorCanvasAgent(InstrumentingAgents*, InspectorCompositeState*, InspectorPageAgent*, InjectedScriptManager*);
diff --git a/Source/core/inspector/InspectorClient.h b/Source/core/inspector/InspectorClient.h
index dfcca85..6fa61c7 100644
--- a/Source/core/inspector/InspectorClient.h
+++ b/Source/core/inspector/InspectorClient.h
@@ -61,6 +61,7 @@
     virtual void setShowDebugBorders(bool) { }
     virtual void setShowFPSCounter(bool) { }
     virtual void setContinuousPaintingEnabled(bool) { }
+    virtual void setShowScrollBottleneckRects(bool) { }
 
     virtual void getAllocatedObjects(HashSet<const void*>&) { }
     virtual void dumpUncountedAllocatedObjects(const HashMap<const void*, size_t>&) { }
diff --git a/Source/core/inspector/InspectorConsoleAgent.cpp b/Source/core/inspector/InspectorConsoleAgent.cpp
index c09dd77..b4fcec9 100644
--- a/Source/core/inspector/InspectorConsoleAgent.cpp
+++ b/Source/core/inspector/InspectorConsoleAgent.cpp
@@ -40,17 +40,15 @@
 #include "core/inspector/ScriptCallFrame.h"
 #include "core/inspector/ScriptCallStack.h"
 #include "core/loader/DocumentLoader.h"
-#include "core/page/Console.h"
-#include "core/page/DOMWindow.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/platform/network/ResourceError.h"
 #include "core/platform/network/ResourceResponse.h"
-#include <wtf/CurrentTime.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/text/StringBuilder.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/CurrentTime.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/text/StringBuilder.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -174,7 +172,7 @@
     addConsoleMessage(adoptPtr(new ConsoleMessage(!isWorkerAgent(), source, type, level, message, arguments, state, requestIdentifier)));
 }
 
-void InspectorConsoleAgent::addMessageToConsole(MessageSource source, MessageType type, MessageLevel level, const String& message, const String& scriptId, unsigned lineNumber, ScriptState* state, unsigned long requestIdentifier)
+void InspectorConsoleAgent::addMessageToConsole(MessageSource source, MessageType type, MessageLevel level, const String& message, const String& scriptId, unsigned lineNumber, unsigned columnNumber, ScriptState* state, unsigned long requestIdentifier)
 {
     if (type == ClearMessageType) {
         ErrorString error;
@@ -182,7 +180,7 @@
     }
 
     bool canGenerateCallStack = !isWorkerAgent() && m_frontend;
-    addConsoleMessage(adoptPtr(new ConsoleMessage(canGenerateCallStack, source, type, level, message, scriptId, lineNumber, state, requestIdentifier)));
+    addConsoleMessage(adoptPtr(new ConsoleMessage(canGenerateCallStack, source, type, level, message, scriptId, lineNumber, columnNumber, state, requestIdentifier)));
 }
 
 Vector<unsigned> InspectorConsoleAgent::consoleMessageArgumentCounts()
@@ -220,7 +218,7 @@
     double elapsed = monotonicallyIncreasingTime() - startTime;
     String message = title + String::format(": %.3fms", elapsed * 1000);
     const ScriptCallFrame& lastCaller = callStack->at(0);
-    addMessageToConsole(ConsoleAPIMessageSource, TimingMessageType, DebugMessageLevel, message, lastCaller.sourceURL(), lastCaller.lineNumber());
+    addMessageToConsole(ConsoleAPIMessageSource, TimingMessageType, DebugMessageLevel, message, lastCaller.sourceURL(), lastCaller.lineNumber(), lastCaller.columnNumber());
 }
 
 void InspectorConsoleAgent::consoleCount(ScriptState* state, PassRefPtr<ScriptArguments> arguments)
@@ -268,7 +266,7 @@
 {
     if (m_frontend && m_state->getBoolean(ConsoleAgentState::monitoringXHR)) {
         String message = "XHR finished loading: \"" + url + "\".";
-        addMessageToConsole(NetworkMessageSource, LogMessageType, DebugMessageLevel, message, sendURL, sendLineNumber, 0, requestIdentifier);
+        addMessageToConsole(NetworkMessageSource, LogMessageType, DebugMessageLevel, message, sendURL, sendLineNumber, 0, 0, requestIdentifier);
     }
 }
 
@@ -278,7 +276,7 @@
         return;
     if (response.httpStatusCode() >= 400) {
         String message = "Failed to load resource: the server responded with a status of " + String::number(response.httpStatusCode()) + " (" + response.httpStatusText() + ')';
-        addMessageToConsole(NetworkMessageSource, LogMessageType, ErrorMessageLevel, message, response.url().string(), 0, 0, requestIdentifier);
+        addMessageToConsole(NetworkMessageSource, LogMessageType, ErrorMessageLevel, message, response.url().string(), 0, 0, 0, requestIdentifier);
     }
 }
 
@@ -292,7 +290,7 @@
         message.appendLiteral(": ");
         message.append(error.localizedDescription());
     }
-    addMessageToConsole(NetworkMessageSource, LogMessageType, ErrorMessageLevel, message.toString(), error.failingURL(), 0, 0, requestIdentifier);
+    addMessageToConsole(NetworkMessageSource, LogMessageType, ErrorMessageLevel, message.toString(), error.failingURL(), 0, 0, 0, requestIdentifier);
 }
 
 void InspectorConsoleAgent::setMonitoringXHREnabled(ErrorString*, bool enabled)
diff --git a/Source/core/inspector/InspectorConsoleAgent.h b/Source/core/inspector/InspectorConsoleAgent.h
index 550d295..3d08e74 100644
--- a/Source/core/inspector/InspectorConsoleAgent.h
+++ b/Source/core/inspector/InspectorConsoleAgent.h
@@ -74,7 +74,7 @@
     virtual void restore();
 
     void addMessageToConsole(MessageSource, MessageType, MessageLevel, const String& message, ScriptState*, PassRefPtr<ScriptArguments>, unsigned long requestIdentifier = 0);
-    void addMessageToConsole(MessageSource, MessageType, MessageLevel, const String& message, const String& scriptId, unsigned lineNumber, ScriptState* = 0, unsigned long requestIdentifier = 0);
+    void addMessageToConsole(MessageSource, MessageType, MessageLevel, const String& message, const String& scriptId, unsigned lineNumber, unsigned columnNumber = 0, ScriptState* = 0, unsigned long requestIdentifier = 0);
 
     // FIXME: Remove once we no longer generate stacks outside of Inspector.
     void addMessageToConsole(MessageSource, MessageType, MessageLevel, const String& message, PassRefPtr<ScriptCallStack>, unsigned long requestIdentifier = 0);
diff --git a/Source/core/inspector/InspectorController.cpp b/Source/core/inspector/InspectorController.cpp
index 9e59ddc..196c876 100644
--- a/Source/core/inspector/InspectorController.cpp
+++ b/Source/core/inspector/InspectorController.cpp
@@ -70,8 +70,7 @@
 #include "core/inspector/PageRuntimeAgent.h"
 #include "core/page/Page.h"
 #include "core/platform/PlatformMouseEvent.h"
-#include <wtf/MemoryInstrumentationVector.h>
-#include <wtf/UnusedParam.h>
+#include "wtf/MemoryInstrumentationVector.h"
 
 namespace WebCore {
 
@@ -112,7 +111,7 @@
        inspectorClient));
     m_agents.append(InspectorApplicationCacheAgent::create(m_instrumentingAgents.get(), m_state.get(), pageAgent));
 
-    m_agents.append(InspectorResourceAgent::create(m_instrumentingAgents.get(), pageAgent, inspectorClient, m_state.get()));
+    m_agents.append(InspectorResourceAgent::create(m_instrumentingAgents.get(), pageAgent, inspectorClient, m_state.get(), m_overlay.get()));
 
     PageScriptDebugServer* pageScriptDebugServer = &PageScriptDebugServer::shared();
 
diff --git a/Source/core/inspector/InspectorCounters.h b/Source/core/inspector/InspectorCounters.h
index d619d16..893f941 100644
--- a/Source/core/inspector/InspectorCounters.h
+++ b/Source/core/inspector/InspectorCounters.h
@@ -31,11 +31,10 @@
 #ifndef InspectorCounters_h
 #define InspectorCounters_h
 
-#include <wtf/FastAllocBase.h>
-#include <wtf/UnusedParam.h>
+#include "wtf/FastAllocBase.h"
 
 #if !ASSERT_DISABLED
-#include <wtf/MainThread.h>
+#include "wtf/MainThread.h"
 #endif
 
 namespace WebCore {
diff --git a/Source/core/inspector/InspectorDOMAgent.cpp b/Source/core/inspector/InspectorDOMAgent.cpp
index 16de128..c9a1674 100644
--- a/Source/core/inspector/InspectorDOMAgent.cpp
+++ b/Source/core/inspector/InspectorDOMAgent.cpp
@@ -37,6 +37,7 @@
 #include "core/dom/Attr.h"
 #include "core/dom/CharacterData.h"
 #include "core/dom/ContainerNode.h"
+#include "core/dom/DOMException.h"
 #include "core/dom/Document.h"
 #include "core/dom/DocumentFragment.h"
 #include "core/dom/DocumentType.h"
@@ -93,7 +94,7 @@
 static const size_t maxTextSize = 10000;
 static const UChar ellipsisUChar[] = { 0x2026, 0 };
 
-static Color parseColor(const RefPtr<InspectorObject>* colorObject)
+static Color parseColor(const RefPtr<JSONObject>* colorObject)
 {
     if (!colorObject || !(*colorObject))
         return Color::transparent;
@@ -121,13 +122,13 @@
     return Color(r, g, b, static_cast<int>(a * 255));
 }
 
-static Color parseConfigColor(const String& fieldName, InspectorObject* configObject)
+static Color parseConfigColor(const String& fieldName, JSONObject* configObject)
 {
-    const RefPtr<InspectorObject> colorObject = configObject->getObject(fieldName);
+    const RefPtr<JSONObject> colorObject = configObject->getObject(fieldName);
     return parseColor(&colorObject);
 }
 
-static bool parseQuad(const RefPtr<InspectorArray>& quadArray, FloatQuad* quad)
+static bool parseQuad(const RefPtr<JSONArray>& quadArray, FloatQuad* quad)
 {
     if (!quadArray)
         return false;
@@ -214,10 +215,8 @@
 
 String InspectorDOMAgent::toErrorString(const ExceptionCode& ec)
 {
-    if (ec) {
-        ExceptionCodeDescription description(ec);
-        return description.name;
-    }
+    if (ec)
+        return DOMException::getErrorName(ec);
     return "";
 }
 
@@ -994,7 +993,7 @@
                     break;
 
                 if (node->nodeType() == Node::ATTRIBUTE_NODE)
-                    node = static_cast<Attr*>(node)->ownerElement();
+                    node = toAttr(node)->ownerElement();
                 resultCollector.add(node);
             }
         }
@@ -1101,7 +1100,7 @@
         m_overlay->highlightNode(node, eventTarget, *m_inspectModeHighlightConfig);
 }
 
-void InspectorDOMAgent::setSearchingForNode(ErrorString* errorString, bool enabled, InspectorObject* highlightInspectorObject)
+void InspectorDOMAgent::setSearchingForNode(ErrorString* errorString, bool enabled, JSONObject* highlightInspectorObject)
 {
     if (m_searchingForNode == enabled)
         return;
@@ -1115,7 +1114,7 @@
         hideHighlight(errorString);
 }
 
-PassOwnPtr<HighlightConfig> InspectorDOMAgent::highlightConfigFromInspectorObject(ErrorString* errorString, InspectorObject* highlightInspectorObject)
+PassOwnPtr<HighlightConfig> InspectorDOMAgent::highlightConfigFromInspectorObject(ErrorString* errorString, JSONObject* highlightInspectorObject)
 {
     if (!highlightInspectorObject) {
         *errorString = "Internal error: highlight configuration parameter is missing";
@@ -1138,18 +1137,18 @@
     return highlightConfig.release();
 }
 
-void InspectorDOMAgent::setInspectModeEnabled(ErrorString* errorString, bool enabled, const RefPtr<InspectorObject>* highlightConfig)
+void InspectorDOMAgent::setInspectModeEnabled(ErrorString* errorString, bool enabled, const RefPtr<JSONObject>* highlightConfig)
 {
     setSearchingForNode(errorString, enabled, highlightConfig ? highlightConfig->get() : 0);
 }
 
-void InspectorDOMAgent::highlightRect(ErrorString*, int x, int y, int width, int height, const RefPtr<InspectorObject>* color, const RefPtr<InspectorObject>* outlineColor)
+void InspectorDOMAgent::highlightRect(ErrorString*, int x, int y, int width, int height, const RefPtr<JSONObject>* color, const RefPtr<JSONObject>* outlineColor)
 {
     OwnPtr<FloatQuad> quad = adoptPtr(new FloatQuad(FloatRect(x, y, width, height)));
     innerHighlightQuad(quad.release(), color, outlineColor);
 }
 
-void InspectorDOMAgent::highlightQuad(ErrorString* errorString, const RefPtr<InspectorArray>& quadArray, const RefPtr<InspectorObject>* color, const RefPtr<InspectorObject>* outlineColor)
+void InspectorDOMAgent::highlightQuad(ErrorString* errorString, const RefPtr<JSONArray>& quadArray, const RefPtr<JSONObject>* color, const RefPtr<JSONObject>* outlineColor)
 {
     OwnPtr<FloatQuad> quad = adoptPtr(new FloatQuad());
     if (!parseQuad(quadArray, quad.get())) {
@@ -1159,7 +1158,7 @@
     innerHighlightQuad(quad.release(), color, outlineColor);
 }
 
-void InspectorDOMAgent::innerHighlightQuad(PassOwnPtr<FloatQuad> quad, const RefPtr<InspectorObject>* color, const RefPtr<InspectorObject>* outlineColor)
+void InspectorDOMAgent::innerHighlightQuad(PassOwnPtr<FloatQuad> quad, const RefPtr<JSONObject>* color, const RefPtr<JSONObject>* outlineColor)
 {
     OwnPtr<HighlightConfig> highlightConfig = adoptPtr(new HighlightConfig());
     highlightConfig->content = parseColor(color);
@@ -1167,7 +1166,7 @@
     m_overlay->highlightQuad(quad, *highlightConfig);
 }
 
-void InspectorDOMAgent::highlightNode(ErrorString* errorString, const RefPtr<InspectorObject>& highlightInspectorObject, const int* nodeId, const String* objectId)
+void InspectorDOMAgent::highlightNode(ErrorString* errorString, const RefPtr<JSONObject>& highlightInspectorObject, const int* nodeId, const String* objectId)
 {
     Node* node = 0;
     if (nodeId) {
@@ -1193,8 +1192,8 @@
 void InspectorDOMAgent::highlightFrame(
     ErrorString*,
     const String& frameId,
-    const RefPtr<InspectorObject>* color,
-    const RefPtr<InspectorObject>* outlineColor)
+    const RefPtr<JSONObject>* color,
+    const RefPtr<JSONObject>* outlineColor)
 {
     Frame* frame = m_pageAgent->frameForId(frameId);
     if (frame && frame->ownerElement()) {
@@ -1269,7 +1268,7 @@
     element->focus();
 }
 
-void InspectorDOMAgent::setFileInputFiles(ErrorString* errorString, int nodeId, const RefPtr<InspectorArray>& files)
+void InspectorDOMAgent::setFileInputFiles(ErrorString* errorString, int nodeId, const RefPtr<JSONArray>& files)
 {
     Node* node = assertNode(errorString, nodeId);
     if (!node)
@@ -1280,7 +1279,7 @@
     }
 
     RefPtr<FileList> fileList = FileList::create();
-    for (InspectorArray::const_iterator iter = files->begin(); iter != files->end(); ++iter) {
+    for (JSONArray::const_iterator iter = files->begin(); iter != files->end(); ++iter) {
         String path;
         if (!(*iter)->asString(&path)) {
             *errorString = "Files must be strings";
@@ -1413,7 +1412,7 @@
         value->setSystemId(docType->systemId());
         value->setInternalSubset(docType->internalSubset());
     } else if (node->isAttributeNode()) {
-        Attr* attribute = static_cast<Attr*>(node);
+        Attr* attribute = toAttr(node);
         value->setName(attribute->name());
         value->setValue(attribute->value());
     }
diff --git a/Source/core/inspector/InspectorDOMAgent.h b/Source/core/inspector/InspectorDOMAgent.h
index 912fdb6..a7aed5d 100644
--- a/Source/core/inspector/InspectorDOMAgent.h
+++ b/Source/core/inspector/InspectorDOMAgent.h
@@ -31,24 +31,19 @@
 #define InspectorDOMAgent_h
 
 #include "InspectorFrontend.h"
-#include "core/dom/EventTarget.h"
 #include "core/inspector/InjectedScript.h"
 #include "core/inspector/InjectedScriptManager.h"
 #include "core/inspector/InspectorBaseAgent.h"
-#include "core/inspector/InspectorOverlay.h"
-#include "core/inspector/InspectorValues.h"
-#include "core/platform/Timer.h"
+#include "core/platform/JSONValues.h"
 #include "core/rendering/RenderLayer.h"
 
-#include <wtf/Deque.h>
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/ListHashSet.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/AtomicString.h>
-#include <wtf/Vector.h>
+#include "wtf/HashMap.h"
+#include "wtf/HashSet.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
 class ContainerNode;
@@ -138,23 +133,23 @@
     virtual void discardSearchResults(ErrorString*, const String& searchId);
     virtual void resolveNode(ErrorString*, int nodeId, const String* objectGroup, RefPtr<TypeBuilder::Runtime::RemoteObject>& result);
     virtual void getAttributes(ErrorString*, int nodeId, RefPtr<TypeBuilder::Array<String> >& result);
-    virtual void setInspectModeEnabled(ErrorString*, bool enabled, const RefPtr<InspectorObject>* highlightConfig);
+    virtual void setInspectModeEnabled(ErrorString*, bool enabled, const RefPtr<JSONObject>* highlightConfig);
     virtual void requestNode(ErrorString*, const String& objectId, int* nodeId);
     virtual void pushNodeByPathToFrontend(ErrorString*, const String& path, int* nodeId);
     virtual void pushNodeByBackendIdToFrontend(ErrorString*, BackendNodeId, int* nodeId);
     virtual void releaseBackendNodeIds(ErrorString*, const String& nodeGroup);
     virtual void hideHighlight(ErrorString*);
-    virtual void highlightRect(ErrorString*, int x, int y, int width, int height, const RefPtr<InspectorObject>* color, const RefPtr<InspectorObject>* outlineColor);
-    virtual void highlightQuad(ErrorString*, const RefPtr<InspectorArray>& quad, const RefPtr<InspectorObject>* color, const RefPtr<InspectorObject>* outlineColor);
-    virtual void highlightNode(ErrorString*, const RefPtr<InspectorObject>& highlightConfig, const int* nodeId, const String* objectId);
-    virtual void highlightFrame(ErrorString*, const String& frameId, const RefPtr<InspectorObject>* color, const RefPtr<InspectorObject>* outlineColor);
+    virtual void highlightRect(ErrorString*, int x, int y, int width, int height, const RefPtr<JSONObject>* color, const RefPtr<JSONObject>* outlineColor);
+    virtual void highlightQuad(ErrorString*, const RefPtr<JSONArray>& quad, const RefPtr<JSONObject>* color, const RefPtr<JSONObject>* outlineColor);
+    virtual void highlightNode(ErrorString*, const RefPtr<JSONObject>& highlightConfig, const int* nodeId, const String* objectId);
+    virtual void highlightFrame(ErrorString*, const String& frameId, const RefPtr<JSONObject>* color, const RefPtr<JSONObject>* outlineColor);
 
     virtual void moveTo(ErrorString*, int nodeId, int targetNodeId, const int* anchorNodeId, int* newNodeId);
     virtual void undo(ErrorString*);
     virtual void redo(ErrorString*);
     virtual void markUndoableState(ErrorString*);
     virtual void focus(ErrorString*, int nodeId);
-    virtual void setFileInputFiles(ErrorString*, int nodeId, const RefPtr<InspectorArray>& files);
+    virtual void setFileInputFiles(ErrorString*, int nodeId, const RefPtr<JSONArray>& files);
 
     static void getEventListeners(Node*, Vector<EventListenerInfo>& listenersArray, bool includeAncestors);
 
@@ -212,8 +207,8 @@
 private:
     InspectorDOMAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorCompositeState*, InjectedScriptManager*, InspectorOverlay*, InspectorClient*);
 
-    void setSearchingForNode(ErrorString*, bool enabled, InspectorObject* highlightConfig);
-    PassOwnPtr<HighlightConfig> highlightConfigFromInspectorObject(ErrorString*, InspectorObject* highlightInspectorObject);
+    void setSearchingForNode(ErrorString*, bool enabled, JSONObject* highlightConfig);
+    PassOwnPtr<HighlightConfig> highlightConfigFromInspectorObject(ErrorString*, JSONObject* highlightInspectorObject);
 
     // Node-related methods.
     typedef HashMap<RefPtr<Node>, int> NodeToIdMap;
@@ -230,7 +225,7 @@
 
     bool hasBreakpoint(Node*, int type);
     void updateSubtreeBreakpoints(Node* root, uint32_t rootMask, bool value);
-    void descriptionForDOMEvent(Node* target, int breakpointType, bool insertion, PassRefPtr<InspectorObject> description);
+    void descriptionForDOMEvent(Node* target, int breakpointType, bool insertion, PassRefPtr<JSONObject> description);
 
     PassRefPtr<TypeBuilder::DOM::Node> buildObjectForNode(Node*, int depth, NodeToIdMap*);
     PassRefPtr<TypeBuilder::Array<String> > buildArrayForElementAttributes(Element*);
@@ -242,7 +237,7 @@
     void discardBackendBindings();
     void discardFrontendBindings();
 
-    void innerHighlightQuad(PassOwnPtr<FloatQuad>, const RefPtr<InspectorObject>* color, const RefPtr<InspectorObject>* outlineColor);
+    void innerHighlightQuad(PassOwnPtr<FloatQuad>, const RefPtr<JSONObject>* color, const RefPtr<JSONObject>* outlineColor);
 
     InspectorPageAgent* m_pageAgent;
     InjectedScriptManager* m_injectedScriptManager;
diff --git a/Source/core/inspector/InspectorDOMDebuggerAgent.cpp b/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
index b955bb9..5d76e88 100644
--- a/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
+++ b/Source/core/inspector/InspectorDOMDebuggerAgent.cpp
@@ -36,9 +36,9 @@
 #include "core/inspector/InspectorDOMAgent.h"
 #include "core/inspector/InspectorDebuggerAgent.h"
 #include "core/inspector/InspectorState.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/inspector/InstrumentingAgents.h"
-#include <wtf/text/WTFString.h>
+#include "core/platform/JSONValues.h"
+#include "wtf/text/WTFString.h"
 
 namespace {
 
@@ -162,7 +162,7 @@
         return;
     }
 
-    RefPtr<InspectorObject> eventListenerBreakpoints = m_state->getObject(DOMDebuggerAgentState::eventListenerBreakpoints);
+    RefPtr<JSONObject> eventListenerBreakpoints = m_state->getObject(DOMDebuggerAgentState::eventListenerBreakpoints);
     eventListenerBreakpoints->setBoolean(eventName, true);
     m_state->setObject(DOMDebuggerAgentState::eventListenerBreakpoints, eventListenerBreakpoints);
 }
@@ -184,7 +184,7 @@
         return;
     }
 
-    RefPtr<InspectorObject> eventListenerBreakpoints = m_state->getObject(DOMDebuggerAgentState::eventListenerBreakpoints);
+    RefPtr<JSONObject> eventListenerBreakpoints = m_state->getObject(DOMDebuggerAgentState::eventListenerBreakpoints);
     eventListenerBreakpoints->remove(eventName);
     m_state->setObject(DOMDebuggerAgentState::eventListenerBreakpoints, eventListenerBreakpoints);
 }
@@ -192,7 +192,7 @@
 void InspectorDOMDebuggerAgent::didInvalidateStyleAttr(Node* node)
 {
     if (hasBreakpoint(node, AttributeModified)) {
-        RefPtr<InspectorObject> eventData = InspectorObject::create();
+        RefPtr<JSONObject> eventData = JSONObject::create();
         descriptionForDOMEvent(node, AttributeModified, false, eventData.get());
         m_debuggerAgent->breakProgram(InspectorFrontend::Debugger::Reason::DOM, eventData.release());
     }
@@ -292,7 +292,7 @@
 void InspectorDOMDebuggerAgent::willInsertDOMNode(Node* parent)
 {
     if (hasBreakpoint(parent, SubtreeModified)) {
-        RefPtr<InspectorObject> eventData = InspectorObject::create();
+        RefPtr<JSONObject> eventData = JSONObject::create();
         descriptionForDOMEvent(parent, SubtreeModified, true, eventData.get());
         m_debuggerAgent->breakProgram(InspectorFrontend::Debugger::Reason::DOM, eventData.release());
     }
@@ -302,11 +302,11 @@
 {
     Node* parentNode = InspectorDOMAgent::innerParentNode(node);
     if (hasBreakpoint(node, NodeRemoved)) {
-        RefPtr<InspectorObject> eventData = InspectorObject::create();
+        RefPtr<JSONObject> eventData = JSONObject::create();
         descriptionForDOMEvent(node, NodeRemoved, false, eventData.get());
         m_debuggerAgent->breakProgram(InspectorFrontend::Debugger::Reason::DOM, eventData.release());
     } else if (parentNode && hasBreakpoint(parentNode, SubtreeModified)) {
-        RefPtr<InspectorObject> eventData = InspectorObject::create();
+        RefPtr<JSONObject> eventData = JSONObject::create();
         descriptionForDOMEvent(node, SubtreeModified, false, eventData.get());
         m_debuggerAgent->breakProgram(InspectorFrontend::Debugger::Reason::DOM, eventData.release());
     }
@@ -316,13 +316,13 @@
 void InspectorDOMDebuggerAgent::willModifyDOMAttr(Element* element, const AtomicString&, const AtomicString&)
 {
     if (hasBreakpoint(element, AttributeModified)) {
-        RefPtr<InspectorObject> eventData = InspectorObject::create();
+        RefPtr<JSONObject> eventData = JSONObject::create();
         descriptionForDOMEvent(element, AttributeModified, false, eventData.get());
         m_debuggerAgent->breakProgram(InspectorFrontend::Debugger::Reason::DOM, eventData.release());
     }
 }
 
-void InspectorDOMDebuggerAgent::descriptionForDOMEvent(Node* target, int breakpointType, bool insertion, InspectorObject* description)
+void InspectorDOMDebuggerAgent::descriptionForDOMEvent(Node* target, int breakpointType, bool insertion, JSONObject* description)
 {
     ASSERT(hasBreakpoint(target, breakpointType));
 
@@ -379,7 +379,7 @@
         updateSubtreeBreakpoints(child, newRootMask, set);
 }
 
-void InspectorDOMDebuggerAgent::pauseOnNativeEventIfNeeded(PassRefPtr<InspectorObject> eventData, bool synchronous)
+void InspectorDOMDebuggerAgent::pauseOnNativeEventIfNeeded(PassRefPtr<JSONObject> eventData, bool synchronous)
 {
     if (!eventData)
         return;
@@ -389,18 +389,18 @@
         m_debuggerAgent->schedulePauseOnNextStatement(InspectorFrontend::Debugger::Reason::EventListener, eventData);
 }
 
-PassRefPtr<InspectorObject> InspectorDOMDebuggerAgent::preparePauseOnNativeEventData(bool isDOMEvent, const String& eventName)
+PassRefPtr<JSONObject> InspectorDOMDebuggerAgent::preparePauseOnNativeEventData(bool isDOMEvent, const String& eventName)
 {
     String fullEventName = (isDOMEvent ? listenerEventCategoryType : instrumentationEventCategoryType) + eventName;
     if (m_pauseInNextEventListener)
         m_pauseInNextEventListener = false;
     else {
-        RefPtr<InspectorObject> eventListenerBreakpoints = m_state->getObject(DOMDebuggerAgentState::eventListenerBreakpoints);
+        RefPtr<JSONObject> eventListenerBreakpoints = m_state->getObject(DOMDebuggerAgentState::eventListenerBreakpoints);
         if (eventListenerBreakpoints->find(fullEventName) == eventListenerBreakpoints->end())
             return 0;
     }
 
-    RefPtr<InspectorObject> eventData = InspectorObject::create();
+    RefPtr<JSONObject> eventData = JSONObject::create();
     eventData->setString("eventName", fullEventName);
     return eventData.release();
 }
@@ -442,7 +442,7 @@
 
 void InspectorDOMDebuggerAgent::didFireWebGLError(const String& errorName)
 {
-    RefPtr<InspectorObject> eventData = preparePauseOnNativeEventData(false, webglErrorFiredEventName);
+    RefPtr<JSONObject> eventData = preparePauseOnNativeEventData(false, webglErrorFiredEventName);
     if (!eventData)
         return;
     eventData->setString("webglErrorName", errorName);
@@ -456,7 +456,7 @@
         return;
     }
 
-    RefPtr<InspectorObject> xhrBreakpoints = m_state->getObject(DOMDebuggerAgentState::xhrBreakpoints);
+    RefPtr<JSONObject> xhrBreakpoints = m_state->getObject(DOMDebuggerAgentState::xhrBreakpoints);
     xhrBreakpoints->setBoolean(url, true);
     m_state->setObject(DOMDebuggerAgentState::xhrBreakpoints, xhrBreakpoints);
 }
@@ -468,7 +468,7 @@
         return;
     }
 
-    RefPtr<InspectorObject> xhrBreakpoints = m_state->getObject(DOMDebuggerAgentState::xhrBreakpoints);
+    RefPtr<JSONObject> xhrBreakpoints = m_state->getObject(DOMDebuggerAgentState::xhrBreakpoints);
     xhrBreakpoints->remove(url);
     m_state->setObject(DOMDebuggerAgentState::xhrBreakpoints, xhrBreakpoints);
 }
@@ -479,8 +479,8 @@
     if (m_state->getBoolean(DOMDebuggerAgentState::pauseOnAllXHRs))
         breakpointURL = "";
     else {
-        RefPtr<InspectorObject> xhrBreakpoints = m_state->getObject(DOMDebuggerAgentState::xhrBreakpoints);
-        for (InspectorObject::iterator it = xhrBreakpoints->begin(); it != xhrBreakpoints->end(); ++it) {
+        RefPtr<JSONObject> xhrBreakpoints = m_state->getObject(DOMDebuggerAgentState::xhrBreakpoints);
+        for (JSONObject::iterator it = xhrBreakpoints->begin(); it != xhrBreakpoints->end(); ++it) {
             if (url.contains(it->key)) {
                 breakpointURL = it->key;
                 break;
@@ -491,7 +491,7 @@
     if (breakpointURL.isNull())
         return;
 
-    RefPtr<InspectorObject> eventData = InspectorObject::create();
+    RefPtr<JSONObject> eventData = JSONObject::create();
     eventData->setString("breakpointURL", breakpointURL);
     eventData->setString("url", url);
     m_debuggerAgent->breakProgram(InspectorFrontend::Debugger::Reason::XHR, eventData.release());
diff --git a/Source/core/inspector/InspectorDOMDebuggerAgent.h b/Source/core/inspector/InspectorDOMDebuggerAgent.h
index d925081..18d3698 100644
--- a/Source/core/inspector/InspectorDOMDebuggerAgent.h
+++ b/Source/core/inspector/InspectorDOMDebuggerAgent.h
@@ -34,10 +34,9 @@
 
 #include "core/inspector/InspectorBaseAgent.h"
 #include "core/inspector/InspectorDebuggerAgent.h"
-#include <wtf/HashMap.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/HashMap.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -47,9 +46,9 @@
 class InspectorDOMAgent;
 class InspectorDebuggerAgent;
 class InspectorFrontend;
-class InspectorObject;
 class InspectorState;
 class InstrumentingAgents;
+class JSONObject;
 class Node;
 
 typedef String ErrorString;
@@ -96,8 +95,8 @@
 private:
     InspectorDOMDebuggerAgent(InstrumentingAgents*, InspectorCompositeState*, InspectorDOMAgent*, InspectorDebuggerAgent*);
 
-    void pauseOnNativeEventIfNeeded(PassRefPtr<InspectorObject> eventData, bool synchronous);
-    PassRefPtr<InspectorObject> preparePauseOnNativeEventData(bool isDOMEvent, const String& eventName);
+    void pauseOnNativeEventIfNeeded(PassRefPtr<JSONObject> eventData, bool synchronous);
+    PassRefPtr<JSONObject> preparePauseOnNativeEventData(bool isDOMEvent, const String& eventName);
 
     // InspectorDebuggerAgent::Listener implementation.
     virtual void debuggerWasEnabled();
@@ -106,7 +105,7 @@
     virtual void didPause();
     void disable();
 
-    void descriptionForDOMEvent(Node* target, int breakpointType, bool insertion, InspectorObject* description);
+    void descriptionForDOMEvent(Node* target, int breakpointType, bool insertion, JSONObject* description);
     void updateSubtreeBreakpoints(Node*, uint32_t rootMask, bool set);
     bool hasBreakpoint(Node*, int type);
     void discardBindings();
diff --git a/Source/core/inspector/InspectorDOMStorageAgent.cpp b/Source/core/inspector/InspectorDOMStorageAgent.cpp
index 01a4545..65f4812 100644
--- a/Source/core/inspector/InspectorDOMStorageAgent.cpp
+++ b/Source/core/inspector/InspectorDOMStorageAgent.cpp
@@ -30,26 +30,24 @@
 #include "config.h"
 #include "core/inspector/InspectorDOMStorageAgent.h"
 
-#include "DOMException.h"
 #include "InspectorFrontend.h"
+#include "core/dom/DOMException.h"
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/inspector/InspectorPageAgent.h"
 #include "core/inspector/InspectorState.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/page/DOMWindow.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/PageGroup.h"
+#include "core/platform/JSONValues.h"
 #include "core/storage/Storage.h"
 #include "core/storage/StorageArea.h"
 #include "core/storage/StorageNamespace.h"
 #include "weborigin/SecurityOrigin.h"
-
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/Vector.h>
+#include "wtf/MemoryInstrumentationHashMap.h"
 
 namespace WebCore {
 
@@ -76,13 +74,10 @@
     , m_pageAgent(pageAgent)
     , m_frontend(0)
 {
-    m_instrumentingAgents->setInspectorDOMStorageAgent(this);
 }
 
 InspectorDOMStorageAgent::~InspectorDOMStorageAgent()
 {
-    m_instrumentingAgents->setInspectorDOMStorageAgent(0);
-    m_instrumentingAgents = 0;
 }
 
 void InspectorDOMStorageAgent::setFrontend(InspectorFrontend* frontend)
@@ -104,17 +99,19 @@
 void InspectorDOMStorageAgent::enable(ErrorString*)
 {
     m_state->setBoolean(DOMStorageAgentState::domStorageAgentEnabled, true);
+    m_instrumentingAgents->setInspectorDOMStorageAgent(this);
 }
 
 void InspectorDOMStorageAgent::disable(ErrorString*)
 {
+    m_instrumentingAgents->setInspectorDOMStorageAgent(0);
     m_state->setBoolean(DOMStorageAgentState::domStorageAgentEnabled, false);
 }
 
-void InspectorDOMStorageAgent::getDOMStorageItems(ErrorString* errorString, const RefPtr<InspectorObject>& storageId, RefPtr<TypeBuilder::Array<TypeBuilder::Array<String> > >& items)
+void InspectorDOMStorageAgent::getDOMStorageItems(ErrorString* errorString, const RefPtr<JSONObject>& storageId, RefPtr<TypeBuilder::Array<TypeBuilder::Array<String> > >& items)
 {
     Frame* frame;
-    RefPtr<StorageArea> storageArea = findStorageArea(errorString, storageId, frame);
+    OwnPtr<StorageArea> storageArea = findStorageArea(errorString, storageId, frame);
     if (!storageArea)
         return;
 
@@ -138,17 +135,15 @@
 
 static String toErrorString(const ExceptionCode& ec)
 {
-    if (ec) {
-        ExceptionCodeDescription description(ec);
-        return description.name;
-    }
+    if (ec)
+        return DOMException::getErrorName(ec);
     return "";
 }
 
-void InspectorDOMStorageAgent::setDOMStorageItem(ErrorString* errorString, const RefPtr<InspectorObject>& storageId, const String& key, const String& value)
+void InspectorDOMStorageAgent::setDOMStorageItem(ErrorString* errorString, const RefPtr<JSONObject>& storageId, const String& key, const String& value)
 {
     Frame* frame;
-    RefPtr<StorageArea> storageArea = findStorageArea(0, storageId, frame);
+    OwnPtr<StorageArea> storageArea = findStorageArea(0, storageId, frame);
     if (!storageArea) {
         *errorString = "Storage not found";
         return;
@@ -159,10 +154,10 @@
     *errorString = toErrorString(exception);
 }
 
-void InspectorDOMStorageAgent::removeDOMStorageItem(ErrorString* errorString, const RefPtr<InspectorObject>& storageId, const String& key)
+void InspectorDOMStorageAgent::removeDOMStorageItem(ErrorString* errorString, const RefPtr<JSONObject>& storageId, const String& key)
 {
     Frame* frame;
-    RefPtr<StorageArea> storageArea = findStorageArea(0, storageId, frame);
+    OwnPtr<StorageArea> storageArea = findStorageArea(0, storageId, frame);
     if (!storageArea) {
         *errorString = "Storage not found";
         return;
@@ -209,7 +204,7 @@
         m_frontend->domstorage()->domStorageItemUpdated(id, key, oldValue, newValue);
 }
 
-PassRefPtr<StorageArea> InspectorDOMStorageAgent::findStorageArea(ErrorString* errorString, const RefPtr<InspectorObject>& storageId, Frame*& targetFrame)
+PassOwnPtr<StorageArea> InspectorDOMStorageAgent::findStorageArea(ErrorString* errorString, const RefPtr<JSONObject>& storageId, Frame*& targetFrame)
 {
     String securityOrigin;
     bool isLocalStorage = false;
@@ -219,21 +214,20 @@
     if (!success) {
         if (errorString)
             *errorString = "Invalid storageId format";
-        return 0;
+        return nullptr;
     }
 
     Frame* frame = m_pageAgent->findFrameWithSecurityOrigin(securityOrigin);
     if (!frame) {
         if (errorString)
             *errorString = "Frame not found for the given security origin";
-        return 0;
+        return nullptr;
     }
     targetFrame = frame;
 
-    Page* page = m_pageAgent->page();
     if (isLocalStorage)
-        return page->group().localStorage()->storageArea(frame->document()->securityOrigin());
-    return page->sessionStorage()->storageArea(frame->document()->securityOrigin());
+        return StorageNamespace::localStorageArea(frame->document()->securityOrigin());
+    return m_pageAgent->page()->sessionStorage()->storageArea(frame->document()->securityOrigin());
 }
 
 void InspectorDOMStorageAgent::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
diff --git a/Source/core/inspector/InspectorDOMStorageAgent.h b/Source/core/inspector/InspectorDOMStorageAgent.h
index 3cacfba..ba2fb1c 100644
--- a/Source/core/inspector/InspectorDOMStorageAgent.h
+++ b/Source/core/inspector/InspectorDOMStorageAgent.h
@@ -31,18 +31,17 @@
 
 #include "core/inspector/InspectorBaseAgent.h"
 #include "core/storage/StorageArea.h"
-#include <wtf/HashMap.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/PassOwnPtr.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
 class Frame;
-class InspectorArray;
 class InspectorFrontend;
 class InspectorPageAgent;
 class InspectorState;
 class InstrumentingAgents;
+class JSONObject;
 class Page;
 class Storage;
 class StorageArea;
@@ -63,9 +62,9 @@
     // Called from the front-end.
     virtual void enable(ErrorString*);
     virtual void disable(ErrorString*);
-    virtual void getDOMStorageItems(ErrorString*, const RefPtr<InspectorObject>& storageId, RefPtr<TypeBuilder::Array<TypeBuilder::Array<String> > >& items);
-    virtual void setDOMStorageItem(ErrorString*, const RefPtr<InspectorObject>& storageId, const String& key, const String& value);
-    virtual void removeDOMStorageItem(ErrorString*, const RefPtr<InspectorObject>& storageId, const String& key);
+    virtual void getDOMStorageItems(ErrorString*, const RefPtr<JSONObject>& storageId, RefPtr<TypeBuilder::Array<TypeBuilder::Array<String> > >& items);
+    virtual void setDOMStorageItem(ErrorString*, const RefPtr<JSONObject>& storageId, const String& key, const String& value);
+    virtual void removeDOMStorageItem(ErrorString*, const RefPtr<JSONObject>& storageId, const String& key);
 
     // Called from the injected script.
     String storageId(Storage*);
@@ -81,7 +80,7 @@
     InspectorDOMStorageAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorCompositeState*);
 
     bool isEnabled() const;
-    PassRefPtr<StorageArea> findStorageArea(ErrorString*, const RefPtr<InspectorObject>&, Frame*&);
+    PassOwnPtr<StorageArea> findStorageArea(ErrorString*, const RefPtr<JSONObject>&, Frame*&);
 
     InspectorPageAgent* m_pageAgent;
     InspectorFrontend* m_frontend;
diff --git a/Source/core/inspector/InspectorDatabaseAgent.cpp b/Source/core/inspector/InspectorDatabaseAgent.cpp
index d75a3aa..2fbc619 100644
--- a/Source/core/inspector/InspectorDatabaseAgent.cpp
+++ b/Source/core/inspector/InspectorDatabaseAgent.cpp
@@ -35,11 +35,11 @@
 #include "core/html/VoidCallback.h"
 #include "core/inspector/InspectorDatabaseResource.h"
 #include "core/inspector/InspectorState.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
+#include "core/platform/JSONValues.h"
 #include "core/platform/sql/SQLValue.h"
 #include "modules/webdatabase/Database.h"
 #include "modules/webdatabase/SQLError.h"
@@ -89,14 +89,14 @@
         for (size_t i = 0; i < columns.size(); ++i)
             columnNames->addItem(columns[i]);
 
-        RefPtr<TypeBuilder::Array<InspectorValue> > values = TypeBuilder::Array<InspectorValue>::create();
+        RefPtr<TypeBuilder::Array<JSONValue> > values = TypeBuilder::Array<JSONValue>::create();
         const Vector<SQLValue>& data = rowList->values();
         for (size_t i = 0; i < data.size(); ++i) {
             const SQLValue& value = rowList->values()[i];
             switch (value.type()) {
-            case SQLValue::StringValue: values->addItem(InspectorString::create(value.string())); break;
-            case SQLValue::NumberValue: values->addItem(InspectorBasicValue::create(value.number())); break;
-            case SQLValue::NullValue: values->addItem(InspectorValue::null()); break;
+            case SQLValue::StringValue: values->addItem(JSONString::create(value.string())); break;
+            case SQLValue::NumberValue: values->addItem(JSONBasicValue::create(value.number())); break;
+            case SQLValue::NullValue: values->addItem(JSONValue::null()); break;
             }
         }
         m_requestCallback->sendSuccess(columnNames.release(), values.release(), 0);
diff --git a/Source/core/inspector/InspectorDatabaseAgent.h b/Source/core/inspector/InspectorDatabaseAgent.h
index 190e004..39eb8ed 100644
--- a/Source/core/inspector/InspectorDatabaseAgent.h
+++ b/Source/core/inspector/InspectorDatabaseAgent.h
@@ -40,7 +40,6 @@
 class Database;
 class DocumentLoader;
 class Frame;
-class InspectorArray;
 class InspectorDatabaseResource;
 class InspectorFrontend;
 class InspectorState;
diff --git a/Source/core/inspector/InspectorDebuggerAgent.cpp b/Source/core/inspector/InspectorDebuggerAgent.cpp
index 6a847c9..b3e2640 100644
--- a/Source/core/inspector/InspectorDebuggerAgent.cpp
+++ b/Source/core/inspector/InspectorDebuggerAgent.cpp
@@ -38,15 +38,15 @@
 #include "core/inspector/InjectedScriptManager.h"
 #include "core/inspector/InspectorPageAgent.h"
 #include "core/inspector/InspectorState.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/inspector/ScriptArguments.h"
 #include "core/inspector/ScriptCallStack.h"
 #include "core/loader/cache/CachedResource.h"
+#include "core/platform/JSONValues.h"
 #include "core/platform/text/RegularExpression.h"
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/MemoryInstrumentationVector.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/MemoryInstrumentationHashMap.h"
+#include "wtf/MemoryInstrumentationVector.h"
+#include "wtf/text/WTFString.h"
 
 using WebCore::TypeBuilder::Array;
 using WebCore::TypeBuilder::Debugger::FunctionDetails;
@@ -113,7 +113,7 @@
 
 void InspectorDebuggerAgent::disable()
 {
-    m_state->setObject(DebuggerAgentState::javaScriptBreakpoints, InspectorObject::create());
+    m_state->setObject(DebuggerAgentState::javaScriptBreakpoints, JSONObject::create());
     m_state->setLong(DebuggerAgentState::pauseOnExceptionsState, ScriptDebugServer::DontPauseOnExceptions);
     m_instrumentingAgents->setInspectorDebuggerAgent(0);
 
@@ -214,9 +214,9 @@
 }
 
 
-static PassRefPtr<InspectorObject> buildObjectForBreakpointCookie(const String& url, int lineNumber, int columnNumber, const String& condition, bool isRegex)
+static PassRefPtr<JSONObject> buildObjectForBreakpointCookie(const String& url, int lineNumber, int columnNumber, const String& condition, bool isRegex)
 {
-    RefPtr<InspectorObject> breakpointObject = InspectorObject::create();
+    RefPtr<JSONObject> breakpointObject = JSONObject::create();
     breakpointObject->setString("url", url);
     breakpointObject->setNumber("lineNumber", lineNumber);
     breakpointObject->setNumber("columnNumber", columnNumber);
@@ -248,7 +248,7 @@
     bool isRegex = optionalURLRegex;
 
     String breakpointId = (isRegex ? "/" + url + "/" : url) + ':' + String::number(lineNumber) + ':' + String::number(columnNumber);
-    RefPtr<InspectorObject> breakpointsCookie = m_state->getObject(DebuggerAgentState::javaScriptBreakpoints);
+    RefPtr<JSONObject> breakpointsCookie = m_state->getObject(DebuggerAgentState::javaScriptBreakpoints);
     if (breakpointsCookie->find(breakpointId) != breakpointsCookie->end()) {
         *errorString = "Breakpoint at specified location already exists.";
         return;
@@ -268,7 +268,7 @@
     *outBreakpointId = breakpointId;
 }
 
-static bool parseLocation(ErrorString* errorString, RefPtr<InspectorObject> location, String* scriptId, int* lineNumber, int* columnNumber)
+static bool parseLocation(ErrorString* errorString, PassRefPtr<JSONObject> location, String* scriptId, int* lineNumber, int* columnNumber)
 {
     if (!location->getString("scriptId", scriptId) || !location->getNumber("lineNumber", lineNumber)) {
         // FIXME: replace with input validation.
@@ -280,7 +280,7 @@
     return true;
 }
 
-void InspectorDebuggerAgent::setBreakpoint(ErrorString* errorString, const RefPtr<InspectorObject>& location, const String* const optionalCondition, TypeBuilder::Debugger::BreakpointId* outBreakpointId, RefPtr<TypeBuilder::Debugger::Location>& actualLocation)
+void InspectorDebuggerAgent::setBreakpoint(ErrorString* errorString, const RefPtr<JSONObject>& location, const String* const optionalCondition, TypeBuilder::Debugger::BreakpointId* outBreakpointId, RefPtr<TypeBuilder::Debugger::Location>& actualLocation)
 {
     String scriptId;
     int lineNumber;
@@ -306,7 +306,7 @@
 
 void InspectorDebuggerAgent::removeBreakpoint(ErrorString*, const String& breakpointId)
 {
-    RefPtr<InspectorObject> breakpointsCookie = m_state->getObject(DebuggerAgentState::javaScriptBreakpoints);
+    RefPtr<JSONObject> breakpointsCookie = m_state->getObject(DebuggerAgentState::javaScriptBreakpoints);
     breakpointsCookie->remove(breakpointId);
     m_state->setObject(DebuggerAgentState::javaScriptBreakpoints, breakpointsCookie);
 
@@ -326,7 +326,7 @@
     m_breakpointIdToDebugServerBreakpointIds.remove(debugServerBreakpointIdsIterator);
 }
 
-void InspectorDebuggerAgent::continueToLocation(ErrorString* errorString, const RefPtr<InspectorObject>& location)
+void InspectorDebuggerAgent::continueToLocation(ErrorString* errorString, const RefPtr<JSONObject>& location)
 {
     if (!m_continueToLocationBreakpointId.isEmpty()) {
         scriptDebugServer().removeBreakpoint(m_continueToLocationBreakpointId);
@@ -374,11 +374,11 @@
     return location;
 }
 
-static PassRefPtr<InspectorObject> scriptToInspectorObject(ScriptObject scriptObject)
+static PassRefPtr<JSONObject> scriptToInspectorObject(ScriptObject scriptObject)
 {
     if (scriptObject.hasNoValue())
         return 0;
-    RefPtr<InspectorValue> value = scriptObject.toInspectorValue(scriptObject.scriptState());
+    RefPtr<JSONValue> value = scriptObject.toJSONValue(scriptObject.scriptState());
     if (!value)
         return 0;
     return value->asObject();
@@ -396,18 +396,18 @@
         *error = "No script for id: " + scriptId;
 }
 
-void InspectorDebuggerAgent::setScriptSource(ErrorString* error, const String& scriptId, const String& newContent, const bool* const preview, RefPtr<Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<InspectorObject>& result)
+void InspectorDebuggerAgent::setScriptSource(ErrorString* error, RefPtr<TypeBuilder::Debugger::SetScriptSourceError>& errorData, const String& scriptId, const String& newContent, const bool* const preview, RefPtr<Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result)
 {
     bool previewOnly = preview && *preview;
     ScriptObject resultObject;
-    if (!scriptDebugServer().setScriptSource(scriptId, newContent, previewOnly, error, &m_currentCallStack, &resultObject))
+    if (!scriptDebugServer().setScriptSource(scriptId, newContent, previewOnly, error, errorData, &m_currentCallStack, &resultObject))
         return;
     newCallFrames = currentCallFrames();
-    RefPtr<InspectorObject> object = scriptToInspectorObject(resultObject);
+    RefPtr<JSONObject> object = scriptToInspectorObject(resultObject);
     if (object)
         result = object;
 }
-void InspectorDebuggerAgent::restartFrame(ErrorString* errorString, const String& callFrameId, RefPtr<Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<InspectorObject>& result)
+void InspectorDebuggerAgent::restartFrame(ErrorString* errorString, const String& callFrameId, RefPtr<Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result)
 {
     InjectedScript injectedScript = m_injectedScriptManager->injectedScriptForObjectId(callFrameId);
     if (injectedScript.hasNoValue()) {
@@ -439,7 +439,7 @@
     injectedScript.getFunctionDetails(errorString, functionId, &details);
 }
 
-void InspectorDebuggerAgent::schedulePauseOnNextStatement(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<InspectorObject> data)
+void InspectorDebuggerAgent::schedulePauseOnNextStatement(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<JSONObject> data)
 {
     if (m_javaScriptPauseScheduled)
         return;
@@ -616,7 +616,7 @@
 {
 }
 
-void InspectorDebuggerAgent::setVariableValue(ErrorString* errorString, int scopeNumber, const String& variableName, const RefPtr<InspectorObject>& newValue, const String* callFrameId, const String* functionObjectId)
+void InspectorDebuggerAgent::setVariableValue(ErrorString* errorString, int scopeNumber, const String& variableName, const RefPtr<JSONObject>& newValue, const String* callFrameId, const String* functionObjectId)
 {
     InjectedScript injectedScript;
     if (callFrameId) {
@@ -643,7 +643,7 @@
 void InspectorDebuggerAgent::scriptExecutionBlockedByCSP(const String& directiveText)
 {
     if (scriptDebugServer().pauseOnExceptionsState() != ScriptDebugServer::DontPauseOnExceptions) {
-        RefPtr<InspectorObject> directive = InspectorObject::create();
+        RefPtr<JSONObject> directive = JSONObject::create();
         directive->setString("directiveText", directiveText);
         breakProgram(InspectorFrontend::Debugger::Reason::CSPViolation, directive.release());
     }
@@ -666,8 +666,7 @@
     bool deprecated;
     String sourceMapURL = ContentSearchUtils::findSourceMapURL(script.source, ContentSearchUtils::JavaScriptMagicComment, &deprecated);
     if (!sourceMapURL.isEmpty()) {
-        if (deprecated)
-            addConsoleMessage(NetworkMessageSource, WarningMessageLevel, "\"//@ sourceMappingURL=\" source mapping URL declaration is deprecated, \"//# sourceMappingURL=\" declaration should be used instead.", script.url);
+        // FIXME: add deprecated console message here.
         return sourceMapURL;
     }
 
@@ -692,8 +691,7 @@
     if (!script.startLine && !script.startColumn) {
         bool deprecated;
         sourceURL = ContentSearchUtils::findSourceURL(script.source, ContentSearchUtils::JavaScriptMagicComment, &deprecated);
-        if (deprecated)
-            addConsoleMessage(NetworkMessageSource, WarningMessageLevel, "\"//@ sourceURL=\" source URL declaration is deprecated, \"//# sourceURL=\" declaration should be used instead.", script.url);
+        // FIXME: add deprecated console message here.
     }
     bool hasSourceURL = !sourceURL.isEmpty();
     String scriptURL = hasSourceURL ? sourceURL : script.url;
@@ -705,9 +703,9 @@
     if (scriptURL.isEmpty())
         return;
 
-    RefPtr<InspectorObject> breakpointsCookie = m_state->getObject(DebuggerAgentState::javaScriptBreakpoints);
-    for (InspectorObject::iterator it = breakpointsCookie->begin(); it != breakpointsCookie->end(); ++it) {
-        RefPtr<InspectorObject> breakpointObject = it->value->asObject();
+    RefPtr<JSONObject> breakpointsCookie = m_state->getObject(DebuggerAgentState::javaScriptBreakpoints);
+    for (JSONObject::iterator it = breakpointsCookie->begin(); it != breakpointsCookie->end(); ++it) {
+        RefPtr<JSONObject> breakpointObject = it->value->asObject();
         bool isRegex;
         breakpointObject->getBoolean("isRegex", &isRegex);
         String url;
@@ -782,7 +780,7 @@
     return scriptDebugServer().canBreakProgram();
 }
 
-void InspectorDebuggerAgent::breakProgram(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<InspectorObject> data)
+void InspectorDebuggerAgent::breakProgram(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<JSONObject> data)
 {
     m_breakReason = breakReason;
     m_breakAuxData = data;
diff --git a/Source/core/inspector/InspectorDebuggerAgent.h b/Source/core/inspector/InspectorDebuggerAgent.h
index cc5664d..d34cff0 100644
--- a/Source/core/inspector/InspectorDebuggerAgent.h
+++ b/Source/core/inspector/InspectorDebuggerAgent.h
@@ -38,22 +38,19 @@
 #include "core/inspector/ScriptBreakpoint.h"
 #include "core/inspector/ScriptDebugListener.h"
 #include "core/page/ConsoleTypes.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/text/StringHash.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/text/StringHash.h"
 
 namespace WebCore {
 
 class InjectedScriptManager;
 class InspectorFrontend;
-class InspectorArray;
-class InspectorObject;
 class InspectorState;
-class InspectorValue;
 class InstrumentingAgents;
+class JSONObject;
 class ScriptArguments;
 class ScriptCallStack;
 class ScriptDebugServer;
@@ -91,13 +88,13 @@
     virtual void setBreakpointsActive(ErrorString*, bool active);
 
     virtual void setBreakpointByUrl(ErrorString*, int lineNumber, const String* optionalURL, const String* optionalURLRegex, const int* optionalColumnNumber, const String* optionalCondition, TypeBuilder::Debugger::BreakpointId*, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::Location> >& locations);
-    virtual void setBreakpoint(ErrorString*, const RefPtr<InspectorObject>& location, const String* optionalCondition, TypeBuilder::Debugger::BreakpointId*, RefPtr<TypeBuilder::Debugger::Location>& actualLocation);
+    virtual void setBreakpoint(ErrorString*, const RefPtr<JSONObject>& location, const String* optionalCondition, TypeBuilder::Debugger::BreakpointId*, RefPtr<TypeBuilder::Debugger::Location>& actualLocation);
     virtual void removeBreakpoint(ErrorString*, const String& breakpointId);
-    virtual void continueToLocation(ErrorString*, const RefPtr<InspectorObject>& location);
+    virtual void continueToLocation(ErrorString*, const RefPtr<JSONObject>& location);
 
     virtual void searchInContent(ErrorString*, const String& scriptId, const String& query, const bool* optionalCaseSensitive, const bool* optionalIsRegex, RefPtr<TypeBuilder::Array<TypeBuilder::Page::SearchMatch> >&);
-    virtual void setScriptSource(ErrorString*, const String& scriptId, const String& newContent, const bool* preview, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<InspectorObject>& result);
-    virtual void restartFrame(ErrorString*, const String& callFrameId, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<InspectorObject>& result);
+    virtual void setScriptSource(ErrorString*, RefPtr<TypeBuilder::Debugger::SetScriptSourceError>&, const String& scriptId, const String& newContent, const bool* preview, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result);
+    virtual void restartFrame(ErrorString*, const String& callFrameId, RefPtr<TypeBuilder::Array<TypeBuilder::Debugger::CallFrame> >& newCallFrames, RefPtr<JSONObject>& result);
     virtual void getScriptSource(ErrorString*, const String& scriptId, String* scriptSource);
     virtual void getFunctionDetails(ErrorString*, const String& functionId, RefPtr<TypeBuilder::Debugger::FunctionDetails>&);
     virtual void pause(ErrorString*);
@@ -119,13 +116,13 @@
     void compileScript(ErrorString*, const String& expression, const String& sourceURL, TypeBuilder::OptOutput<TypeBuilder::Debugger::ScriptId>*, TypeBuilder::OptOutput<String>* syntaxErrorMessage);
     void runScript(ErrorString*, const TypeBuilder::Debugger::ScriptId&, const int* executionContextId, const String* objectGroup, const bool* doNotPauseOnExceptionsAndMuteConsole, RefPtr<TypeBuilder::Runtime::RemoteObject>& result, TypeBuilder::OptOutput<bool>* wasThrown);
     virtual void setOverlayMessage(ErrorString*, const String*);
-    virtual void setVariableValue(ErrorString*, int in_scopeNumber, const String& in_variableName, const RefPtr<InspectorObject>& in_newValue, const String* in_callFrame, const String* in_functionObjectId);
+    virtual void setVariableValue(ErrorString*, int in_scopeNumber, const String& in_variableName, const RefPtr<JSONObject>& in_newValue, const String* in_callFrame, const String* in_functionObjectId);
 
-    void schedulePauseOnNextStatement(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<InspectorObject> data);
+    void schedulePauseOnNextStatement(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<JSONObject> data);
     void didFireTimer();
     void didHandleEvent();
     bool canBreakProgram();
-    void breakProgram(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<InspectorObject> data);
+    void breakProgram(InspectorFrontend::Debugger::Reason::Enum breakReason, PassRefPtr<JSONObject> data);
     virtual void scriptExecutionBlockedByCSP(const String& directiveText);
 
     class Listener {
@@ -196,7 +193,7 @@
     DebugServerBreakpointToBreakpointIdAndSourceMap m_serverBreakpoints;
     String m_continueToLocationBreakpointId;
     InspectorFrontend::Debugger::Reason::Enum m_breakReason;
-    RefPtr<InspectorObject> m_breakAuxData;
+    RefPtr<JSONObject> m_breakAuxData;
     bool m_javaScriptPauseScheduled;
     Listener* m_listener;
 };
diff --git a/Source/core/inspector/InspectorFrontendHost.cpp b/Source/core/inspector/InspectorFrontendHost.cpp
index d23bdce..f914a14 100644
--- a/Source/core/inspector/InspectorFrontendHost.cpp
+++ b/Source/core/inspector/InspectorFrontendHost.cpp
@@ -48,7 +48,6 @@
 #include "core/platform/network/ResourceResponse.h"
 #include "core/rendering/RenderTheme.h"
 #include "modules/filesystem/DOMFileSystem.h"
-#include <wtf/StdLibExtras.h>
 
 using namespace std;
 
diff --git a/Source/core/inspector/InspectorFrontendHost.h b/Source/core/inspector/InspectorFrontendHost.h
index fb9da0c..83e9344 100644
--- a/Source/core/inspector/InspectorFrontendHost.h
+++ b/Source/core/inspector/InspectorFrontendHost.h
@@ -30,12 +30,10 @@
 #define InspectorFrontendHost_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "core/page/ConsoleTypes.h"
-#include "core/page/ContextMenuProvider.h"
 #include "core/platform/ContextMenu.h"
-#include <wtf/RefCounted.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Vector.h>
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/inspector/InspectorIndexedDBAgent.cpp b/Source/core/inspector/InspectorIndexedDBAgent.cpp
index 31e0736..d138931 100644
--- a/Source/core/inspector/InspectorIndexedDBAgent.cpp
+++ b/Source/core/inspector/InspectorIndexedDBAgent.cpp
@@ -40,8 +40,8 @@
 #include "core/inspector/InjectedScript.h"
 #include "core/inspector/InspectorPageAgent.h"
 #include "core/inspector/InspectorState.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/page/Frame.h"
+#include "core/platform/JSONValues.h"
 #include "modules/indexeddb/DOMWindowIndexedDatabase.h"
 #include "modules/indexeddb/IDBCursor.h"
 #include "modules/indexeddb/IDBCursorWithValue.h"
@@ -320,7 +320,7 @@
     RefPtr<RequestDatabaseCallback> m_requestCallback;
 };
 
-static PassRefPtr<IDBKey> idbKeyFromInspectorObject(InspectorObject* key)
+static PassRefPtr<IDBKey> idbKeyFromInspectorObject(JSONObject* key)
 {
     RefPtr<IDBKey> idbKey;
 
@@ -350,10 +350,10 @@
         idbKey = IDBKey::createDate(date);
     } else if (type == array) {
         IDBKey::KeyArray keyArray;
-        RefPtr<InspectorArray> array = key->getArray("array");
+        RefPtr<JSONArray> array = key->getArray("array");
         for (size_t i = 0; i < array->length(); ++i) {
-            RefPtr<InspectorValue> value = array->get(i);
-            RefPtr<InspectorObject> object;
+            RefPtr<JSONValue> value = array->get(i);
+            RefPtr<JSONObject> object;
             if (!value->asObject(&object))
                 return 0;
             keyArray.append(idbKeyFromInspectorObject(object.get()));
@@ -365,14 +365,14 @@
     return idbKey.release();
 }
 
-static PassRefPtr<IDBKeyRange> idbKeyRangeFromKeyRange(InspectorObject* keyRange)
+static PassRefPtr<IDBKeyRange> idbKeyRangeFromKeyRange(JSONObject* keyRange)
 {
-    RefPtr<InspectorObject> lower = keyRange->getObject("lower");
+    RefPtr<JSONObject> lower = keyRange->getObject("lower");
     RefPtr<IDBKey> idbLower = lower ? idbKeyFromInspectorObject(lower.get()) : 0;
     if (lower && !idbLower)
         return 0;
 
-    RefPtr<InspectorObject> upper = keyRange->getObject("upper");
+    RefPtr<JSONObject> upper = keyRange->getObject("upper");
     RefPtr<IDBKey> idbUpper = upper ? idbKeyFromInspectorObject(upper.get()) : 0;
     if (upper && !idbUpper)
         return 0;
@@ -652,7 +652,7 @@
     databaseLoader->start(idbFactory, document->securityOrigin(), databaseName);
 }
 
-void InspectorIndexedDBAgent::requestData(ErrorString* errorString, const String& securityOrigin, const String& databaseName, const String& objectStoreName, const String& indexName, int skipCount, int pageSize, const RefPtr<InspectorObject>* keyRange, PassRefPtr<RequestDataCallback> requestCallback)
+void InspectorIndexedDBAgent::requestData(ErrorString* errorString, const String& securityOrigin, const String& databaseName, const String& objectStoreName, const String& indexName, int skipCount, int pageSize, const RefPtr<JSONObject>* keyRange, PassRefPtr<RequestDataCallback> requestCallback)
 {
     Frame* frame = m_pageAgent->findFrameWithSecurityOrigin(securityOrigin);
     Document* document = assertDocument(errorString, frame);
diff --git a/Source/core/inspector/InspectorIndexedDBAgent.h b/Source/core/inspector/InspectorIndexedDBAgent.h
index 259b2a7..f008585 100644
--- a/Source/core/inspector/InspectorIndexedDBAgent.h
+++ b/Source/core/inspector/InspectorIndexedDBAgent.h
@@ -58,7 +58,7 @@
     virtual void disable(ErrorString*);
     virtual void requestDatabaseNames(ErrorString*, const String& securityOrigin, PassRefPtr<RequestDatabaseNamesCallback>);
     virtual void requestDatabase(ErrorString*, const String& securityOrigin, const String& databaseName, PassRefPtr<RequestDatabaseCallback>);
-    virtual void requestData(ErrorString*, const String& securityOrigin, const String& databaseName, const String& objectStoreName, const String& indexName, int skipCount, int pageSize, const RefPtr<InspectorObject>* keyRange, PassRefPtr<RequestDataCallback>);
+    virtual void requestData(ErrorString*, const String& securityOrigin, const String& databaseName, const String& objectStoreName, const String& indexName, int skipCount, int pageSize, const RefPtr<JSONObject>* keyRange, PassRefPtr<RequestDataCallback>);
     virtual void clearObjectStore(ErrorString*, const String& in_securityOrigin, const String& in_databaseName, const String& in_objectStoreName, PassRefPtr<ClearObjectStoreCallback>);
 
 private:
diff --git a/Source/core/inspector/InspectorInstrumentation.cpp b/Source/core/inspector/InspectorInstrumentation.cpp
index c70efe8..fc2937f 100644
--- a/Source/core/inspector/InspectorInstrumentation.cpp
+++ b/Source/core/inspector/InspectorInstrumentation.cpp
@@ -36,15 +36,13 @@
 #include "core/inspector/InspectorConsoleAgent.h"
 #include "core/inspector/InspectorController.h"
 #include "core/inspector/InspectorDebuggerAgent.h"
-#include "core/inspector/InspectorPageAgent.h"
 #include "core/inspector/InspectorProfilerAgent.h"
 #include "core/inspector/InspectorResourceAgent.h"
 #include "core/inspector/InspectorTimelineAgent.h"
-#include "core/inspector/InspectorWorkerAgent.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/inspector/WorkerInspectorController.h"
 #include "core/loader/cache/CachedResourceInitiatorInfo.h"
-#include "core/workers/WorkerContext.h"
+#include "core/workers/WorkerGlobalScope.h"
 
 namespace WebCore {
 
@@ -207,17 +205,17 @@
     return instrumentingAgentsForFrame(renderer->frame());
 }
 
-InstrumentingAgents* instrumentingAgentsForWorkerContext(WorkerContext* workerContext)
+InstrumentingAgents* instrumentingAgentsForWorkerGlobalScope(WorkerGlobalScope* workerGlobalScope)
 {
-    if (!workerContext)
+    if (!workerGlobalScope)
         return 0;
-    return instrumentationForWorkerContext(workerContext);
+    return instrumentationForWorkerGlobalScope(workerGlobalScope);
 }
 
 InstrumentingAgents* instrumentingAgentsForNonDocumentContext(ScriptExecutionContext* context)
 {
-    if (context->isWorkerContext())
-        return instrumentationForWorkerContext(static_cast<WorkerContext*>(context));
+    if (context->isWorkerGlobalScope())
+        return instrumentationForWorkerGlobalScope(toWorkerGlobalScope(context));
     return 0;
 }
 
@@ -252,9 +250,9 @@
     return 0;
 }
 
-InstrumentingAgents* instrumentationForWorkerContext(WorkerContext* workerContext)
+InstrumentingAgents* instrumentationForWorkerGlobalScope(WorkerGlobalScope* workerGlobalScope)
 {
-    if (WorkerInspectorController* controller = workerContext->workerInspectorController())
+    if (WorkerInspectorController* controller = workerGlobalScope->workerInspectorController())
         return controller->m_instrumentingAgents.get();
     return 0;
 }
diff --git a/Source/core/inspector/InspectorInstrumentation.h b/Source/core/inspector/InspectorInstrumentation.h
index 6d05983..85421bf 100644
--- a/Source/core/inspector/InspectorInstrumentation.h
+++ b/Source/core/inspector/InspectorInstrumentation.h
@@ -31,17 +31,13 @@
 #ifndef InspectorInstrumentation_h
 #define InspectorInstrumentation_h
 
-#include "bindings/v8/ScriptState.h"
 #include "bindings/v8/ScriptString.h"
-#include "core/css/CSSImportRule.h"
-#include "core/css/CSSRule.h"
 #include "core/css/CSSSelector.h"
 #include "core/css/CSSStyleSheet.h"
 #include "core/dom/Element.h"
 #include "core/dom/EventContext.h"
 #include "core/dom/ScriptExecutionContext.h"
 #include "core/inspector/ConsoleAPITypes.h"
-#include "core/page/ConsoleTypes.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/platform/network/FormData.h"
@@ -51,8 +47,6 @@
 #include "modules/websockets/WebSocketHandshakeRequest.h"
 #include "modules/websockets/WebSocketHandshakeResponse.h"
 #include "wtf/RefPtr.h"
-#include "wtf/UnusedParam.h"
-#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -95,8 +89,8 @@
 class StyleRule;
 class StyleSheet;
 class ThreadableLoaderClient;
-class WorkerContext;
-class WorkerContextProxy;
+class WorkerGlobalScope;
+class WorkerGlobalScopeProxy;
 class XMLHttpRequest;
 
 #define FAST_RETURN_IF_NO_FRONTENDS(value) if (!hasFrontends()) return value;
@@ -144,7 +138,7 @@
 InstrumentingAgents* instrumentingAgentsForRenderObject(RenderObject*);
 InstrumentingAgents* instrumentingAgentsForElement(Element*);
 
-InstrumentingAgents* instrumentingAgentsForWorkerContext(WorkerContext*);
+InstrumentingAgents* instrumentingAgentsForWorkerGlobalScope(WorkerGlobalScope*);
 InstrumentingAgents* instrumentingAgentsForNonDocumentContext(ScriptExecutionContext*);
 
 }  // namespace InspectorInstrumentation
@@ -205,7 +199,7 @@
 
 InstrumentingAgents* instrumentationForPage(Page*);
 
-InstrumentingAgents* instrumentationForWorkerContext(WorkerContext*);
+InstrumentingAgents* instrumentationForWorkerGlobalScope(WorkerGlobalScope*);
 
 } // namespace WebCore
 
diff --git a/Source/core/inspector/InspectorInstrumentation.idl b/Source/core/inspector/InspectorInstrumentation.idl
index 1e8d82e..f90e47e 100644
--- a/Source/core/inspector/InspectorInstrumentation.idl
+++ b/Source/core/inspector/InspectorInstrumentation.idl
@@ -36,7 +36,7 @@
 *
 * The syntax for an instrumentation method is as follows:
 *
-*    [methodAttributes] returnValue methodName([paramAttributes] paramList)
+*    [methodAttributes] returnValue methodName([paramAttr1] param1, [paramAttr2] param2, ...)
 *
 * Where:
 *   methodAttributes - optional list of method attributes.
@@ -48,8 +48,9 @@
 *       Attributes without "=" are the names of the agents to be invoked.
 *           Examples: DOM, Page, Debugger.
 *
-*   paramAttributes - options list of attributes controlling the parameters handling.
+*   paramAttr - optional attribute controlling the parameters handling (one attribute per parameter max).
 *       Keep - pass first parameter (used to access the InstrumentingAgents instance) to agents.
+*       FastReturn - return early from the inline method if this parameter is 0/false.
 *
 *   returnValue: C++ return value. Only "void" and "InspectorInstrumentationCookie" are supported.
 *
@@ -111,6 +112,9 @@
     [CSS, Inline=FastReturn]
     void didUpdateRegionLayout([Keep] Document*, NamedFlow*);
 
+    [CSS, Inline=FastReturn]
+    void didChangeRegionOverset([Keep] Document*, NamedFlow*);
+
     [DOMDebugger, Inline=FastReturn]
     void willSendXMLHttpRequest(ScriptExecutionContext*, const String& url);
 
@@ -225,8 +229,8 @@
     [CSS, Inline=FastReturn]
     void didMatchRule(const InspectorInstrumentationCookie&, bool matched);
 
-    [CSS, Inline=Custom]
-    InspectorInstrumentationCookie willProcessRule(Document* document, StyleRule* rule, StyleResolver* styleResolver);
+    [CSS, Inline=FastReturn]
+    InspectorInstrumentationCookie willProcessRule(Document* document, [FastReturn] StyleRule* rule, StyleResolver* styleResolver);
 
     [CSS, Inline=FastReturn]
     void didProcessRule(const InspectorInstrumentationCookie&);
@@ -372,13 +376,13 @@
     void didDispatchDOMStorageEvent(Page* page, const String& key, const String& oldValue, const String& newValue, StorageType storageType, SecurityOrigin* securityOrigin);
 
     [Worker]
-    void didStartWorkerContext(ScriptExecutionContext*, WorkerContextProxy* proxy, const KURL& url);
+    void didStartWorkerGlobalScope(ScriptExecutionContext*, WorkerGlobalScopeProxy* proxy, const KURL& url);
 
     [WorkerRuntime]
-    void willEvaluateWorkerScript([Keep] WorkerContext* context, int workerThreadStartMode);
+    void willEvaluateWorkerScript([Keep] WorkerGlobalScope* context, int workerThreadStartMode);
 
     [Worker]
-    void workerContextTerminated(ScriptExecutionContext*, WorkerContextProxy* proxy);
+    void workerGlobalScopeTerminated(ScriptExecutionContext*, WorkerGlobalScopeProxy* proxy);
 
     [Resource, Timeline]
     void didCreateWebSocket([Keep] Document*, unsigned long identifier, const KURL& requestURL, const String& protocol);
@@ -430,14 +434,14 @@
     void addMessageToConsole(Page* page, MessageSource source, MessageType type, MessageLevel level, const String& message, ScriptState* state, PassRefPtr<ScriptArguments> arguments, unsigned long requestIdentifier = 0);
 
     [Console]
-    void addMessageToConsole(Page* page, MessageSource source, MessageType type, MessageLevel level, const String& message, const String& scriptId, unsigned lineNumber, ScriptState* state = 0, unsigned long requestIdentifier = 0);
+    void addMessageToConsole(Page* page, MessageSource source, MessageType type, MessageLevel level, const String& message, const String& scriptId, unsigned lineNumber, unsigned columnNumber = 0, ScriptState* state = 0, unsigned long requestIdentifier = 0);
 
     // FIXME: Convert to ScriptArguments to match non-worker context.
     // Use the same implementation as above as a similar method dispatched on Page.
-    void addMessageToConsole(WorkerContext* workerContext, MessageSource source, MessageType type, MessageLevel level, const String& message, PassRefPtr<ScriptCallStack> callStack, unsigned long requestIdentifier = 0);
+    void addMessageToConsole(WorkerGlobalScope* workerGlobalScope, MessageSource source, MessageType type, MessageLevel level, const String& message, PassRefPtr<ScriptCallStack> callStack, unsigned long requestIdentifier = 0);
 
     // Use the same implementation as above as a similar method dispatched on Page.
-    void addMessageToConsole(WorkerContext* workerContext, MessageSource source, MessageType type, MessageLevel level, const String& message, const String& scriptId, unsigned lineNumber, ScriptState* state, unsigned long requestIdentifier = 0);
+    void addMessageToConsole(WorkerGlobalScope* workerGlobalScope, MessageSource source, MessageType type, MessageLevel level, const String& message, const String& scriptId, unsigned lineNumber, unsigned columnNumber, ScriptState* state, unsigned long requestIdentifier = 0);
 
     [Console]
     void consoleCount(Page* page, ScriptState* state, PassRefPtr<ScriptArguments> arguments);
diff --git a/Source/core/inspector/InspectorInstrumentationCustomInl.h b/Source/core/inspector/InspectorInstrumentationCustomInl.h
index 8657666..4a181f6 100644
--- a/Source/core/inspector/InspectorInstrumentationCustomInl.h
+++ b/Source/core/inspector/InspectorInstrumentationCustomInl.h
@@ -37,7 +37,6 @@
 
 bool profilerEnabledImpl(InstrumentingAgents*);
 bool isDebuggerPausedImpl(InstrumentingAgents*);
-InspectorInstrumentationCookie willProcessRuleImpl(InstrumentingAgents*, StyleRule*, StyleResolver*);
 bool collectingHTMLParseErrorsImpl(InstrumentingAgents*);
 
 bool canvasAgentEnabled(ScriptExecutionContext*);
@@ -59,16 +58,6 @@
     return false;
 }
 
-inline InspectorInstrumentationCookie willProcessRule(Document* document, StyleRule* rule, StyleResolver* styleResolver)
-{
-    FAST_RETURN_IF_NO_FRONTENDS(InspectorInstrumentationCookie());
-    if (!rule)
-        return InspectorInstrumentationCookie();
-    if (InstrumentingAgents* instrumentingAgents = instrumentingAgentsForDocument(document))
-        return willProcessRuleImpl(instrumentingAgents, rule, styleResolver);
-    return InspectorInstrumentationCookie();
-}
-
 inline bool collectingHTMLParseErrors(Page* page)
 {
     FAST_RETURN_IF_NO_FRONTENDS(false);
diff --git a/Source/core/inspector/InspectorLayerTreeAgent.h b/Source/core/inspector/InspectorLayerTreeAgent.h
index cfb8765..f77c5cb 100644
--- a/Source/core/inspector/InspectorLayerTreeAgent.h
+++ b/Source/core/inspector/InspectorLayerTreeAgent.h
@@ -34,10 +34,9 @@
 #include "InspectorTypeBuilder.h"
 #include "core/inspector/InspectorBaseAgent.h"
 #include "core/rendering/RenderLayer.h"
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Vector.h>
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/inspector/InspectorMemoryAgent.cpp b/Source/core/inspector/InspectorMemoryAgent.cpp
index 017c362..7c576db 100644
--- a/Source/core/inspector/InspectorMemoryAgent.cpp
+++ b/Source/core/inspector/InspectorMemoryAgent.cpp
@@ -40,22 +40,20 @@
 #include "core/inspector/HeapGraphSerializer.h"
 #include "core/inspector/InspectorClient.h"
 #include "core/inspector/InspectorDOMStorageAgent.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/inspector/MemoryInstrumentationImpl.h"
 #include "core/loader/cache/MemoryCache.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
+#include "core/platform/JSONValues.h"
 #include "core/platform/MemoryUsageSupport.h"
-#include <wtf/ArrayBufferView.h>
-#include <wtf/HashSet.h>
-#include <wtf/MemoryInstrumentationArrayBufferView.h>
-#include <wtf/NonCopyingSort.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/text/StringBuilder.h>
-#include <wtf/text/StringImpl.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Vector.h>
+#include "wtf/ArrayBufferView.h"
+#include "wtf/MemoryInstrumentationArrayBufferView.h"
+#include "wtf/NonCopyingSort.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/text/StringImpl.h"
+#include "wtf/text/WTFString.h"
 
 // Use a type alias instead of 'using' here which would cause a conflict on Mac.
 typedef WebCore::TypeBuilder::Memory::MemoryBlock InspectorMemoryBlock;
@@ -298,7 +296,7 @@
     getProcessMemoryDistributionImpl(false, memoryInfo);
 }
 
-void InspectorMemoryAgent::getProcessMemoryDistribution(ErrorString*, const bool* reportGraph, RefPtr<InspectorMemoryBlock>& processMemory, RefPtr<InspectorObject>& graphMetaInformation)
+void InspectorMemoryAgent::getProcessMemoryDistribution(ErrorString*, const bool* reportGraph, RefPtr<InspectorMemoryBlock>& processMemory, RefPtr<JSONObject>& graphMetaInformation)
 {
     TypeNameToSizeMap memoryInfo;
     graphMetaInformation = getProcessMemoryDistributionImpl(reportGraph && *reportGraph, &memoryInfo);
@@ -339,9 +337,9 @@
 
 }
 
-PassRefPtr<InspectorObject> InspectorMemoryAgent::getProcessMemoryDistributionImpl(bool reportGraph, TypeNameToSizeMap* memoryInfo)
+PassRefPtr<JSONObject> InspectorMemoryAgent::getProcessMemoryDistributionImpl(bool reportGraph, TypeNameToSizeMap* memoryInfo)
 {
-    RefPtr<InspectorObject> meta;
+    RefPtr<JSONObject> meta;
     OwnPtr<HeapGraphSerializer> graphSerializer;
     OwnPtr<FrontendWrapper> frontendWrapper;
 
diff --git a/Source/core/inspector/InspectorMemoryAgent.h b/Source/core/inspector/InspectorMemoryAgent.h
index 0f580c3..bc39faa 100644
--- a/Source/core/inspector/InspectorMemoryAgent.h
+++ b/Source/core/inspector/InspectorMemoryAgent.h
@@ -59,7 +59,7 @@
     virtual ~InspectorMemoryAgent();
 
     virtual void getDOMCounters(ErrorString*, int* documents, int* nodes, int* jsEventListeners);
-    virtual void getProcessMemoryDistribution(ErrorString*, const bool* reportGraph, RefPtr<TypeBuilder::Memory::MemoryBlock>& out_processMemory, RefPtr<InspectorObject>& graphMetaInformation);
+    virtual void getProcessMemoryDistribution(ErrorString*, const bool* reportGraph, RefPtr<TypeBuilder::Memory::MemoryBlock>& out_processMemory, RefPtr<JSONObject>& graphMetaInformation);
 
     virtual void reportMemoryUsage(MemoryObjectInfo*) const;
 
@@ -71,7 +71,7 @@
 private:
     InspectorMemoryAgent(InstrumentingAgents*, InspectorClient*, InspectorCompositeState*, Page*);
 
-    PassRefPtr<InspectorObject> getProcessMemoryDistributionImpl(bool reportGraph, HashMap<String, size_t>* memoryInfo);
+    PassRefPtr<JSONObject> getProcessMemoryDistributionImpl(bool reportGraph, HashMap<String, size_t>* memoryInfo);
 
     InspectorClient* m_inspectorClient;
     Page* m_page;
diff --git a/Source/core/inspector/InspectorOverlay.cpp b/Source/core/inspector/InspectorOverlay.cpp
index 4a27580..5964d55 100644
--- a/Source/core/inspector/InspectorOverlay.cpp
+++ b/Source/core/inspector/InspectorOverlay.cpp
@@ -35,11 +35,9 @@
 #include "bindings/v8/ScriptSourceCode.h"
 #include "core/dom/Element.h"
 #include "core/dom/Node.h"
-#include "core/dom/StyledElement.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/inspector/InspectorClient.h"
 #include "core/inspector/InspectorOverlayHost.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/EmptyClients.h"
 #include "core/page/Chrome.h"
@@ -48,13 +46,13 @@
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
+#include "core/platform/JSONValues.h"
 #include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/PlatformTouchEvent.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/rendering/RenderBoxModelObject.h"
 #include "core/rendering/RenderInline.h"
 #include "core/rendering/RenderObject.h"
-#include <wtf/text/StringBuilder.h>
+#include "wtf/text/StringBuilder.h"
 
 namespace WebCore {
 
@@ -234,6 +232,8 @@
     , m_drawViewSizeWithGrid(false)
     , m_timer(this, &InspectorOverlay::onTimer)
     , m_overlayHost(InspectorOverlayHost::create())
+    , m_overrides(0)
+    , m_overridesTopOffset(0)
 {
 }
 
@@ -262,12 +262,23 @@
         return false;
 
     EventHandler* eventHandler = overlayPage()->mainFrame()->eventHandler();
+    bool result;
     switch (event.type()) {
-    case PlatformEvent::MouseMoved: return eventHandler->mouseMoved(event);
-    case PlatformEvent::MousePressed: return eventHandler->handleMousePressEvent(event);
-    case PlatformEvent::MouseReleased: return eventHandler->handleMouseReleaseEvent(event);
-    default: return false;
+    case PlatformEvent::MouseMoved:
+        result = eventHandler->mouseMoved(event);
+        break;
+    case PlatformEvent::MousePressed:
+        result = eventHandler->handleMousePressEvent(event);
+        break;
+    case PlatformEvent::MouseReleased:
+        result = eventHandler->handleMouseReleaseEvent(event);
+        break;
+    default:
+        return false;
     }
+
+    overlayPage()->mainFrame()->document()->updateLayout();
+    return result;
 }
 
 bool InspectorOverlay::handleTouchEvent(const PlatformTouchEvent& event)
@@ -314,6 +325,25 @@
     update();
 }
 
+void InspectorOverlay::setOverride(OverrideType type, bool enabled)
+{
+    bool currentEnabled = m_overrides & type;
+    if (currentEnabled == enabled)
+        return;
+    if (enabled)
+        m_overrides |= type;
+    else
+        m_overrides &= ~type;
+    update();
+}
+
+void InspectorOverlay::setOverridesTopOffset(int offset)
+{
+    m_overridesTopOffset = offset;
+    if (m_overrides)
+        update();
+}
+
 void InspectorOverlay::hideHighlight()
 {
     m_highlightNode.clear();
@@ -352,7 +382,7 @@
 
 bool InspectorOverlay::isEmpty()
 {
-    bool hasAlwaysVisibleElements = m_highlightNode || m_eventTargetNode || m_highlightQuad || !m_size.isEmpty() || m_drawViewSize;
+    bool hasAlwaysVisibleElements = m_highlightNode || m_eventTargetNode || m_highlightQuad || m_overrides || !m_size.isEmpty() || m_drawViewSize;
     bool hasInvisibleInInspectModeElements = !m_pausedInDebuggerMessage.isNull();
     return !(hasAlwaysVisibleElements || (hasInvisibleInInspectModeElements && !m_inspectModeEnabled));
 }
@@ -384,6 +414,7 @@
     if (!m_inspectModeEnabled)
         drawPausedInDebuggerMessage();
     drawViewSize();
+    drawOverridesMessage();
 
     // Position DOM elements.
     overlayPage()->mainFrame()->document()->recalcStyle(Node::Force);
@@ -404,20 +435,22 @@
     m_size = IntSize();
     m_drawViewSize = false;
     m_drawViewSizeWithGrid = false;
+    m_overrides = 0;
+    m_overridesTopOffset = 0;
     update();
 }
 
-static PassRefPtr<InspectorObject> buildObjectForPoint(const FloatPoint& point)
+static PassRefPtr<JSONObject> buildObjectForPoint(const FloatPoint& point)
 {
-    RefPtr<InspectorObject> object = InspectorObject::create();
+    RefPtr<JSONObject> object = JSONObject::create();
     object->setNumber("x", point.x());
     object->setNumber("y", point.y());
     return object.release();
 }
 
-static PassRefPtr<InspectorArray> buildArrayForQuad(const FloatQuad& quad)
+static PassRefPtr<JSONArray> buildArrayForQuad(const FloatQuad& quad)
 {
-    RefPtr<InspectorArray> array = InspectorArray::create();
+    RefPtr<JSONArray> array = JSONArray::create();
     array->pushObject(buildObjectForPoint(quad.p1()));
     array->pushObject(buildObjectForPoint(quad.p2()));
     array->pushObject(buildObjectForPoint(quad.p3()));
@@ -425,10 +458,10 @@
     return array.release();
 }
 
-static PassRefPtr<InspectorObject> buildObjectForHighlight(const Highlight& highlight)
+static PassRefPtr<JSONObject> buildObjectForHighlight(const Highlight& highlight)
 {
-    RefPtr<InspectorObject> object = InspectorObject::create();
-    RefPtr<InspectorArray> array = InspectorArray::create();
+    RefPtr<JSONObject> object = JSONObject::create();
+    RefPtr<JSONArray> array = JSONArray::create();
     for (size_t i = 0; i < highlight.quads.size(); ++i)
         array->pushArray(buildArrayForQuad(highlight.quads[i]));
     object->setArray("quads", array.release());
@@ -442,9 +475,9 @@
     return object.release();
 }
 
-static PassRefPtr<InspectorObject> buildObjectForSize(const IntSize& size)
+static PassRefPtr<JSONObject> buildObjectForSize(const IntSize& size)
 {
-    RefPtr<InspectorObject> result = InspectorObject::create();
+    RefPtr<JSONObject> result = JSONObject::create();
     result->setNumber("width", size.width());
     result->setNumber("height", size.height());
     return result.release();
@@ -467,11 +500,11 @@
         buildNodeHighlight(m_eventTargetNode.get(), m_nodeHighlightConfig, &eventTargetHighlight);
         highlight.quads.append(eventTargetHighlight.quads[1]); // Add border from eventTargetNode to highlight.
     }
-    RefPtr<InspectorObject> highlightObject = buildObjectForHighlight(highlight);
+    RefPtr<JSONObject> highlightObject = buildObjectForHighlight(highlight);
 
     Node* node = m_highlightNode.get();
     if (node->isElementNode() && m_nodeHighlightConfig.showInfo && node->renderer() && node->document()->frame()) {
-        RefPtr<InspectorObject> elementInfo = InspectorObject::create();
+        RefPtr<JSONObject> elementInfo = JSONObject::create();
         Element* element = toElement(node);
         bool isXHTML = element->document()->isXHTMLDocument();
         elementInfo->setString("tagName", isXHTML ? element->nodeName() : element->nodeName().lower());
@@ -479,7 +512,7 @@
         HashSet<AtomicString> usedClassNames;
         if (element->hasClass() && element->isStyledElement()) {
             StringBuilder classNames;
-            const SpaceSplitString& classNamesString = static_cast<StyledElement*>(element)->classNames();
+            const SpaceSplitString& classNamesString = element->classNames();
             size_t classNameCount = classNamesString.size();
             for (size_t i = 0; i < classNameCount; ++i) {
                 const AtomicString& className = classNamesString[i];
@@ -525,6 +558,14 @@
         evaluateInOverlay("drawViewSize", m_drawViewSizeWithGrid ? "true" : "false");
 }
 
+void InspectorOverlay::drawOverridesMessage()
+{
+    RefPtr<JSONObject> data = JSONObject::create();
+    data->setNumber("overrides", m_overrides);
+    data->setNumber("topOffset", m_overridesTopOffset);
+    evaluateInOverlay("drawOverridesMessage", data.release());
+}
+
 Page* InspectorOverlay::overlayPage()
 {
     if (m_overlayPage)
@@ -562,11 +603,9 @@
     frame->view()->setCanHaveScrollbars(false);
     frame->view()->setTransparent(true);
     ASSERT(loader->activeDocumentLoader());
-    loader->activeDocumentLoader()->writer()->setMIMEType("text/html");
-    loader->activeDocumentLoader()->writer()->begin();
-    loader->activeDocumentLoader()->writer()->addData(reinterpret_cast<const char*>(InspectorOverlayPage_html), sizeof(InspectorOverlayPage_html));
-    loader->activeDocumentLoader()->writer()->end();
-
+    DocumentWriter* writer = loader->activeDocumentLoader()->beginWriting("text/html", "UTF-8");
+    writer->addData(reinterpret_cast<const char*>(InspectorOverlayPage_html), sizeof(InspectorOverlayPage_html));
+    loader->activeDocumentLoader()->endWriting(writer);
     v8::HandleScope handleScope;
     v8::Handle<v8::Context> frameContext = frame->script()->currentWorldContext();
     v8::Context::Scope contextScope(frameContext);
@@ -587,7 +626,7 @@
 
 void InspectorOverlay::reset(const IntSize& viewportSize, const IntSize& frameViewFullSize, int scrollX, int scrollY)
 {
-    RefPtr<InspectorObject> resetData = InspectorObject::create();
+    RefPtr<JSONObject> resetData = JSONObject::create();
     resetData->setNumber("pageScaleFactor", m_page->pageScaleFactor());
     resetData->setNumber("deviceScaleFactor", m_page->deviceScaleFactor());
     resetData->setObject("viewportSize", buildObjectForSize(viewportSize));
@@ -600,15 +639,15 @@
 
 void InspectorOverlay::evaluateInOverlay(const String& method, const String& argument)
 {
-    RefPtr<InspectorArray> command = InspectorArray::create();
+    RefPtr<JSONArray> command = JSONArray::create();
     command->pushString(method);
     command->pushString(argument);
     overlayPage()->mainFrame()->script()->executeScriptInMainWorld(ScriptSourceCode("dispatch(" + command->toJSONString() + ")"));
 }
 
-void InspectorOverlay::evaluateInOverlay(const String& method, PassRefPtr<InspectorValue> argument)
+void InspectorOverlay::evaluateInOverlay(const String& method, PassRefPtr<JSONValue> argument)
 {
-    RefPtr<InspectorArray> command = InspectorArray::create();
+    RefPtr<JSONArray> command = JSONArray::create();
     command->pushString(method);
     command->pushValue(argument);
     overlayPage()->mainFrame()->script()->executeScriptInMainWorld(ScriptSourceCode("dispatch(" + command->toJSONString() + ")"));
diff --git a/Source/core/inspector/InspectorOverlay.h b/Source/core/inspector/InspectorOverlay.h
index d742dfd..574222e 100644
--- a/Source/core/inspector/InspectorOverlay.h
+++ b/Source/core/inspector/InspectorOverlay.h
@@ -47,8 +47,8 @@
 class GraphicsContext;
 class InspectorClient;
 class InspectorOverlayHost;
-class InspectorValue;
 class IntRect;
+class JSONValue;
 class Node;
 class Page;
 class PlatformMouseEvent;
@@ -107,6 +107,15 @@
 class InspectorOverlay {
     WTF_MAKE_FAST_ALLOCATED;
 public:
+    // This must be kept in sync with the overrideEntries array in InspectorOverlayPage.html.
+    enum OverrideType {
+        UserAgentOverride = 1,
+        DeviceMetricsOverride = 1 << 1,
+        GeolocationOverride = 1 << 2,
+        DeviceOrientationOverride = 1 << 3,
+        TouchOverride = 1 << 4,
+        CSSMediaOverride = 1 << 5
+    };
     static PassOwnPtr<InspectorOverlay> create(Page* page, InspectorClient* client)
     {
         return adoptPtr(new InspectorOverlay(page, client));
@@ -124,6 +133,8 @@
 
     void setPausedInDebuggerMessage(const String*);
     void setInspectModeEnabled(bool);
+    void setOverride(OverrideType, bool);
+    void setOverridesTopOffset(int);
 
     void hideHighlight();
     void highlightNode(Node*, Node* eventTarget, const HighlightConfig&);
@@ -150,11 +161,12 @@
     void drawQuadHighlight();
     void drawPausedInDebuggerMessage();
     void drawViewSize();
+    void drawOverridesMessage();
 
     Page* overlayPage();
     void reset(const IntSize& viewportSize, const IntSize& frameViewFullSize, int scrollX, int scrollY);
     void evaluateInOverlay(const String& method, const String& argument);
-    void evaluateInOverlay(const String& method, PassRefPtr<InspectorValue> argument);
+    void evaluateInOverlay(const String& method, PassRefPtr<JSONValue> argument);
     void onTimer(Timer<InspectorOverlay>*);
 
     Page* m_page;
@@ -173,6 +185,8 @@
     bool m_drawViewSize;
     bool m_drawViewSizeWithGrid;
     Timer<InspectorOverlay> m_timer;
+    unsigned m_overrides;
+    int m_overridesTopOffset;
 };
 
 } // namespace WebCore
diff --git a/Source/core/inspector/InspectorOverlayHost.cpp b/Source/core/inspector/InspectorOverlayHost.cpp
index e28cf6f..830dd54 100644
--- a/Source/core/inspector/InspectorOverlayHost.cpp
+++ b/Source/core/inspector/InspectorOverlayHost.cpp
@@ -30,8 +30,6 @@
 
 #include "InspectorOverlayHost.h"
 
-#include "InspectorController.h"
-
 namespace WebCore {
 
 InspectorOverlayHost::InspectorOverlayHost()
diff --git a/Source/core/inspector/InspectorOverlayPage.html b/Source/core/inspector/InspectorOverlayPage.html
index 14ce216..4d6f021 100644
--- a/Source/core/inspector/InspectorOverlayPage.html
+++ b/Source/core/inspector/InspectorOverlayPage.html
@@ -34,6 +34,10 @@
     padding: 0;
 }
 
+body.touch {
+    cursor: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABUAAAAVCAQAAAADHm0dAAABH0lEQVR4XpWTO2rDQBCG18S6gAWCoD6VFHKCCBZsN7qACgenFZn/OAZDrConMahJzmGM+oBJMfmziIUs8UMOXzHD7seyzMMwJOEDZ7r4ftEFZy5PwtvfNKIliE/Z4hVbFwmHZfRXTfWZWOEOI5iekctXINx5GqopZSdTmCOm2AmFt15lpMu9TGBOMsFe9InjXmVBzGHOMgfBR6cyJtYwF1mDYGyYEdmAmoNgZmgPcjOgjvEltEarFmaQd2hltN5cob5B6ytf/YBW//krMyIfUO99BWKiGVCbvq6+W+UFsfTd8jPQSXJGTND1MxBMViflyRe7YLK8rEuiQQ5fDRfz/o/uPD3egoIgDtJig9ZFwlGEWxASM6PVSmutaF0eh7c/zBRVQt5j3yoAAAAASUVORK5CYII=) 10 10, auto !important;
+}
+
 body.platform-mac {
     font-size: 11px;
     font-family: Menlo, Monaco;
@@ -163,6 +167,30 @@
     background-color: darkgray;
 }
 
+#overrides-container {
+    display: inline-block;
+    padding: 0 0 10px 10px;
+    position: absolute;
+    top: 0;
+    right: 0;
+}
+
+#overrides-message > div:not(:first-child) {
+    text-indent: 8px;
+}
+
+#overrides-message {
+    display: inline-block;
+    font-size: 14px;
+    padding: 4px 6px;
+    color: red;
+    background-color: rgba(17, 17, 17, 0.843); /* Same as DebugColors::HUDBackgroundColor() */
+}
+
+#overrides-container:hover #overrides-message,
+#overrides-container.hidden #overrides-message {
+    visibility: hidden;
+}
 </style>
 <script>
 const lightGridColor = "rgba(0,0,0,0.2)";
@@ -170,6 +198,13 @@
 const transparentColor = "rgba(0, 0, 0, 0)";
 const gridBackgroundColor = "rgba(255, 255, 255, 0.8)";
 
+// The order must correspond to that in InspectorOverlay::OverrideType.
+const overrideEntries = ["User-Agent", "Device Metrics", "Geolocation", "Device Orientation", "Touch", "Media"];
+const overrideTouchBit = 1 << 4;
+
+var overridesContainer;
+var overridesMessageElement;
+
 function drawPausedInDebuggerMessage(message)
 {
     document.querySelector(".controls-line").style.visibility = "visible";
@@ -410,6 +445,39 @@
         _drawGrid();
 }
 
+function drawOverridesMessage(data)
+{
+    overridesContainer.style.top = data.topOffset + "px";
+    var overrides = data.overrides;
+    overridesMessageElement.textContent = "";
+    if (!overrides) {
+        overridesContainer.classList.add("hidden");
+        document.body.classList.remove("touch");
+        return;
+    }
+
+    var header = document.createElement("div");
+    header.id = "overrides-header";
+    header.textContent = "Overrides:";
+    overridesMessageElement.appendChild(header);
+
+    var maskBit = 1;
+    for (var i = 0; i < overrideEntries.length; ++i, maskBit <<= 1) {
+        if (!(overrides & maskBit))
+            continue;
+        var item = document.createElement("div");
+        item.textContent = overrideEntries[i];
+        overridesMessageElement.appendChild(item);
+    }
+
+    overridesContainer.classList.remove("hidden");
+    var hasTouch = overrides & overrideTouchBit;
+    if (hasTouch)
+        document.body.classList.add("touch");
+    else
+        document.body.classList.remove("touch");
+}
+
 function reset(resetData)
 {
     window.viewportSize = resetData.viewportSize;
@@ -689,10 +757,31 @@
     InspectorOverlayHost.stepOver();
 }
 
+function onMouseMotion(isOverElement)
+{
+    if (!overridesMessageElement.textContent.length)
+        return;
+    if (isOverElement)
+        overridesContainer.classList.add("hidden");
+    else
+        overridesContainer.classList.remove("hidden");
+}
+
+function onFocus()
+{
+    if (overridesMessageElement.textContent.length)
+        overridesContainer.classList.remove("hidden");
+}
+
 function onLoaded()
 {
+    overridesContainer = document.getElementById("overrides-container");
+    overridesMessageElement = document.getElementById("overrides-message");
     document.getElementById("resume-button").addEventListener("click", onResumeClick);
     document.getElementById("step-over-button").addEventListener("click", onStepOverClick);
+    overridesContainer.addEventListener("mousemove", onMouseMotion.bind(this, true));
+    overridesContainer.addEventListener("mouseout", onMouseMotion.bind(this, false));
+    window.addEventListener("focus", onFocus);
 }
 
 window.addEventListener("DOMContentLoaded", onLoaded);
@@ -713,5 +802,8 @@
 </div>
 <div id="right-gutter"></div>
 <div id="bottom-gutter"></div>
+<div id="overrides-container">
+  <div id="overrides-message"></div>
+</div>
 <div id="log"></div>
 </html>
diff --git a/Source/core/inspector/InspectorPageAgent.cpp b/Source/core/inspector/InspectorPageAgent.cpp
index 41bfe99..7c33d1b 100644
--- a/Source/core/inspector/InspectorPageAgent.cpp
+++ b/Source/core/inspector/InspectorPageAgent.cpp
@@ -35,7 +35,6 @@
 #include "InspectorFrontend.h"
 #include "bindings/v8/DOMWrapperWorld.h"
 #include "bindings/v8/ScriptController.h"
-#include "bindings/v8/ScriptObject.h"
 #include "core/dom/DOMImplementation.h"
 #include "core/dom/DeviceOrientationController.h"
 #include "core/dom/Document.h"
@@ -49,7 +48,6 @@
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/inspector/InspectorOverlay.h"
 #include "core/inspector/InspectorState.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/loader/CookieJar.h"
 #include "core/loader/DocumentLoader.h"
@@ -68,15 +66,14 @@
 #include "core/page/PageConsole.h"
 #include "core/page/Settings.h"
 #include "core/platform/Cookie.h"
+#include "core/platform/JSONValues.h"
 #include "core/platform/text/RegularExpression.h"
 #include "modules/geolocation/GeolocationController.h"
-#include "modules/geolocation/GeolocationError.h"
 #include "weborigin/SecurityOrigin.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/ListHashSet.h"
 #include "wtf/Vector.h"
 #include "wtf/text/Base64.h"
-#include "wtf/text/StringBuilder.h"
 #include "wtf/text/TextEncoding.h"
 
 using namespace std;
@@ -95,6 +92,7 @@
 static const char pageAgentContinuousPaintingEnabled[] = "pageAgentContinuousPaintingEnabled";
 static const char pageAgentShowPaintRects[] = "pageAgentShowPaintRects";
 static const char pageAgentShowDebugBorders[] = "pageAgentShowDebugBorders";
+static const char pageAgentShowScrollBottleneckRects[] = "pageAgentShowScrollBottleneckRects";
 static const char touchEventEmulationEnabled[] = "touchEventEmulationEnabled";
 static const char pageAgentEmulatedMedia[] = "pageAgentEmulatedMedia";
 static const char showSizeOnResize[] = "showSizeOnResize";
@@ -363,6 +361,8 @@
         setEmulatedMedia(0, emulatedMedia);
         bool continuousPaintingEnabled = m_state->getBoolean(PageAgentState::pageAgentContinuousPaintingEnabled);
         setContinuousPaintingEnabled(0, continuousPaintingEnabled);
+        bool showScrollBottleneckRects = m_state->getBoolean(PageAgentState::pageAgentShowScrollBottleneckRects);
+        setShowScrollBottleneckRects(0, showScrollBottleneckRects);
 
         int currentWidth = static_cast<int>(m_state->getLong(PageAgentState::pageAgentScreenWidthOverride));
         int currentHeight = static_cast<int>(m_state->getLong(PageAgentState::pageAgentScreenHeightOverride));
@@ -399,6 +399,7 @@
     setShowFPSCounter(0, false);
     setEmulatedMedia(0, "");
     setContinuousPaintingEnabled(0, false);
+    setShowScrollBottleneckRects(0, false);
     setShowViewportSizeOnResize(0, false, 0);
     if (m_didForceCompositingMode)
         setForceCompositingMode(0, false);
@@ -416,9 +417,9 @@
 
 void InspectorPageAgent::addScriptToEvaluateOnLoad(ErrorString*, const String& source, String* identifier)
 {
-    RefPtr<InspectorObject> scripts = m_state->getObject(PageAgentState::pageAgentScriptsToEvaluateOnLoad);
+    RefPtr<JSONObject> scripts = m_state->getObject(PageAgentState::pageAgentScriptsToEvaluateOnLoad);
     if (!scripts) {
-        scripts = InspectorObject::create();
+        scripts = JSONObject::create();
         m_state->setObject(PageAgentState::pageAgentScriptsToEvaluateOnLoad, scripts);
     }
     // Assure we don't override existing ids -- m_lastScriptIdentifier could get out of sync WRT actual
@@ -434,7 +435,7 @@
 
 void InspectorPageAgent::removeScriptToEvaluateOnLoad(ErrorString* error, const String& identifier)
 {
-    RefPtr<InspectorObject> scripts = m_state->getObject(PageAgentState::pageAgentScriptsToEvaluateOnLoad);
+    RefPtr<JSONObject> scripts = m_state->getObject(PageAgentState::pageAgentScriptsToEvaluateOnLoad);
     if (!scripts || scripts->find(identifier) == scripts->end()) {
         *error = "Script not found";
         return;
@@ -711,8 +712,6 @@
 {
     m_state->setBoolean(PageAgentState::pageAgentShowDebugBorders, show);
     m_client->setShowDebugBorders(show);
-    if (mainFrame() && mainFrame()->view())
-        mainFrame()->view()->invalidate();
 }
 
 void InspectorPageAgent::setShowFPSCounter(ErrorString*, bool show)
@@ -720,8 +719,7 @@
     m_state->setBoolean(PageAgentState::pageAgentShowFPSCounter, show);
     m_client->setShowFPSCounter(show);
 
-    if (mainFrame() && mainFrame()->view())
-        mainFrame()->view()->invalidate();
+    updateOverridesTopOffset();
 }
 
 void InspectorPageAgent::setContinuousPaintingEnabled(ErrorString*, bool enabled)
@@ -729,8 +727,13 @@
     m_state->setBoolean(PageAgentState::pageAgentContinuousPaintingEnabled, enabled);
     m_client->setContinuousPaintingEnabled(enabled);
 
-    if (!enabled && mainFrame() && mainFrame()->view())
-        mainFrame()->view()->invalidate();
+    updateOverridesTopOffset();
+}
+
+void InspectorPageAgent::setShowScrollBottleneckRects(ErrorString*, bool show)
+{
+    m_state->setBoolean(PageAgentState::pageAgentShowScrollBottleneckRects, show);
+    m_client->setShowScrollBottleneckRects(show);
 }
 
 void InspectorPageAgent::getScriptExecutionStatus(ErrorString*, PageCommandHandler::Result::Enum* status)
@@ -780,10 +783,10 @@
     if (!m_frontend)
         return;
 
-    RefPtr<InspectorObject> scripts = m_state->getObject(PageAgentState::pageAgentScriptsToEvaluateOnLoad);
+    RefPtr<JSONObject> scripts = m_state->getObject(PageAgentState::pageAgentScriptsToEvaluateOnLoad);
     if (scripts) {
-        InspectorObject::const_iterator end = scripts->end();
-        for (InspectorObject::const_iterator it = scripts->begin(); it != end; ++it) {
+        JSONObject::const_iterator end = scripts->end();
+        for (JSONObject::const_iterator it = scripts->begin(); it != end; ++it) {
             String scriptText;
             if (it->value->asString(&scriptText))
                 frame->script()->executeScript(scriptText);
@@ -804,8 +807,10 @@
         setForceCompositingMode(0, true);
 }
 
-void InspectorPageAgent::loadEventFired(Frame*)
+void InspectorPageAgent::loadEventFired(Frame* frame)
 {
+    if (frame->page()->mainFrame() != frame)
+        return;
     m_frontend->loadEventFired(currentTime());
 }
 
@@ -902,7 +907,7 @@
         return String();
     String deprecatedHeaderSourceMapURL = resource->response().httpHeaderField(deprecatedSourceMapHttpHeader);
     if (!deprecatedHeaderSourceMapURL.isEmpty()) {
-        m_page->console()->addMessage(NetworkMessageSource, WarningMessageLevel, "Resource is served with deprecated header X-SourceMap, SourceMap should be used instead.", url, 0);
+        // FIXME: add deprecated console message here.
         return deprecatedHeaderSourceMapURL;
     }
     return resource->response().httpHeaderField(sourceMapHttpHeader);
@@ -1107,6 +1112,7 @@
     if (document)
         document->styleResolverChanged(RecalcStyleImmediately);
     InspectorInstrumentation::mediaQueryResultChanged(document);
+    m_overlay->setOverride(InspectorOverlay::DeviceMetricsOverride, width && height);
 }
 
 void InspectorPageAgent::updateTouchEventEmulationInPage(bool enabled)
@@ -1114,6 +1120,19 @@
     m_state->setBoolean(PageAgentState::touchEventEmulationEnabled, enabled);
     if (mainFrame() && mainFrame()->settings())
         mainFrame()->settings()->setTouchEventEmulationEnabled(enabled);
+    m_overlay->setOverride(InspectorOverlay::TouchOverride, enabled);
+}
+
+void InspectorPageAgent::updateOverridesTopOffset()
+{
+    static const int continousPaintingGraphHeight = 92;
+    static const int fpsGraphHeight = 73;
+    int topOffset = 0;
+    if (m_state->getBoolean(PageAgentState::pageAgentContinuousPaintingEnabled))
+        topOffset = continousPaintingGraphHeight;
+    else if (m_state->getBoolean(PageAgentState::pageAgentShowFPSCounter))
+        topOffset = fpsGraphHeight;
+    m_overlay->setOverridesTopOffset(topOffset);
 }
 
 void InspectorPageAgent::setGeolocationOverride(ErrorString* error, const double* latitude, const double* longitude, const double* accuracy)
@@ -1135,6 +1154,7 @@
         m_geolocationPosition.clear();
 
     controller->positionChanged(0); // Kick location update.
+    m_overlay->setOverride(InspectorOverlay::GeolocationOverride, true);
 }
 
 void InspectorPageAgent::clearGeolocationOverride(ErrorString*)
@@ -1147,6 +1167,7 @@
     GeolocationController* controller = GeolocationController::from(m_page);
     if (controller && m_platformGeolocationPosition.get())
         controller->positionChanged(m_platformGeolocationPosition.get());
+    m_overlay->setOverride(InspectorOverlay::GeolocationOverride, false);
 }
 
 GeolocationPosition* InspectorPageAgent::overrideGeolocationPosition(GeolocationPosition* position)
@@ -1172,11 +1193,13 @@
 
     m_deviceOrientation = DeviceOrientationData::create(true, alpha, true, beta, true, gamma);
     controller->didChangeDeviceOrientation(m_deviceOrientation.get());
+    m_overlay->setOverride(InspectorOverlay::DeviceOrientationOverride, true);
 }
 
 void InspectorPageAgent::clearDeviceOrientationOverride(ErrorString*)
 {
     m_deviceOrientation.clear();
+    m_overlay->setOverride(InspectorOverlay::DeviceOrientationOverride, false);
 }
 
 DeviceOrientationData* InspectorPageAgent::overrideDeviceOrientation(DeviceOrientationData* deviceOrientation)
@@ -1207,6 +1230,7 @@
         document->styleResolverChanged(RecalcStyleImmediately);
         document->updateLayout();
     }
+    m_overlay->setOverride(InspectorOverlay::CSSMediaOverride, !media.isEmpty());
 }
 
 void InspectorPageAgent::applyEmulatedMedia(String* media)
@@ -1235,20 +1259,6 @@
     mainFrame->view()->updateCompositingLayersAfterStyleChange();
 }
 
-void InspectorPageAgent::getCompositingBordersVisible(ErrorString* error, bool* outParam)
-{
-    Settings* settings = m_page->settings();
-    *outParam = settings->showDebugBorders() || settings->showRepaintCounter();
-}
-
-void InspectorPageAgent::setCompositingBordersVisible(ErrorString*, bool visible)
-{
-    Settings* settings = m_page->settings();
-
-    settings->setShowDebugBorders(visible);
-    settings->setShowRepaintCounter(visible);
-}
-
 void InspectorPageAgent::captureScreenshot(ErrorString*, String*)
 {
     // Handled on the browser level.
diff --git a/Source/core/inspector/InspectorPageAgent.h b/Source/core/inspector/InspectorPageAgent.h
index af638d1..f73f6f9 100644
--- a/Source/core/inspector/InspectorPageAgent.h
+++ b/Source/core/inspector/InspectorPageAgent.h
@@ -36,10 +36,8 @@
 #include "core/dom/DeviceOrientationData.h"
 #include "core/inspector/InspectorBaseAgent.h"
 #include "modules/geolocation/GeolocationPosition.h"
-#include <wtf/HashMap.h>
-#include <wtf/RefCounted.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Vector.h>
+#include "wtf/HashMap.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -106,6 +104,7 @@
     virtual void setShowDebugBorders(ErrorString*, bool show);
     virtual void setShowFPSCounter(ErrorString*, bool show);
     virtual void setContinuousPaintingEnabled(ErrorString*, bool enabled);
+    virtual void setShowScrollBottleneckRects(ErrorString*, bool show);
     virtual void getScriptExecutionStatus(ErrorString*, PageCommandHandler::Result::Enum*);
     virtual void setScriptExecutionDisabled(ErrorString*, bool);
     virtual void setGeolocationOverride(ErrorString*, const double*, const double*, const double*);
@@ -115,8 +114,6 @@
     virtual void setTouchEmulationEnabled(ErrorString*, bool);
     virtual void setEmulatedMedia(ErrorString*, const String&);
     virtual void setForceCompositingMode(ErrorString*, bool force);
-    virtual void getCompositingBordersVisible(ErrorString*, bool* out_param);
-    virtual void setCompositingBordersVisible(ErrorString*, bool);
     virtual void captureScreenshot(ErrorString*, String* data);
     virtual void handleJavaScriptDialog(ErrorString*, bool accept, const String* promptText);
     virtual void setShowViewportSizeOnResize(ErrorString*, bool show, const bool* showGrid);
@@ -178,6 +175,7 @@
     bool deviceMetricsChanged(int width, int height, double fontScaleFactor, bool fitWindow);
     void updateViewMetrics(int, int, double, bool);
     void updateTouchEventEmulationInPage(bool);
+    void updateOverridesTopOffset();
 
     static bool dataContent(const char* data, unsigned size, const String& textEncodingName, bool withBase64Encode, String* result);
 
diff --git a/Source/core/inspector/InspectorProfilerAgent.cpp b/Source/core/inspector/InspectorProfilerAgent.cpp
index d84ef17..dc2f7e6 100644
--- a/Source/core/inspector/InspectorProfilerAgent.cpp
+++ b/Source/core/inspector/InspectorProfilerAgent.cpp
@@ -31,26 +31,19 @@
 #include "core/inspector/InspectorProfilerAgent.h"
 
 #include "InspectorFrontend.h"
-#include "bindings/v8/PageScriptDebugServer.h"
-#include "bindings/v8/ScriptObject.h"
 #include "bindings/v8/ScriptProfiler.h"
-#include "bindings/v8/WorkerScriptDebugServer.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/inspector/ConsoleAPITypes.h"
 #include "core/inspector/InjectedScript.h"
 #include "core/inspector/InjectedScriptHost.h"
 #include "core/inspector/InspectorConsoleAgent.h"
 #include "core/inspector/InspectorState.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/inspector/ScriptCallStack.h"
 #include "core/inspector/ScriptProfile.h"
-#include "core/page/Console.h"
 #include "core/page/ConsoleTypes.h"
-#include "core/page/Page.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/MemoryInstrumentationHashMap.h"
-#include "wtf/OwnPtr.h"
 #include "wtf/text/StringConcatenate.h"
 
 namespace WebCore {
diff --git a/Source/core/inspector/InspectorProfilerAgent.h b/Source/core/inspector/InspectorProfilerAgent.h
index 98f48ba..d30be1e 100644
--- a/Source/core/inspector/InspectorProfilerAgent.h
+++ b/Source/core/inspector/InspectorProfilerAgent.h
@@ -42,16 +42,14 @@
 namespace WebCore {
 
 class InjectedScriptManager;
-class InspectorArray;
 class InspectorConsoleAgent;
 class InspectorFrontend;
-class InspectorObject;
 class InspectorState;
 class InstrumentingAgents;
 class Page;
 class ScriptCallStack;
 class ScriptProfile;
-class WorkerContext;
+class WorkerGlobalScope;
 
 typedef String ErrorString;
 
diff --git a/Source/core/inspector/InspectorResourceAgent.cpp b/Source/core/inspector/InspectorResourceAgent.cpp
index c9ea29e..9b15d6e 100644
--- a/Source/core/inspector/InspectorResourceAgent.cpp
+++ b/Source/core/inspector/InspectorResourceAgent.cpp
@@ -34,30 +34,28 @@
 #include "InspectorFrontend.h"
 #include "bindings/v8/ScriptCallStackFactory.h"
 #include "core/dom/Document.h"
-#include "core/dom/Event.h"
-#include "core/dom/EventListener.h"
-#include "core/dom/EventTarget.h"
-#include "core/dom/ExceptionCode.h"
 #include "core/dom/ExceptionCodePlaceholder.h"
 #include "core/dom/ScriptableDocumentParser.h"
 #include "core/inspector/IdentifiersFactory.h"
 #include "core/inspector/InspectorClient.h"
+#include "core/inspector/InspectorOverlay.h"
 #include "core/inspector/InspectorPageAgent.h"
 #include "core/inspector/InspectorState.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/inspector/NetworkResourcesData.h"
 #include "core/inspector/ScriptCallStack.h"
 #include "core/loader/DocumentLoader.h"
+#include "core/loader/DocumentThreadableLoader.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/ResourceLoader.h"
-#include "core/loader/UniqueIdentifier.h"
-#include "core/loader/cache/CachedRawResource.h"
+#include "core/loader/ThreadableLoader.h"
+#include "core/loader/ThreadableLoaderClient.h"
 #include "core/loader/cache/CachedResource.h"
 #include "core/loader/cache/CachedResourceInitiatorInfo.h"
 #include "core/loader/cache/MemoryCache.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
+#include "core/platform/JSONValues.h"
 #include "core/platform/network/HTTPHeaderMap.h"
 #include "core/platform/network/ResourceError.h"
 #include "core/platform/network/ResourceRequest.h"
@@ -68,11 +66,8 @@
 #include "modules/websockets/WebSocketHandshakeResponse.h"
 #include "weborigin/KURL.h"
 #include "wtf/CurrentTime.h"
-#include "wtf/HexNumber.h"
-#include "wtf/ListHashSet.h"
 #include "wtf/MemoryInstrumentationHashMap.h"
 #include "wtf/RefPtr.h"
-#include "wtf/text/StringBuilder.h"
 
 typedef WebCore::InspectorBackendDispatcher::NetworkCommandHandler::LoadResourceForFrontendCallback LoadResourceForFrontendCallback;
 
@@ -87,47 +82,92 @@
 
 namespace {
 
-class SendXHRCallback : public EventListener {
-    WTF_MAKE_NONCOPYABLE(SendXHRCallback);
+static PassRefPtr<JSONObject> buildObjectForHeaders(const HTTPHeaderMap& headers)
+{
+    RefPtr<JSONObject> headersObject = JSONObject::create();
+    HTTPHeaderMap::const_iterator end = headers.end();
+    for (HTTPHeaderMap::const_iterator it = headers.begin(); it != end; ++it)
+        headersObject->setString(it->key.string(), it->value);
+    return headersObject;
+}
+
+class InspectorThreadableLoaderClient : public ThreadableLoaderClient {
+    WTF_MAKE_NONCOPYABLE(InspectorThreadableLoaderClient);
 public:
-    static PassRefPtr<SendXHRCallback> create(PassRefPtr<LoadResourceForFrontendCallback> callback)
+    InspectorThreadableLoaderClient(PassRefPtr<LoadResourceForFrontendCallback> callback)
+        : m_callback(callback)
+        , m_statusCode(0) { }
+
+    virtual ~InspectorThreadableLoaderClient() { }
+
+    virtual void didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
     {
-        return adoptRef(new SendXHRCallback(callback));
+        WTF::TextEncoding textEncoding(response.textEncodingName());
+        bool useDetector = false;
+        if (!textEncoding.isValid()) {
+            textEncoding = UTF8Encoding();
+            useDetector = true;
+        }
+        m_decoder = TextResourceDecoder::create("text/plain", textEncoding, useDetector);
+        m_statusCode = response.httpStatusCode();
+        m_responseHeaders = response.httpHeaderFields();
     }
 
-    virtual ~SendXHRCallback() { }
-
-    virtual bool operator==(const EventListener& other) OVERRIDE
+    virtual void didReceiveData(const char* data, int dataLength)
     {
-        return this == &other;
+        if (!dataLength)
+            return;
+
+        if (dataLength == -1)
+            dataLength = strlen(data);
+
+        m_responseText = m_responseText.concatenateWith(m_decoder->decode(data, dataLength));
     }
 
-    virtual void handleEvent(ScriptExecutionContext*, Event* event) OVERRIDE
+    virtual void didFinishLoading(unsigned long /*identifier*/, double /*finishTime*/)
     {
-        if (!m_callback->isActive())
-            return;
-        if (event->type() == eventNames().errorEvent) {
-            m_callback->sendFailure("Error loading resource.");
-            return;
-        }
-        if (event->type() != eventNames().readystatechangeEvent) {
-            m_callback->sendFailure("Unexpected event type.");
-            return;
-        }
+        if (m_decoder)
+            m_responseText = m_responseText.concatenateWith(m_decoder->flush());
+        m_callback->sendSuccess(m_statusCode, buildObjectForHeaders(m_responseHeaders), m_responseText.flattenToString());
+        dispose();
+    }
 
-        XMLHttpRequest* xhr = static_cast<XMLHttpRequest*>(event->target());
-        if (xhr->readyState() != XMLHttpRequest::DONE)
-            return;
+    virtual void didFail(const ResourceError&)
+    {
+        m_callback->sendFailure("Loading resource for inspector failed");
+        dispose();
+    }
 
-        ScriptString responseText = xhr->responseText(IGNORE_EXCEPTION);
-        m_callback->sendSuccess(responseText.flattenToString());
+    virtual void didFailRedirectCheck()
+    {
+        m_callback->sendFailure("Loading resource for inspector failed redirect check");
+        dispose();
+    }
+
+    void didFailLoaderCreation()
+    {
+        m_callback->sendFailure("Couldn't create a loader");
+        dispose();
+    }
+
+    void setLoader(PassRefPtr<ThreadableLoader> loader)
+    {
+        m_loader = loader;
     }
 
 private:
-    SendXHRCallback(PassRefPtr<LoadResourceForFrontendCallback> callback)
-        : EventListener(EventListener::CPPEventListenerType)
-        , m_callback(callback) { }
+    void dispose()
+    {
+        m_loader = 0;
+        delete this;
+    }
+
     RefPtr<LoadResourceForFrontendCallback> m_callback;
+    RefPtr<ThreadableLoader> m_loader;
+    RefPtr<TextResourceDecoder> m_decoder;
+    ScriptString m_responseText;
+    int m_statusCode;
+    HTTPHeaderMap m_responseHeaders;
 };
 
 KURL urlWithoutFragment(const KURL& url)
@@ -157,15 +197,6 @@
         enable();
 }
 
-static PassRefPtr<InspectorObject> buildObjectForHeaders(const HTTPHeaderMap& headers)
-{
-    RefPtr<InspectorObject> headersObject = InspectorObject::create();
-    HTTPHeaderMap::const_iterator end = headers.end();
-    for (HTTPHeaderMap::const_iterator it = headers.begin(); it != end; ++it)
-        headersObject->setString(it->key.string(), it->value);
-    return headersObject;
-}
-
 static PassRefPtr<TypeBuilder::Network::ResourceTiming> buildObjectForTiming(const ResourceLoadTiming& timing, DocumentLoader* loader)
 {
     return TypeBuilder::Network::ResourceTiming::create()
@@ -210,7 +241,7 @@
         status = response.httpStatusCode();
         statusText = response.httpStatusText();
     }
-    RefPtr<InspectorObject> headers;
+    RefPtr<JSONObject> headers;
     if (response.resourceLoadInfo())
         headers = buildObjectForHeaders(response.resourceLoadInfo()->responseHeaders);
     else
@@ -267,11 +298,11 @@
     String requestId = IdentifiersFactory::requestId(identifier);
     m_resourcesData->resourceCreated(requestId, m_pageAgent->loaderId(loader));
 
-    RefPtr<InspectorObject> headers = m_state->getObject(ResourceAgentState::extraRequestHeaders);
+    RefPtr<JSONObject> headers = m_state->getObject(ResourceAgentState::extraRequestHeaders);
 
     if (headers) {
-        InspectorObject::const_iterator end = headers->end();
-        for (InspectorObject::const_iterator it = headers->begin(); it != end; ++it) {
+        JSONObject::const_iterator end = headers->end();
+        for (JSONObject::const_iterator it = headers->begin(); it != end; ++it) {
             String value;
             if (it->value->asString(&value))
                 request.setHTTPHeaderField(it->key, value);
@@ -362,31 +393,15 @@
         finishTime = loader->timing()->monotonicTimeToPseudoWallTime(monotonicFinishTime);
 
     String requestId = IdentifiersFactory::requestId(identifier);
-    if (m_resourcesData->resourceType(requestId) == InspectorPageAgent::DocumentResource) {
-        RefPtr<SharedBuffer> buffer = loader->frameLoader()->documentLoader()->mainResourceData();
-        m_resourcesData->addResourceSharedBuffer(requestId, buffer, loader->frame()->document()->inputEncoding());
-    }
-
     m_resourcesData->maybeDecodeDataToContent(requestId);
-
     if (!finishTime)
         finishTime = currentTime();
-
     m_frontend->loadingFinished(requestId, finishTime);
 }
 
 void InspectorResourceAgent::didFailLoading(unsigned long identifier, DocumentLoader* loader, const ResourceError& error)
 {
     String requestId = IdentifiersFactory::requestId(identifier);
-
-    if (m_resourcesData->resourceType(requestId) == InspectorPageAgent::DocumentResource) {
-        Frame* frame = loader ? loader->frame() : 0;
-        if (frame && frame->loader()->documentLoader() && frame->document()) {
-            RefPtr<SharedBuffer> buffer = frame->loader()->documentLoader()->mainResourceData();
-            m_resourcesData->addResourceSharedBuffer(requestId, buffer, frame->document()->inputEncoding());
-        }
-    }
-
     bool canceled = error.isCancellation();
     m_frontend->loadingFailed(requestId, currentTime(), error.localizedDescription(), canceled ? &canceled : 0);
 }
@@ -600,9 +615,10 @@
 void InspectorResourceAgent::setUserAgentOverride(ErrorString*, const String& userAgent)
 {
     m_state->setString(ResourceAgentState::userAgentOverride, userAgent);
+    m_overlay->setOverride(InspectorOverlay::UserAgentOverride, !userAgent.isEmpty());
 }
 
-void InspectorResourceAgent::setExtraHTTPHeaders(ErrorString*, const RefPtr<InspectorObject>& headers)
+void InspectorResourceAgent::setExtraHTTPHeaders(ErrorString*, const RefPtr<JSONObject>& headers)
 {
     m_state->setObject(ResourceAgentState::extraRequestHeaders, headers);
 }
@@ -687,7 +703,7 @@
         memoryCache()->evictResources();
 }
 
-void InspectorResourceAgent::loadResourceForFrontend(ErrorString* errorString, const String& frameId, const String& url, PassRefPtr<LoadResourceForFrontendCallback> callback)
+void InspectorResourceAgent::loadResourceForFrontend(ErrorString* errorString, const String& frameId, const String& url, const RefPtr<JSONObject>* requestHeaders, PassRefPtr<LoadResourceForFrontendCallback> callback)
 {
     Frame* frame = m_pageAgent->assertFrame(errorString, frameId);
     if (!frame)
@@ -699,30 +715,39 @@
         return;
     }
 
-    RefPtr<XMLHttpRequest> xhr = XMLHttpRequest::create(document);
-
     KURL kurl = KURL(ParsedURLString, url);
     if (kurl.isLocalFile()) {
         *errorString = "Can not load local file";
         return;
     }
 
-    ExceptionCode ec = 0;
-    xhr->open(ASCIILiteral("GET"), kurl, ec);
-    if (ec) {
-        *errorString = "Error opening an XMLHttpRequest";
-        return;
+    ResourceRequest request(url);
+    request.setHTTPMethod("GET");
+    request.setCachePolicy(ReloadIgnoringCacheData);
+    if (requestHeaders) {
+        for (JSONObject::iterator it = (*requestHeaders)->begin(); it != (*requestHeaders)->end(); ++it) {
+            String value;
+            bool success = it->value->asString(&value);
+            if (!success) {
+                *errorString = "Request header \"" + it->key + "\" value is not a string";
+                return;
+            }
+            request.addHTTPHeaderField(it->key, value);
+        }
     }
 
-    RefPtr<SendXHRCallback> sendXHRCallback = SendXHRCallback::create(callback);
-    xhr->addEventListener(eventNames().abortEvent, sendXHRCallback, false);
-    xhr->addEventListener(eventNames().errorEvent, sendXHRCallback, false);
-    xhr->addEventListener(eventNames().readystatechangeEvent, sendXHRCallback, false);
-    xhr->sendForInspector(ec);
-    if (ec) {
-        *errorString = "Error sending an XMLHttpRequest";
+    ThreadableLoaderOptions options;
+    options.allowCredentials = DoNotAllowStoredCredentials;
+    options.crossOriginRequestPolicy = AllowCrossOriginRequests;
+
+    InspectorThreadableLoaderClient* inspectorThreadableLoaderClient = new InspectorThreadableLoaderClient(callback);
+    RefPtr<DocumentThreadableLoader> loader = DocumentThreadableLoader::create(document, inspectorThreadableLoaderClient, request, options);
+    if (!loader) {
+        inspectorThreadableLoaderClient->didFailLoaderCreation();
         return;
     }
+    loader->setDefersLoading(false);
+    inspectorThreadableLoaderClient->setLoader(loader.release());
 }
 
 void InspectorResourceAgent::didCommitLoad(Frame* frame, DocumentLoader* loader)
@@ -749,10 +774,11 @@
     info.addMember(m_styleRecalculationInitiator, "styleRecalculationInitiator");
 }
 
-InspectorResourceAgent::InspectorResourceAgent(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorClient* client, InspectorCompositeState* state)
+InspectorResourceAgent::InspectorResourceAgent(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorClient* client, InspectorCompositeState* state, InspectorOverlay* overlay)
     : InspectorBaseAgent<InspectorResourceAgent>("Network", instrumentingAgents, state)
     , m_pageAgent(pageAgent)
     , m_client(client)
+    , m_overlay(overlay)
     , m_frontend(0)
     , m_resourcesData(adoptPtr(new NetworkResourcesData()))
     , m_loadingXHRSynchronously(false)
diff --git a/Source/core/inspector/InspectorResourceAgent.h b/Source/core/inspector/InspectorResourceAgent.h
index 40827c6..ec3771a 100644
--- a/Source/core/inspector/InspectorResourceAgent.h
+++ b/Source/core/inspector/InspectorResourceAgent.h
@@ -35,9 +35,6 @@
 #include "bindings/v8/ScriptString.h"
 #include "core/inspector/InspectorBaseAgent.h"
 #include "wtf/PassOwnPtr.h"
-#include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
-#include "wtf/text/TextPosition.h"
 #include "wtf/text/WTFString.h"
 
 
@@ -54,13 +51,13 @@
 class FormData;
 class Frame;
 class HTTPHeaderMap;
-class InspectorArray;
 class InspectorClient;
 class InspectorFrontend;
-class InspectorObject;
+class InspectorOverlay;
 class InspectorPageAgent;
 class InspectorState;
 class InstrumentingAgents;
+class JSONObject;
 class KURL;
 class NetworkResourcesData;
 class Page;
@@ -81,9 +78,9 @@
 
 class InspectorResourceAgent : public InspectorBaseAgent<InspectorResourceAgent>, public InspectorBackendDispatcher::NetworkCommandHandler {
 public:
-    static PassOwnPtr<InspectorResourceAgent> create(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorClient* client, InspectorCompositeState* state)
+    static PassOwnPtr<InspectorResourceAgent> create(InstrumentingAgents* instrumentingAgents, InspectorPageAgent* pageAgent, InspectorClient* client, InspectorCompositeState* state, InspectorOverlay* overlay)
     {
-        return adoptPtr(new InspectorResourceAgent(instrumentingAgents, pageAgent, client, state));
+        return adoptPtr(new InspectorResourceAgent(instrumentingAgents, pageAgent, client, state, overlay));
     }
 
     virtual void setFrontend(InspectorFrontend*);
@@ -138,7 +135,7 @@
     virtual void enable(ErrorString*);
     virtual void disable(ErrorString*);
     virtual void setUserAgentOverride(ErrorString*, const String& userAgent);
-    virtual void setExtraHTTPHeaders(ErrorString*, const RefPtr<InspectorObject>&);
+    virtual void setExtraHTTPHeaders(ErrorString*, const RefPtr<JSONObject>&);
     virtual void getResponseBody(ErrorString*, const String& requestId, String* content, bool* base64Encoded);
 
     virtual void replayXHR(ErrorString*, const String& requestId);
@@ -149,17 +146,18 @@
     virtual void clearBrowserCookies(ErrorString*);
     virtual void setCacheDisabled(ErrorString*, bool cacheDisabled);
 
-    virtual void loadResourceForFrontend(ErrorString*, const String& frameId, const String& url, PassRefPtr<LoadResourceForFrontendCallback>);
+    virtual void loadResourceForFrontend(ErrorString*, const String& frameId, const String& url, const RefPtr<JSONObject>* requestHeaders, PassRefPtr<LoadResourceForFrontendCallback>);
 
     virtual void reportMemoryUsage(MemoryObjectInfo*) const OVERRIDE;
 
 private:
-    InspectorResourceAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorClient*, InspectorCompositeState*);
+    InspectorResourceAgent(InstrumentingAgents*, InspectorPageAgent*, InspectorClient*, InspectorCompositeState*, InspectorOverlay*);
 
     void enable();
 
     InspectorPageAgent* m_pageAgent;
     InspectorClient* m_client;
+    InspectorOverlay* m_overlay;
     InspectorFrontend::Network* m_frontend;
     String m_userAgentOverride;
     OwnPtr<NetworkResourcesData> m_resourcesData;
diff --git a/Source/core/inspector/InspectorRuntimeAgent.cpp b/Source/core/inspector/InspectorRuntimeAgent.cpp
index c042fe2..2568d13 100644
--- a/Source/core/inspector/InspectorRuntimeAgent.cpp
+++ b/Source/core/inspector/InspectorRuntimeAgent.cpp
@@ -33,8 +33,7 @@
 
 #include "core/inspector/InjectedScript.h"
 #include "core/inspector/InjectedScriptManager.h"
-#include "core/inspector/InspectorValues.h"
-#include <wtf/PassRefPtr.h>
+#include "core/platform/JSONValues.h"
 
 
 #include "bindings/v8/ScriptDebugServer.h"
@@ -86,7 +85,7 @@
     }
 }
 
-void InspectorRuntimeAgent::callFunctionOn(ErrorString* errorString, const String& objectId, const String& expression, const RefPtr<InspectorArray>* const optionalArguments, const bool* const doNotPauseOnExceptionsAndMuteConsole, const bool* const returnByValue, const bool* generatePreview, RefPtr<TypeBuilder::Runtime::RemoteObject>& result, TypeBuilder::OptOutput<bool>* wasThrown)
+void InspectorRuntimeAgent::callFunctionOn(ErrorString* errorString, const String& objectId, const String& expression, const RefPtr<JSONArray>* const optionalArguments, const bool* const doNotPauseOnExceptionsAndMuteConsole, const bool* const returnByValue, const bool* generatePreview, RefPtr<TypeBuilder::Runtime::RemoteObject>& result, TypeBuilder::OptOutput<bool>* wasThrown)
 {
     InjectedScript injectedScript = m_injectedScriptManager->injectedScriptForObjectId(objectId);
     if (injectedScript.hasNoValue()) {
diff --git a/Source/core/inspector/InspectorRuntimeAgent.h b/Source/core/inspector/InspectorRuntimeAgent.h
index 83ec406..8ad65c1 100644
--- a/Source/core/inspector/InspectorRuntimeAgent.h
+++ b/Source/core/inspector/InspectorRuntimeAgent.h
@@ -32,22 +32,19 @@
 #define InspectorRuntimeAgent_h
 
 
-#include "bindings/v8/ScriptState.h"
 #include "core/inspector/InspectorBaseAgent.h"
-#include <wtf/Forward.h>
-#include <wtf/Noncopyable.h>
+#include "wtf/Forward.h"
+#include "wtf/Noncopyable.h"
 
 namespace WebCore {
 
 class InjectedScript;
 class InjectedScriptManager;
-class InspectorArray;
 class InspectorFrontend;
-class InspectorObject;
-class InspectorValue;
 class InstrumentingAgents;
+class JSONArray;
 class ScriptDebugServer;
-class WorkerContext;
+class WorkerGlobalScope;
 
 typedef String ErrorString;
 
@@ -73,7 +70,7 @@
     virtual void callFunctionOn(ErrorString*,
                         const String& objectId,
                         const String& expression,
-                        const RefPtr<InspectorArray>* optionalArguments,
+                        const RefPtr<JSONArray>* optionalArguments,
                         const bool* doNotPauseOnExceptionsAndMuteConsole,
                         const bool* returnByValue,
                         const bool* generatePreview,
diff --git a/Source/core/inspector/InspectorState.cpp b/Source/core/inspector/InspectorState.cpp
index fc3124f..2ed6d20 100644
--- a/Source/core/inspector/InspectorState.cpp
+++ b/Source/core/inspector/InspectorState.cpp
@@ -30,11 +30,12 @@
 #include "core/inspector/InspectorState.h"
 
 #include "core/inspector/InspectorStateClient.h"
-#include <wtf/PassOwnPtr.h>
+#include "core/inspector/JSONParser.h"
+#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
-InspectorState::InspectorState(InspectorStateUpdateListener* listener, PassRefPtr<InspectorObject> properties)
+InspectorState::InspectorState(InspectorStateUpdateListener* listener, PassRefPtr<JSONObject> properties)
     : m_listener(listener)
     , m_properties(properties)
 {
@@ -46,12 +47,12 @@
         m_listener->inspectorStateUpdated();
 }
 
-void InspectorState::setFromCookie(PassRefPtr<InspectorObject> properties)
+void InspectorState::setFromCookie(PassRefPtr<JSONObject> properties)
 {
     m_properties = properties;
 }
 
-void InspectorState::setValue(const String& propertyName, PassRefPtr<InspectorValue> value)
+void InspectorState::setValue(const String& propertyName, PassRefPtr<JSONValue> value)
 {
     m_properties->setValue(propertyName, value);
     updateCookie();
@@ -65,7 +66,7 @@
 
 bool InspectorState::getBoolean(const String& propertyName)
 {
-    InspectorObject::iterator it = m_properties->find(propertyName);
+    JSONObject::iterator it = m_properties->find(propertyName);
     bool value = false;
     if (it != m_properties->end())
         it->value->asBoolean(&value);
@@ -74,7 +75,7 @@
 
 String InspectorState::getString(const String& propertyName)
 {
-    InspectorObject::iterator it = m_properties->find(propertyName);
+    JSONObject::iterator it = m_properties->find(propertyName);
     String value;
     if (it != m_properties->end())
         it->value->asString(&value);
@@ -83,7 +84,7 @@
 
 long InspectorState::getLong(const String& propertyName)
 {
-    InspectorObject::iterator it = m_properties->find(propertyName);
+    JSONObject::iterator it = m_properties->find(propertyName);
     long value = 0;
     if (it != m_properties->end())
         it->value->asNumber(&value);
@@ -92,18 +93,18 @@
 
 double InspectorState::getDouble(const String& propertyName)
 {
-    InspectorObject::iterator it = m_properties->find(propertyName);
+    JSONObject::iterator it = m_properties->find(propertyName);
     double value = 0;
     if (it != m_properties->end())
         it->value->asNumber(&value);
     return value;
 }
 
-PassRefPtr<InspectorObject> InspectorState::getObject(const String& propertyName)
+PassRefPtr<JSONObject> InspectorState::getObject(const String& propertyName)
 {
-    InspectorObject::iterator it = m_properties->find(propertyName);
+    JSONObject::iterator it = m_properties->find(propertyName);
     if (it == m_properties->end()) {
-        m_properties->setObject(propertyName, InspectorObject::create());
+        m_properties->setObject(propertyName, JSONObject::create());
         it = m_properties->find(propertyName);
     }
     return it->value->asObject();
@@ -113,7 +114,7 @@
 {
     ASSERT(m_stateObject->find(agentName) == m_stateObject->end());
     ASSERT(m_inspectorStateMap.find(agentName) == m_inspectorStateMap.end());
-    RefPtr<InspectorObject> stateProperties = InspectorObject::create();
+    RefPtr<JSONObject> stateProperties = JSONObject::create();
     m_stateObject->setObject(agentName, stateProperties);
     OwnPtr<InspectorState> statePtr = adoptPtr(new InspectorState(this, stateProperties));
     InspectorState* state = statePtr.get();
@@ -123,17 +124,17 @@
 
 void InspectorCompositeState::loadFromCookie(const String& inspectorCompositeStateCookie)
 {
-    RefPtr<InspectorValue> cookie = InspectorValue::parseJSON(inspectorCompositeStateCookie);
+    RefPtr<JSONValue> cookie = parseJSON(inspectorCompositeStateCookie);
     if (cookie)
         m_stateObject = cookie->asObject();
     if (!m_stateObject)
-        m_stateObject = InspectorObject::create();
+        m_stateObject = JSONObject::create();
 
     InspectorStateMap::iterator end = m_inspectorStateMap.end();
     for (InspectorStateMap::iterator it = m_inspectorStateMap.begin(); it != end; ++it) {
-        RefPtr<InspectorObject> agentStateObject = m_stateObject->getObject(it->key);
+        RefPtr<JSONObject> agentStateObject = m_stateObject->getObject(it->key);
         if (!agentStateObject) {
-            agentStateObject = InspectorObject::create();
+            agentStateObject = JSONObject::create();
             m_stateObject->setObject(it->key, agentStateObject);
         }
         it->value->setFromCookie(agentStateObject);
diff --git a/Source/core/inspector/InspectorState.h b/Source/core/inspector/InspectorState.h
index 7952f2b..7fe1f50 100644
--- a/Source/core/inspector/InspectorState.h
+++ b/Source/core/inspector/InspectorState.h
@@ -32,10 +32,9 @@
 #define InspectorState_h
 
 
-#include "core/inspector/InspectorValues.h"
-#include <wtf/HashMap.h>
-#include <wtf/RefCounted.h>
-#include <wtf/text/WTFString.h>
+#include "core/platform/JSONValues.h"
+#include "wtf/HashMap.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -50,7 +49,7 @@
 class InspectorState {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    InspectorState(InspectorStateUpdateListener*, PassRefPtr<InspectorObject>);
+    InspectorState(InspectorStateUpdateListener*, PassRefPtr<JSONObject>);
     virtual ~InspectorState() {}
 
     void loadFromCookie(const String& inspectorStateCookie);
@@ -62,33 +61,33 @@
     String getString(const String& propertyName);
     long getLong(const String& propertyName);
     double getDouble(const String& propertyName);
-    PassRefPtr<InspectorObject> getObject(const String& propertyName);
+    PassRefPtr<JSONObject> getObject(const String& propertyName);
 
-    void setBoolean(const String& propertyName, bool value) { setValue(propertyName, InspectorBasicValue::create(value)); }
-    void setString(const String& propertyName, const String& value) { setValue(propertyName, InspectorString::create(value)); }
-    void setLong(const String& propertyName, long value) { setValue(propertyName, InspectorBasicValue::create((double)value)); }
-    void setDouble(const String& propertyName, double value) { setValue(propertyName, InspectorBasicValue::create(value)); }
-    void setObject(const String& propertyName, PassRefPtr<InspectorObject> value) { setValue(propertyName, value); }
+    void setBoolean(const String& propertyName, bool value) { setValue(propertyName, JSONBasicValue::create(value)); }
+    void setString(const String& propertyName, const String& value) { setValue(propertyName, JSONString::create(value)); }
+    void setLong(const String& propertyName, long value) { setValue(propertyName, JSONBasicValue::create((double)value)); }
+    void setDouble(const String& propertyName, double value) { setValue(propertyName, JSONBasicValue::create(value)); }
+    void setObject(const String& propertyName, PassRefPtr<JSONObject> value) { setValue(propertyName, value); }
 
     void remove(const String&);
 private:
     void updateCookie();
-    void setValue(const String& propertyName, PassRefPtr<InspectorValue>);
+    void setValue(const String& propertyName, PassRefPtr<JSONValue>);
 
     // Gets called from InspectorCompositeState::loadFromCookie().
-    void setFromCookie(PassRefPtr<InspectorObject>);
+    void setFromCookie(PassRefPtr<JSONObject>);
 
     friend class InspectorCompositeState;
 
     InspectorStateUpdateListener* m_listener;
-    RefPtr<InspectorObject> m_properties;
+    RefPtr<JSONObject> m_properties;
 };
 
 class InspectorCompositeState : public InspectorStateUpdateListener {
 public:
     InspectorCompositeState(InspectorStateClient* inspectorClient)
         : m_client(inspectorClient)
-        , m_stateObject(InspectorObject::create())
+        , m_stateObject(JSONObject::create())
         , m_isMuted(false)
     {
     }
@@ -107,7 +106,7 @@
     virtual void inspectorStateUpdated();
 
     InspectorStateClient* m_client;
-    RefPtr<InspectorObject> m_stateObject;
+    RefPtr<JSONObject> m_stateObject;
     bool m_isMuted;
     InspectorStateMap m_inspectorStateMap;
 };
diff --git a/Source/core/inspector/InspectorStyleSheet.cpp b/Source/core/inspector/InspectorStyleSheet.cpp
index 0d52545..e001e72 100644
--- a/Source/core/inspector/InspectorStyleSheet.cpp
+++ b/Source/core/inspector/InspectorStyleSheet.cpp
@@ -29,7 +29,6 @@
 #include "HTMLNames.h"
 #include "SVGNames.h"
 #include "core/css/CSSHostRule.h"
-#include "core/css/CSSImportRule.h"
 #include "core/css/CSSKeyframesRule.h"
 #include "core/css/CSSMediaRule.h"
 #include "core/css/CSSParser.h"
@@ -49,15 +48,15 @@
 #include "core/inspector/ContentSearchUtils.h"
 #include "core/inspector/InspectorCSSAgent.h"
 #include "core/inspector/InspectorPageAgent.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/page/Page.h"
 #include "core/page/PageConsole.h"
+#include "core/platform/JSONValues.h"
 #include "core/platform/text/RegularExpression.h"
-
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/text/StringBuilder.h>
-#include <wtf/Vector.h>
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/text/StringBuilder.h"
+#include "wtf/text/TextPosition.h"
 
 using WebCore::TypeBuilder::Array;
 using WebCore::RuleSourceDataList;
@@ -443,12 +442,12 @@
     MediaListSourceImportRule
 };
 
-static PassRefPtr<TypeBuilder::CSS::SourceRange> buildSourceRangeObject(const SourceRange& range, Vector<size_t>* lineEndings)
+static PassRefPtr<TypeBuilder::CSS::SourceRange> buildSourceRangeObject(const SourceRange& range, Vector<unsigned>* lineEndings)
 {
     if (!lineEndings)
         return 0;
-    TextPosition start = ContentSearchUtils::textPositionFromOffset(range.start, *lineEndings);
-    TextPosition end = ContentSearchUtils::textPositionFromOffset(range.end, *lineEndings);
+    TextPosition start = TextPosition::fromOffsetAndLineEndings(range.start, *lineEndings);
+    TextPosition end = TextPosition::fromOffsetAndLineEndings(range.end, *lineEndings);
 
     RefPtr<TypeBuilder::CSS::SourceRange> result = TypeBuilder::CSS::SourceRange::create()
         .setStartLine(start.m_line.zeroBasedInt())
@@ -710,7 +709,7 @@
     HashSet<String> foundShorthands;
     String previousPriority;
     String previousStatus;
-    OwnPtr<Vector<size_t> > lineEndings(m_parentStyleSheet ? m_parentStyleSheet->lineEndings() : PassOwnPtr<Vector<size_t> >());
+    OwnPtr<Vector<unsigned> > lineEndings(m_parentStyleSheet ? m_parentStyleSheet->lineEndings() : PassOwnPtr<Vector<unsigned> >());
     RefPtr<CSSRuleSourceData> sourceData = extractSourceData();
     unsigned ruleBodyRangeStart = sourceData ? sourceData->ruleBodyRange.start : 0;
 
@@ -903,14 +902,13 @@
     int propertyIndex = 0;
     bool isFullPrefixScanned = false;
     bool lineFeedTerminated = false;
-    const UChar* characters = text.characters();
     while (propertyIndex < propertyCount) {
         const WebCore::CSSPropertySourceData& currentProperty = sourcePropertyData->at(propertyIndex++);
 
         bool processNextProperty = false;
         int scanEnd = currentProperty.range.start;
         for (int i = scanStart; i < scanEnd; ++i) {
-            UChar ch = characters[i];
+            UChar ch = text[i];
             bool isLineFeed = isHTMLLineBreak(ch);
             if (isLineFeed) {
                 if (!lineFeedTerminated)
@@ -1434,8 +1432,7 @@
         bool deprecated;
         String commentValue = ContentSearchUtils::findSourceURL(styleSheetText, ContentSearchUtils::CSSMagicComment, &deprecated);
         if (!commentValue.isEmpty()) {
-            if (deprecated)
-                m_pageAgent->page()->console()->addMessage(NetworkMessageSource, WarningMessageLevel, "\"/*@ sourceURL=\" source URL declaration is deprecated, \"/*# sourceURL=\" declaration should be used instead.", finalURL(), 0);
+            // FIXME: add deprecated console message here.
             m_sourceURL = commentValue;
             return commentValue;
         }
@@ -1488,8 +1485,7 @@
         bool deprecated;
         String commentValue = ContentSearchUtils::findSourceMapURL(styleSheetText, ContentSearchUtils::CSSMagicComment, &deprecated);
         if (!commentValue.isEmpty()) {
-            if (deprecated)
-                m_pageAgent->page()->console()->addMessage(NetworkMessageSource, WarningMessageLevel, "\"/*@ sourceMappingURL=\" source mapping URL declaration is deprecated, \"/*# sourceMappingURL=\" declaration should be used instead.", finalURL(), 0);
+            // FIXME: add deprecated console message here.
             return commentValue;
         }
     }
@@ -1514,11 +1510,11 @@
     return m_parsedStyleSheet->ruleSourceDataAt(ruleIndexByStyle(style));
 }
 
-PassOwnPtr<Vector<size_t> > InspectorStyleSheet::lineEndings() const
+PassOwnPtr<Vector<unsigned> > InspectorStyleSheet::lineEndings() const
 {
     if (!m_parsedStyleSheet->hasText())
-        return PassOwnPtr<Vector<size_t> >();
-    return ContentSearchUtils::lineEndings(m_parsedStyleSheet->text());
+        return PassOwnPtr<Vector<unsigned> >();
+    return WTF::lineEndings(m_parsedStyleSheet->text());
 }
 
 unsigned InspectorStyleSheet::ruleIndexByStyle(CSSStyleDeclaration* pageStyle) const
@@ -1748,9 +1744,9 @@
     return !ec;
 }
 
-PassOwnPtr<Vector<size_t> > InspectorStyleSheetForInlineStyle::lineEndings() const
+PassOwnPtr<Vector<unsigned> > InspectorStyleSheetForInlineStyle::lineEndings() const
 {
-    return ContentSearchUtils::lineEndings(elementStyleText());
+    return WTF::lineEndings(elementStyleText());
 }
 
 Document* InspectorStyleSheetForInlineStyle::ownerDocument() const
diff --git a/Source/core/inspector/InspectorStyleSheet.h b/Source/core/inspector/InspectorStyleSheet.h
index 61a8d3c..9082de5 100644
--- a/Source/core/inspector/InspectorStyleSheet.h
+++ b/Source/core/inspector/InspectorStyleSheet.h
@@ -30,14 +30,12 @@
 #include "core/css/CSSStyleDeclaration.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/inspector/InspectorStyleTextEditor.h"
-#include "core/inspector/InspectorValues.h"
-
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Vector.h>
+#include "core/platform/JSONValues.h"
+#include "wtf/HashMap.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
 
 class ParsedStyleSheet;
 
@@ -63,12 +61,12 @@
     {
     }
 
-    explicit InspectorCSSId(RefPtr<InspectorObject> value)
+    explicit InspectorCSSId(PassRefPtr<JSONObject> value)
     {
         if (!value->getString("styleSheetId", &m_styleSheetId))
             return;
         
-        RefPtr<InspectorValue> ordinalValue = value->get("ordinal");
+        RefPtr<JSONValue> ordinalValue = value->get("ordinal");
         if (!ordinalValue || !ordinalValue->asNumber(&m_ordinal))
             m_styleSheetId = "";
     }
@@ -223,7 +221,7 @@
 
     // Also accessed by friend class InspectorStyle.
     virtual bool setStyleText(CSSStyleDeclaration*, const String&);
-    virtual PassOwnPtr<Vector<size_t> > lineEndings() const;
+    virtual PassOwnPtr<Vector<unsigned> > lineEndings() const;
 
 private:
     friend class InspectorStyle;
@@ -277,7 +275,7 @@
 
     // Also accessed by friend class InspectorStyle.
     virtual bool setStyleText(CSSStyleDeclaration*, const String&);
-    virtual PassOwnPtr<Vector<size_t> > lineEndings() const;
+    virtual PassOwnPtr<Vector<unsigned> > lineEndings() const;
 
 private:
     CSSStyleDeclaration* inlineStyle() const;
diff --git a/Source/core/inspector/InspectorStyleTextEditor.cpp b/Source/core/inspector/InspectorStyleTextEditor.cpp
index f2701b2..f7044ff 100644
--- a/Source/core/inspector/InspectorStyleTextEditor.cpp
+++ b/Source/core/inspector/InspectorStyleTextEditor.cpp
@@ -68,13 +68,11 @@
     if (insertLast && !insertFirstInSource) {
         propertyStart = styleBodyLength;
         if (propertyStart && textToSet.length()) {
-            const UChar* characters = m_styleText.characters();
-
             long curPos = propertyStart - 1; // The last position of style declaration, since propertyStart points past one.
-            while (curPos && isHTMLSpace(characters[curPos]))
+            while (curPos && isHTMLSpace(m_styleText[curPos]))
                 --curPos;
             if (curPos) {
-                bool terminated = characters[curPos] == ';' || (characters[curPos] == '/' && characters[curPos - 1] == '*');
+                bool terminated = m_styleText[curPos] == ';' || (m_styleText[curPos] == '/' && m_styleText[curPos - 1] == '*');
                 if (!terminated) {
                     // Prepend a ";" to the property text if appending to a style declaration where
                     // the last property has no trailing ";".
@@ -140,7 +138,6 @@
     const SourceRange& range = property.sourceData.range;
     long replaceRangeStart = range.start;
     long replaceRangeEnd = range.end;
-    const UChar* characters = m_styleText.characters();
     long newTextLength = newText.length();
     String finalNewText = newText;
 
@@ -151,14 +148,14 @@
         if (replaceRangeStart >= fullPrefixLength && m_styleText.substring(replaceRangeStart - fullPrefixLength, fullPrefixLength) == fullPrefix)
             replaceRangeStart -= fullPrefixLength;
     } else if (newTextLength) {
-        if (isHTMLLineBreak(newText.characters()[newTextLength - 1])) {
+        if (isHTMLLineBreak(newText[newTextLength - 1])) {
             // Coalesce newlines of the original and new property values (to avoid a lot of blank lines while incrementally applying property values).
             bool foundNewline = false;
             bool isLastNewline = false;
             int i;
             int textLength = m_styleText.length();
-            for (i = replaceRangeEnd; i < textLength && isSpaceOrNewline(characters[i]); ++i) {
-                isLastNewline = isHTMLLineBreak(characters[i]);
+            for (i = replaceRangeEnd; i < textLength && isSpaceOrNewline(m_styleText[i]); ++i) {
+                isLastNewline = isHTMLLineBreak(m_styleText[i]);
                 if (isLastNewline)
                     foundNewline = true;
                 else if (foundNewline && !isLastNewline) {
diff --git a/Source/core/inspector/InspectorStyleTextEditor.h b/Source/core/inspector/InspectorStyleTextEditor.h
index 5fdab78..f5ac0ec 100644
--- a/Source/core/inspector/InspectorStyleTextEditor.h
+++ b/Source/core/inspector/InspectorStyleTextEditor.h
@@ -25,10 +25,8 @@
 #ifndef InspectorStyleTextEditor_h
 #define InspectorStyleTextEditor_h
 
-#include "core/css/CSSPropertySourceData.h"
-
-#include <wtf/text/WTFString.h>
-#include <wtf/Vector.h>
+#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/inspector/InspectorTimelineAgent.cpp b/Source/core/inspector/InspectorTimelineAgent.cpp
index 09db80d..0ea8f7f 100644
--- a/Source/core/inspector/InspectorTimelineAgent.cpp
+++ b/Source/core/inspector/InspectorTimelineAgent.cpp
@@ -55,7 +55,7 @@
 #include "core/rendering/RenderView.h"
 #include "core/xml/XMLHttpRequest.h"
 
-#include <wtf/CurrentTime.h>
+#include "wtf/CurrentTime.h"
 
 namespace WebCore {
 
@@ -164,7 +164,7 @@
     GCEvents events = m_gcEvents;
     m_gcEvents.clear();
     for (GCEvents::iterator i = events.begin(); i != events.end(); ++i) {
-        RefPtr<InspectorObject> record = TimelineRecordFactory::createGenericRecord(m_timeConverter.fromMonotonicallyIncreasingTime(i->startTime), m_maxCallStackDepth, TimelineRecordType::GCEvent);
+        RefPtr<JSONObject> record = TimelineRecordFactory::createGenericRecord(m_timeConverter.fromMonotonicallyIncreasingTime(i->startTime), m_maxCallStackDepth, TimelineRecordType::GCEvent);
         record->setObject("data", TimelineRecordFactory::createGCEventData(i->collectedBytes));
         record->setNumber("endTime", m_timeConverter.fromMonotonicallyIncreasingTime(i->endTime));
         addRecordToTimeline(record.release());
@@ -294,7 +294,7 @@
 
 void InspectorTimelineAgent::didInvalidateLayout(Frame* frame)
 {
-    appendRecord(InspectorObject::create(), TimelineRecordType::InvalidateLayout, true, frame);
+    appendRecord(JSONObject::create(), TimelineRecordType::InvalidateLayout, true, frame);
 }
 
 bool InspectorTimelineAgent::willLayout(Frame* frame)
@@ -333,12 +333,12 @@
 
 void InspectorTimelineAgent::didScheduleStyleRecalculation(Document* document)
 {
-    appendRecord(InspectorObject::create(), TimelineRecordType::ScheduleStyleRecalculation, true, document->frame());
+    appendRecord(JSONObject::create(), TimelineRecordType::ScheduleStyleRecalculation, true, document->frame());
 }
 
 bool InspectorTimelineAgent::willRecalculateStyle(Document* document)
 {
-    pushCurrentRecord(InspectorObject::create(), TimelineRecordType::RecalculateStyles, true, document->frame());
+    pushCurrentRecord(JSONObject::create(), TimelineRecordType::RecalculateStyles, true, document->frame());
     ASSERT(!m_styleRecalcElementCounter);
     return true;
 }
@@ -366,7 +366,7 @@
         InstrumentationEventArguments::PageId, reinterpret_cast<unsigned long long>(frame->page()),
         InstrumentationEventArguments::NodeId, idForNode(renderer->generatingNode()));
 
-    pushCurrentRecord(InspectorObject::create(), TimelineRecordType::Paint, true, frame, true);
+    pushCurrentRecord(JSONObject::create(), TimelineRecordType::Paint, true, frame, true);
 }
 
 void InspectorTimelineAgent::didPaint(RenderObject* renderer, GraphicsContext*, const LayoutRect& clipRect)
@@ -381,7 +381,7 @@
 
 void InspectorTimelineAgent::willScrollLayer(Frame* frame)
 {
-    pushCurrentRecord(InspectorObject::create(), TimelineRecordType::ScrollLayer, false, frame);
+    pushCurrentRecord(JSONObject::create(), TimelineRecordType::ScrollLayer, false, frame);
 }
 
 void InspectorTimelineAgent::didScrollLayer()
@@ -411,7 +411,7 @@
 
 void InspectorTimelineAgent::willComposite()
 {
-    pushCurrentRecord(InspectorObject::create(), TimelineRecordType::CompositeLayers, false, 0);
+    pushCurrentRecord(JSONObject::create(), TimelineRecordType::CompositeLayers, false, 0);
 }
 
 void InspectorTimelineAgent::didComposite()
@@ -604,7 +604,7 @@
 
 void InspectorTimelineAgent::willProcessTask()
 {
-    pushCurrentRecord(InspectorObject::create(), TimelineRecordType::Program, false, 0);
+    pushCurrentRecord(JSONObject::create(), TimelineRecordType::Program, false, 0);
 }
 
 void InspectorTimelineAgent::didProcessTask()
@@ -632,13 +632,13 @@
     appendRecord(TimelineRecordFactory::createGenericWebSocketData(identifier), TimelineRecordType::WebSocketDestroy, true, document->frame());
 }
 
-void InspectorTimelineAgent::addRecordToTimeline(PassRefPtr<InspectorObject> record)
+void InspectorTimelineAgent::addRecordToTimeline(PassRefPtr<JSONObject> record)
 {
     commitFrameRecord();
     innerAddRecordToTimeline(record);
 }
 
-void InspectorTimelineAgent::innerAddRecordToTimeline(PassRefPtr<InspectorObject> prpRecord)
+void InspectorTimelineAgent::innerAddRecordToTimeline(PassRefPtr<JSONObject> prpRecord)
 {
     RefPtr<TypeBuilder::Timeline::TimelineEvent> record = TypeBuilder::Timeline::TimelineEvent::runtimeCast(prpRecord);
 
@@ -687,7 +687,7 @@
         return;
     HashMap<String, size_t> map;
     m_memoryAgent->getProcessMemoryDistributionMap(&map);
-    RefPtr<InspectorObject> stats = InspectorObject::create();
+    RefPtr<JSONObject> stats = JSONObject::create();
     for (HashMap<String, size_t>::iterator it = map.begin(); it != map.end(); ++it)
         stats->setNumber(it->key, it->value);
     size_t privateBytes = 0;
@@ -697,7 +697,7 @@
     record->setNativeHeapStatistics(stats.release());
 }
 
-void InspectorTimelineAgent::setFrameIdentifier(InspectorObject* record, Frame* frame)
+void InspectorTimelineAgent::setFrameIdentifier(JSONObject* record, Frame* frame)
 {
     if (!frame || !m_pageAgent)
         return;
@@ -747,29 +747,29 @@
 {
 }
 
-void InspectorTimelineAgent::appendRecord(PassRefPtr<InspectorObject> data, const String& type, bool captureCallStack, Frame* frame)
+void InspectorTimelineAgent::appendRecord(PassRefPtr<JSONObject> data, const String& type, bool captureCallStack, Frame* frame)
 {
     pushGCEventRecords();
-    RefPtr<InspectorObject> record = TimelineRecordFactory::createGenericRecord(timestamp(), captureCallStack ? m_maxCallStackDepth : 0, type);
+    RefPtr<JSONObject> record = TimelineRecordFactory::createGenericRecord(timestamp(), captureCallStack ? m_maxCallStackDepth : 0, type);
     record->setObject("data", data);
     setFrameIdentifier(record.get(), frame);
     addRecordToTimeline(record.release());
 }
 
-void InspectorTimelineAgent::sendEvent(PassRefPtr<InspectorObject> event)
+void InspectorTimelineAgent::sendEvent(PassRefPtr<JSONObject> event)
 {
     // FIXME: runtimeCast is a hack. We do it because we can't build TimelineEvent directly now.
     RefPtr<TypeBuilder::Timeline::TimelineEvent> recordChecked = TypeBuilder::Timeline::TimelineEvent::runtimeCast(event);
     m_frontend->eventRecorded(recordChecked.release());
 }
 
-void InspectorTimelineAgent::pushCurrentRecord(PassRefPtr<InspectorObject> data, const String& type, bool captureCallStack, Frame* frame, bool hasLowLevelDetails)
+void InspectorTimelineAgent::pushCurrentRecord(PassRefPtr<JSONObject> data, const String& type, bool captureCallStack, Frame* frame, bool hasLowLevelDetails)
 {
     pushGCEventRecords();
     commitFrameRecord();
-    RefPtr<InspectorObject> record = TimelineRecordFactory::createGenericRecord(timestamp(), captureCallStack ? m_maxCallStackDepth : 0, type);
+    RefPtr<JSONObject> record = TimelineRecordFactory::createGenericRecord(timestamp(), captureCallStack ? m_maxCallStackDepth : 0, type);
     setFrameIdentifier(record.get(), frame);
-    m_recordStack.append(TimelineRecordEntry(record.release(), data, InspectorArray::create(), type, getUsedHeapSize()));
+    m_recordStack.append(TimelineRecordEntry(record.release(), data, JSONArray::create(), type, getUsedHeapSize()));
     if (hasLowLevelDetails && !m_platformInstrumentationClientInstalledAtStackDepth && !PlatformInstrumentation::hasClient()) {
         m_platformInstrumentationClientInstalledAtStackDepth = m_recordStack.size();
         PlatformInstrumentation::setClient(this);
@@ -781,7 +781,7 @@
     if (!m_pendingFrameRecord)
         return;
     
-    m_pendingFrameRecord->setObject("data", InspectorObject::create());
+    m_pendingFrameRecord->setObject("data", JSONObject::create());
     innerAddRecordToTimeline(m_pendingFrameRecord.release());
 }
 
diff --git a/Source/core/inspector/InspectorTimelineAgent.h b/Source/core/inspector/InspectorTimelineAgent.h
index 2a35c56..b589156 100644
--- a/Source/core/inspector/InspectorTimelineAgent.h
+++ b/Source/core/inspector/InspectorTimelineAgent.h
@@ -36,13 +36,13 @@
 #include "bindings/v8/ScriptGCEvent.h"
 #include "core/dom/EventContext.h"
 #include "core/inspector/InspectorBaseAgent.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/inspector/ScriptGCEventListener.h"
+#include "core/platform/JSONValues.h"
 #include "core/platform/PlatformInstrumentation.h"
 #include "core/platform/graphics/LayoutRect.h"
-#include <wtf/PassOwnPtr.h>
-#include <wtf/Vector.h>
-#include <wtf/WeakPtr.h>
+#include "wtf/PassOwnPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/WeakPtr.h"
 
 namespace WebCore {
 struct CachedResourceInitiatorInfo;
@@ -214,13 +214,13 @@
     friend class TimelineTraceEventProcessor;
 
     struct TimelineRecordEntry {
-        TimelineRecordEntry(PassRefPtr<InspectorObject> record, PassRefPtr<InspectorObject> data, PassRefPtr<InspectorArray> children, const String& type, size_t usedHeapSizeAtStart)
+        TimelineRecordEntry(PassRefPtr<JSONObject> record, PassRefPtr<JSONObject> data, PassRefPtr<JSONArray> children, const String& type, size_t usedHeapSizeAtStart)
             : record(record), data(data), children(children), type(type), usedHeapSizeAtStart(usedHeapSizeAtStart)
         {
         }
-        RefPtr<InspectorObject> record;
-        RefPtr<InspectorObject> data;
-        RefPtr<InspectorArray> children;
+        RefPtr<JSONObject> record;
+        RefPtr<JSONObject> data;
+        RefPtr<JSONArray> children;
         String type;
         size_t usedHeapSizeAtStart;
     };
@@ -229,22 +229,22 @@
 
     void didFinishLoadingResource(unsigned long, bool didFail, double finishTime, Frame*);
 
-    void sendEvent(PassRefPtr<InspectorObject>);
-    void appendRecord(PassRefPtr<InspectorObject> data, const String& type, bool captureCallStack, Frame*);
-    void pushCurrentRecord(PassRefPtr<InspectorObject>, const String& type, bool captureCallStack, Frame*, bool hasLowLevelDetails = false);
+    void sendEvent(PassRefPtr<JSONObject>);
+    void appendRecord(PassRefPtr<JSONObject> data, const String& type, bool captureCallStack, Frame*);
+    void pushCurrentRecord(PassRefPtr<JSONObject>, const String& type, bool captureCallStack, Frame*, bool hasLowLevelDetails = false);
 
     void setDOMCounters(TypeBuilder::Timeline::TimelineEvent* record);
     void setNativeHeapStatistics(TypeBuilder::Timeline::TimelineEvent* record);
-    void setFrameIdentifier(InspectorObject* record, Frame*);
+    void setFrameIdentifier(JSONObject* record, Frame*);
     void pushGCEventRecords();
 
     void didCompleteCurrentRecord(const String& type);
 
-    void setHeapSizeStatistics(InspectorObject* record);
+    void setHeapSizeStatistics(JSONObject* record);
     void commitFrameRecord();
 
-    void addRecordToTimeline(PassRefPtr<InspectorObject>);
-    void innerAddRecordToTimeline(PassRefPtr<InspectorObject>);
+    void addRecordToTimeline(PassRefPtr<JSONObject>);
+    void innerAddRecordToTimeline(PassRefPtr<JSONObject>);
     void clearRecordStack();
 
     void localToPageQuad(const RenderObject& renderer, const LayoutRect&, FloatQuad*);
@@ -279,7 +279,7 @@
     GCEvents m_gcEvents;
     int m_maxCallStackDepth;
     unsigned m_platformInstrumentationClientInstalledAtStackDepth;
-    RefPtr<InspectorObject> m_pendingFrameRecord;
+    RefPtr<JSONObject> m_pendingFrameRecord;
     InspectorType m_inspectorType;
     InspectorClient* m_client;
     WeakPtrFactory<InspectorTimelineAgent> m_weakFactory;
diff --git a/Source/core/inspector/InspectorValues.cpp b/Source/core/inspector/InspectorValues.cpp
deleted file mode 100644
index c132a98..0000000
--- a/Source/core/inspector/InspectorValues.cpp
+++ /dev/null
@@ -1,796 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/inspector/InspectorValues.h"
-
-#include <wtf/DecimalNumber.h>
-#include <wtf/dtoa.h>
-#include <wtf/text/StringBuilder.h>
-
-namespace WebCore {
-
-namespace {
-
-static const int stackLimit = 1000;
-
-enum Token {
-    OBJECT_BEGIN,
-    OBJECT_END,
-    ARRAY_BEGIN,
-    ARRAY_END,
-    STRING,
-    NUMBER,
-    BOOL_TRUE,
-    BOOL_FALSE,
-    NULL_TOKEN,
-    LIST_SEPARATOR,
-    OBJECT_PAIR_SEPARATOR,
-    INVALID_TOKEN,
-};
-
-const char* const nullString = "null";
-const char* const trueString = "true";
-const char* const falseString = "false";
-
-bool parseConstToken(const UChar* start, const UChar* end, const UChar** tokenEnd, const char* token)
-{
-    while (start < end && *token != '\0' && *start++ == *token++) { }
-    if (*token != '\0')
-        return false;
-    *tokenEnd = start;
-    return true;
-}
-
-bool readInt(const UChar* start, const UChar* end, const UChar** tokenEnd, bool canHaveLeadingZeros)
-{
-    if (start == end)
-        return false;
-    bool haveLeadingZero = '0' == *start;
-    int length = 0;
-    while (start < end && '0' <= *start && *start <= '9') {
-        ++start;
-        ++length;
-    }
-    if (!length)
-        return false;
-    if (!canHaveLeadingZeros && length > 1 && haveLeadingZero)
-        return false;
-    *tokenEnd = start;
-    return true;
-}
-
-bool parseNumberToken(const UChar* start, const UChar* end, const UChar** tokenEnd)
-{
-    // We just grab the number here.  We validate the size in DecodeNumber.
-    // According   to RFC4627, a valid number is: [minus] int [frac] [exp]
-    if (start == end)
-        return false;
-    UChar c = *start;
-    if ('-' == c)
-        ++start;
-
-    if (!readInt(start, end, &start, false))
-        return false;
-    if (start == end) {
-        *tokenEnd = start;
-        return true;
-    }
-
-    // Optional fraction part
-    c = *start;
-    if ('.' == c) {
-        ++start;
-        if (!readInt(start, end, &start, true))
-            return false;
-        if (start == end) {
-            *tokenEnd = start;
-            return true;
-        }
-        c = *start;
-    }
-
-    // Optional exponent part
-    if ('e' == c || 'E' == c) {
-        ++start;
-        if (start == end)
-            return false;
-        c = *start;
-        if ('-' == c || '+' == c) {
-            ++start;
-            if (start == end)
-                return false;
-        }
-        if (!readInt(start, end, &start, true))
-            return false;
-    }
-
-    *tokenEnd = start;
-    return true;
-}
-
-bool readHexDigits(const UChar* start, const UChar* end, const UChar** tokenEnd, int digits)
-{
-    if (end - start < digits)
-        return false;
-    for (int i = 0; i < digits; ++i) {
-        UChar c = *start++;
-        if (!(('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')))
-            return false;
-    }
-    *tokenEnd = start;
-    return true;
-}
-
-bool parseStringToken(const UChar* start, const UChar* end, const UChar** tokenEnd)
-{
-    while (start < end) {
-        UChar c = *start++;
-        if ('\\' == c) {
-            c = *start++;
-            // Make sure the escaped char is valid.
-            switch (c) {
-            case 'x':
-                if (!readHexDigits(start, end, &start, 2))
-                    return false;
-                break;
-            case 'u':
-                if (!readHexDigits(start, end, &start, 4))
-                    return false;
-                break;
-            case '\\':
-            case '/':
-            case 'b':
-            case 'f':
-            case 'n':
-            case 'r':
-            case 't':
-            case 'v':
-            case '"':
-                break;
-            default:
-                return false;
-            }
-        } else if ('"' == c) {
-            *tokenEnd = start;
-            return true;
-        }
-    }
-    return false;
-}
-
-Token parseToken(const UChar* start, const UChar* end, const UChar** tokenStart, const UChar** tokenEnd)
-{
-    while (start < end && isSpaceOrNewline(*start))
-        ++start;
-
-    if (start == end)
-        return INVALID_TOKEN;
-
-    *tokenStart = start;
-
-    switch (*start) {
-    case 'n':
-        if (parseConstToken(start, end, tokenEnd, nullString))
-            return NULL_TOKEN;
-        break;
-    case 't':
-        if (parseConstToken(start, end, tokenEnd, trueString))
-            return BOOL_TRUE;
-        break;
-    case 'f':
-        if (parseConstToken(start, end, tokenEnd, falseString))
-            return BOOL_FALSE;
-        break;
-    case '[':
-        *tokenEnd = start + 1;
-        return ARRAY_BEGIN;
-    case ']':
-        *tokenEnd = start + 1;
-        return ARRAY_END;
-    case ',':
-        *tokenEnd = start + 1;
-        return LIST_SEPARATOR;
-    case '{':
-        *tokenEnd = start + 1;
-        return OBJECT_BEGIN;
-    case '}':
-        *tokenEnd = start + 1;
-        return OBJECT_END;
-    case ':':
-        *tokenEnd = start + 1;
-        return OBJECT_PAIR_SEPARATOR;
-    case '0':
-    case '1':
-    case '2':
-    case '3':
-    case '4':
-    case '5':
-    case '6':
-    case '7':
-    case '8':
-    case '9':
-    case '-':
-        if (parseNumberToken(start, end, tokenEnd))
-            return NUMBER;
-        break;
-    case '"':
-        if (parseStringToken(start + 1, end, tokenEnd))
-            return STRING;
-        break;
-    }
-    return INVALID_TOKEN;
-}
-
-inline int hexToInt(UChar c)
-{
-    if ('0' <= c && c <= '9')
-        return c - '0';
-    if ('A' <= c && c <= 'F')
-        return c - 'A' + 10;
-    if ('a' <= c && c <= 'f')
-        return c - 'a' + 10;
-    ASSERT_NOT_REACHED();
-    return 0;
-}
-
-bool decodeString(const UChar* start, const UChar* end, StringBuilder* output)
-{
-    while (start < end) {
-        UChar c = *start++;
-        if ('\\' != c) {
-            output->append(c);
-            continue;
-        }
-        c = *start++;
-        switch (c) {
-        case '"':
-        case '/':
-        case '\\':
-            break;
-        case 'b':
-            c = '\b';
-            break;
-        case 'f':
-            c = '\f';
-            break;
-        case 'n':
-            c = '\n';
-            break;
-        case 'r':
-            c = '\r';
-            break;
-        case 't':
-            c = '\t';
-            break;
-        case 'v':
-            c = '\v';
-            break;
-        case 'x':
-            c = (hexToInt(*start) << 4) +
-                hexToInt(*(start + 1));
-            start += 2;
-            break;
-        case 'u':
-            c = (hexToInt(*start) << 12) +
-                (hexToInt(*(start + 1)) << 8) +
-                (hexToInt(*(start + 2)) << 4) +
-                hexToInt(*(start + 3));
-            start += 4;
-            break;
-        default:
-            return false;
-        }
-        output->append(c);
-    }
-    return true;
-}
-
-bool decodeString(const UChar* start, const UChar* end, String* output)
-{
-    if (start == end) {
-        *output = "";
-        return true;
-    }
-    if (start > end)
-        return false;
-    StringBuilder buffer;
-    buffer.reserveCapacity(end - start);
-    if (!decodeString(start, end, &buffer))
-        return false;
-    *output = buffer.toString();
-    return true;
-}
-
-PassRefPtr<InspectorValue> buildValue(const UChar* start, const UChar* end, const UChar** valueTokenEnd, int depth)
-{
-    if (depth > stackLimit)
-        return 0;
-
-    RefPtr<InspectorValue> result;
-    const UChar* tokenStart;
-    const UChar* tokenEnd;
-    Token token = parseToken(start, end, &tokenStart, &tokenEnd);
-    switch (token) {
-    case INVALID_TOKEN:
-        return 0;
-    case NULL_TOKEN:
-        result = InspectorValue::null();
-        break;
-    case BOOL_TRUE:
-        result = InspectorBasicValue::create(true);
-        break;
-    case BOOL_FALSE:
-        result = InspectorBasicValue::create(false);
-        break;
-    case NUMBER: {
-        bool ok;
-        double value = charactersToDouble(tokenStart, tokenEnd - tokenStart, &ok);
-        if (!ok)
-            return 0;
-        result = InspectorBasicValue::create(value);
-        break;
-    }
-    case STRING: {
-        String value;
-        bool ok = decodeString(tokenStart + 1, tokenEnd - 1, &value);
-        if (!ok)
-            return 0;
-        result = InspectorString::create(value);
-        break;
-    }
-    case ARRAY_BEGIN: {
-        RefPtr<InspectorArray> array = InspectorArray::create();
-        start = tokenEnd;
-        token = parseToken(start, end, &tokenStart, &tokenEnd);
-        while (token != ARRAY_END) {
-            RefPtr<InspectorValue> arrayNode = buildValue(start, end, &tokenEnd, depth + 1);
-            if (!arrayNode)
-                return 0;
-            array->pushValue(arrayNode);
-
-            // After a list value, we expect a comma or the end of the list.
-            start = tokenEnd;
-            token = parseToken(start, end, &tokenStart, &tokenEnd);
-            if (token == LIST_SEPARATOR) {
-                start = tokenEnd;
-                token = parseToken(start, end, &tokenStart, &tokenEnd);
-                if (token == ARRAY_END)
-                    return 0;
-            } else if (token != ARRAY_END) {
-                // Unexpected value after list value.  Bail out.
-                return 0;
-            }
-        }
-        if (token != ARRAY_END)
-            return 0;
-        result = array.release();
-        break;
-    }
-    case OBJECT_BEGIN: {
-        RefPtr<InspectorObject> object = InspectorObject::create();
-        start = tokenEnd;
-        token = parseToken(start, end, &tokenStart, &tokenEnd);
-        while (token != OBJECT_END) {
-            if (token != STRING)
-                return 0;
-            String key;
-            if (!decodeString(tokenStart + 1, tokenEnd - 1, &key))
-                return 0;
-            start = tokenEnd;
-
-            token = parseToken(start, end, &tokenStart, &tokenEnd);
-            if (token != OBJECT_PAIR_SEPARATOR)
-                return 0;
-            start = tokenEnd;
-
-            RefPtr<InspectorValue> value = buildValue(start, end, &tokenEnd, depth + 1);
-            if (!value)
-                return 0;
-            object->setValue(key, value);
-            start = tokenEnd;
-
-            // After a key/value pair, we expect a comma or the end of the
-            // object.
-            token = parseToken(start, end, &tokenStart, &tokenEnd);
-            if (token == LIST_SEPARATOR) {
-                start = tokenEnd;
-                token = parseToken(start, end, &tokenStart, &tokenEnd);
-                 if (token == OBJECT_END)
-                    return 0;
-            } else if (token != OBJECT_END) {
-                // Unexpected value after last object value.  Bail out.
-                return 0;
-            }
-        }
-        if (token != OBJECT_END)
-            return 0;
-        result = object.release();
-        break;
-    }
-
-    default:
-        // We got a token that's not a value.
-        return 0;
-    }
-    *valueTokenEnd = tokenEnd;
-    return result.release();
-}
-
-inline bool escapeChar(UChar c, StringBuilder* dst)
-{
-    switch (c) {
-    case '\b': dst->append("\\b", 2); break;
-    case '\f': dst->append("\\f", 2); break;
-    case '\n': dst->append("\\n", 2); break;
-    case '\r': dst->append("\\r", 2); break;
-    case '\t': dst->append("\\t", 2); break;
-    case '\\': dst->append("\\\\", 2); break;
-    case '"': dst->append("\\\"", 2); break;
-    default:
-        return false;
-    }
-    return true;
-}
-
-inline void doubleQuoteString(const String& str, StringBuilder* dst)
-{
-    dst->append('"');
-    for (unsigned i = 0; i < str.length(); ++i) {
-        UChar c = str[i];
-        if (!escapeChar(c, dst)) {
-            if (c < 32 || c > 126 || c == '<' || c == '>') {
-                // 1. Escaping <, > to prevent script execution.
-                // 2. Technically, we could also pass through c > 126 as UTF8, but this
-                //    is also optional.  It would also be a pain to implement here.
-                unsigned int symbol = static_cast<unsigned int>(c);
-                String symbolCode = String::format("\\u%04X", symbol);
-                dst->append(symbolCode.characters(), symbolCode.length());
-            } else
-                dst->append(c);
-        }
-    }
-    dst->append('"');
-}
-
-} // anonymous namespace
-
-bool InspectorValue::asBoolean(bool*) const
-{
-    return false;
-}
-
-bool InspectorValue::asNumber(double*) const
-{
-    return false;
-}
-
-bool InspectorValue::asNumber(long*) const
-{
-    return false;
-}
-
-bool InspectorValue::asNumber(int*) const
-{
-    return false;
-}
-
-bool InspectorValue::asNumber(unsigned long*) const
-{
-    return false;
-}
-
-bool InspectorValue::asNumber(unsigned int*) const
-{
-    return false;
-}
-
-bool InspectorValue::asString(String*) const
-{
-    return false;
-}
-
-bool InspectorValue::asValue(RefPtr<InspectorValue>* output)
-{
-    *output = this;
-    return true;
-}
-
-bool InspectorValue::asObject(RefPtr<InspectorObject>*)
-{
-    return false;
-}
-
-bool InspectorValue::asArray(RefPtr<InspectorArray>*)
-{
-    return false;
-}
-
-PassRefPtr<InspectorObject> InspectorValue::asObject()
-{
-    return 0;
-}
-
-PassRefPtr<InspectorArray> InspectorValue::asArray()
-{
-    return 0;
-}
-
-PassRefPtr<InspectorValue> InspectorValue::parseJSON(const String& json)
-{
-    const UChar* start = json.characters();
-    const UChar* end = json.characters() + json.length();
-    const UChar *tokenEnd;
-    RefPtr<InspectorValue> value = buildValue(start, end, &tokenEnd, 0);
-    if (!value || tokenEnd != end)
-        return 0;
-    return value.release();
-}
-
-String InspectorValue::toJSONString() const
-{
-    StringBuilder result;
-    result.reserveCapacity(512);
-    writeJSON(&result);
-    return result.toString();
-}
-
-void InspectorValue::writeJSON(StringBuilder* output) const
-{
-    ASSERT(m_type == TypeNull);
-    output->append(nullString, 4);
-}
-
-bool InspectorBasicValue::asBoolean(bool* output) const
-{
-    if (type() != TypeBoolean)
-        return false;
-    *output = m_boolValue;
-    return true;
-}
-
-bool InspectorBasicValue::asNumber(double* output) const
-{
-    if (type() != TypeNumber)
-        return false;
-    *output = m_doubleValue;
-    return true;
-}
-
-bool InspectorBasicValue::asNumber(long* output) const
-{
-    if (type() != TypeNumber)
-        return false;
-    *output = static_cast<long>(m_doubleValue);
-    return true;
-}
-
-bool InspectorBasicValue::asNumber(int* output) const
-{
-    if (type() != TypeNumber)
-        return false;
-    *output = static_cast<int>(m_doubleValue);
-    return true;
-}
-
-bool InspectorBasicValue::asNumber(unsigned long* output) const
-{
-    if (type() != TypeNumber)
-        return false;
-    *output = static_cast<unsigned long>(m_doubleValue);
-    return true;
-}
-
-bool InspectorBasicValue::asNumber(unsigned int* output) const
-{
-    if (type() != TypeNumber)
-        return false;
-    *output = static_cast<unsigned int>(m_doubleValue);
-    return true;
-}
-
-void InspectorBasicValue::writeJSON(StringBuilder* output) const
-{
-    ASSERT(type() == TypeBoolean || type() == TypeNumber);
-    if (type() == TypeBoolean) {
-        if (m_boolValue)
-            output->append(trueString, 4);
-        else
-            output->append(falseString, 5);
-    } else if (type() == TypeNumber) {
-        NumberToLStringBuffer buffer;
-        if (!std::isfinite(m_doubleValue)) {
-            output->append(nullString, 4);
-            return;
-        }
-        DecimalNumber decimal = m_doubleValue;
-        unsigned length = 0;
-        if (decimal.bufferLengthForStringDecimal() > WTF::NumberToStringBufferLength) {
-            // Not enough room for decimal. Use exponential format.
-            if (decimal.bufferLengthForStringExponential() > WTF::NumberToStringBufferLength) {
-                // Fallback for an abnormal case if it's too little even for exponential.
-                output->append("NaN", 3);
-                return;
-            }
-            length = decimal.toStringExponential(buffer, WTF::NumberToStringBufferLength);
-        } else
-            length = decimal.toStringDecimal(buffer, WTF::NumberToStringBufferLength);
-        output->append(buffer, length);
-    }
-}
-
-bool InspectorString::asString(String* output) const
-{
-    *output = m_stringValue;
-    return true;
-}
-
-void InspectorString::writeJSON(StringBuilder* output) const
-{
-    ASSERT(type() == TypeString);
-    doubleQuoteString(m_stringValue, output);
-}
-
-InspectorObjectBase::~InspectorObjectBase()
-{
-}
-
-bool InspectorObjectBase::asObject(RefPtr<InspectorObject>* output)
-{
-    COMPILE_ASSERT(sizeof(InspectorObject) == sizeof(InspectorObjectBase), cannot_cast);
-    *output = static_cast<InspectorObject*>(this);
-    return true;
-}
-
-PassRefPtr<InspectorObject> InspectorObjectBase::asObject()
-{
-    return openAccessors();
-}
-
-InspectorObject* InspectorObjectBase::openAccessors()
-{
-    COMPILE_ASSERT(sizeof(InspectorObject) == sizeof(InspectorObjectBase), cannot_cast);
-    return static_cast<InspectorObject*>(this);
-}
-
-bool InspectorObjectBase::getBoolean(const String& name, bool* output) const
-{
-    RefPtr<InspectorValue> value = get(name);
-    if (!value)
-        return false;
-    return value->asBoolean(output);
-}
-
-bool InspectorObjectBase::getString(const String& name, String* output) const
-{
-    RefPtr<InspectorValue> value = get(name);
-    if (!value)
-        return false;
-    return value->asString(output);
-}
-
-PassRefPtr<InspectorObject> InspectorObjectBase::getObject(const String& name) const
-{
-    PassRefPtr<InspectorValue> value = get(name);
-    if (!value)
-        return 0;
-    return value->asObject();
-}
-
-PassRefPtr<InspectorArray> InspectorObjectBase::getArray(const String& name) const
-{
-    PassRefPtr<InspectorValue> value = get(name);
-    if (!value)
-        return 0;
-    return value->asArray();
-}
-
-PassRefPtr<InspectorValue> InspectorObjectBase::get(const String& name) const
-{
-    Dictionary::const_iterator it = m_data.find(name);
-    if (it == m_data.end())
-        return 0;
-    return it->value;
-}
-
-void InspectorObjectBase::remove(const String& name)
-{
-    m_data.remove(name);
-    for (size_t i = 0; i < m_order.size(); ++i) {
-        if (m_order[i] == name) {
-            m_order.remove(i);
-            break;
-        }
-    }
-}
-
-void InspectorObjectBase::writeJSON(StringBuilder* output) const
-{
-    output->append('{');
-    for (size_t i = 0; i < m_order.size(); ++i) {
-        Dictionary::const_iterator it = m_data.find(m_order[i]);
-        ASSERT(it != m_data.end());
-        if (i)
-            output->append(',');
-        doubleQuoteString(it->key, output);
-        output->append(':');
-        it->value->writeJSON(output);
-    }
-    output->append('}');
-}
-
-InspectorObjectBase::InspectorObjectBase()
-    : InspectorValue(TypeObject)
-    , m_data()
-    , m_order()
-{
-}
-
-InspectorArrayBase::~InspectorArrayBase()
-{
-}
-
-bool InspectorArrayBase::asArray(RefPtr<InspectorArray>* output)
-{
-    COMPILE_ASSERT(sizeof(InspectorArrayBase) == sizeof(InspectorArray), cannot_cast);
-    *output = static_cast<InspectorArray*>(this);
-    return true;
-}
-
-PassRefPtr<InspectorArray> InspectorArrayBase::asArray()
-{
-    COMPILE_ASSERT(sizeof(InspectorArrayBase) == sizeof(InspectorArray), cannot_cast);
-    return static_cast<InspectorArray*>(this);
-}
-
-void InspectorArrayBase::writeJSON(StringBuilder* output) const
-{
-    output->append('[');
-    for (Vector<RefPtr<InspectorValue> >::const_iterator it = m_data.begin(); it != m_data.end(); ++it) {
-        if (it != m_data.begin())
-            output->append(',');
-        (*it)->writeJSON(output);
-    }
-    output->append(']');
-}
-
-InspectorArrayBase::InspectorArrayBase()
-    : InspectorValue(TypeArray)
-    , m_data()
-{
-}
-
-PassRefPtr<InspectorValue> InspectorArrayBase::get(size_t index)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(index < m_data.size());
-    return m_data[index];
-}
-
-} // namespace WebCore
diff --git a/Source/core/inspector/InspectorValues.h b/Source/core/inspector/InspectorValues.h
deleted file mode 100644
index 1f0aecb..0000000
--- a/Source/core/inspector/InspectorValues.h
+++ /dev/null
@@ -1,395 +0,0 @@
-/*
- * Copyright (C) 2009 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef InspectorValues_h
-#define InspectorValues_h
-
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/RefCounted.h>
-#include <wtf/Vector.h>
-#include <wtf/text/StringHash.h>
-#include <wtf/text/WTFString.h>
-
-namespace WebCore {
-
-class InspectorArray;
-class InspectorObject;
-
-class InspectorValue : public RefCounted<InspectorValue> {
-public:
-    static const int maxDepth = 1000;
-
-    InspectorValue() : m_type(TypeNull) { }
-    virtual ~InspectorValue() { }
-
-    static PassRefPtr<InspectorValue> null()
-    {
-        return adoptRef(new InspectorValue());
-    }
-
-    typedef enum {
-        TypeNull = 0,
-        TypeBoolean,
-        TypeNumber,
-        TypeString,
-        TypeObject,
-        TypeArray
-    } Type;
-
-    Type type() const { return m_type; }
-
-    bool isNull() const { return m_type == TypeNull; }
-
-    virtual bool asBoolean(bool* output) const;
-    virtual bool asNumber(double* output) const;
-    virtual bool asNumber(long* output) const;
-    virtual bool asNumber(int* output) const;
-    virtual bool asNumber(unsigned long* output) const;
-    virtual bool asNumber(unsigned int* output) const;
-    virtual bool asString(String* output) const;
-    virtual bool asValue(RefPtr<InspectorValue>* output);
-    virtual bool asObject(RefPtr<InspectorObject>* output);
-    virtual bool asArray(RefPtr<InspectorArray>* output);
-    virtual PassRefPtr<InspectorObject> asObject();
-    virtual PassRefPtr<InspectorArray> asArray();
-
-    static PassRefPtr<InspectorValue> parseJSON(const String& json);
-
-    String toJSONString() const;
-    virtual void writeJSON(StringBuilder* output) const;
-
-protected:
-    explicit InspectorValue(Type type) : m_type(type) { }
-
-private:
-    Type m_type;
-};
-
-class InspectorBasicValue : public InspectorValue {
-public:
-
-    static PassRefPtr<InspectorBasicValue> create(bool value)
-    {
-        return adoptRef(new InspectorBasicValue(value));
-    }
-
-    static PassRefPtr<InspectorBasicValue> create(int value)
-    {
-        return adoptRef(new InspectorBasicValue(value));
-    }
-
-    static PassRefPtr<InspectorBasicValue> create(double value)
-    {
-        return adoptRef(new InspectorBasicValue(value));
-    }
-
-    virtual bool asBoolean(bool* output) const;
-    virtual bool asNumber(double* output) const;
-    virtual bool asNumber(long* output) const;
-    virtual bool asNumber(int* output) const;
-    virtual bool asNumber(unsigned long* output) const;
-    virtual bool asNumber(unsigned int* output) const;
-
-    virtual void writeJSON(StringBuilder* output) const;
-
-private:
-    explicit InspectorBasicValue(bool value) : InspectorValue(TypeBoolean), m_boolValue(value) { }
-    explicit InspectorBasicValue(int value) : InspectorValue(TypeNumber), m_doubleValue((double)value) { }
-    explicit InspectorBasicValue(double value) : InspectorValue(TypeNumber), m_doubleValue(value) { }
-
-    union {
-        bool m_boolValue;
-        double m_doubleValue;
-    };
-};
-
-class InspectorString : public InspectorValue {
-public:
-    static PassRefPtr<InspectorString> create(const String& value)
-    {
-        return adoptRef(new InspectorString(value));
-    }
-
-    static PassRefPtr<InspectorString> create(const char* value)
-    {
-        return adoptRef(new InspectorString(value));
-    }
-
-    virtual bool asString(String* output) const;    
-
-    virtual void writeJSON(StringBuilder* output) const;
-
-private:
-    explicit InspectorString(const String& value) : InspectorValue(TypeString), m_stringValue(value) { }
-    explicit InspectorString(const char* value) : InspectorValue(TypeString), m_stringValue(value) { }
-
-    String m_stringValue;
-};
-
-class InspectorObjectBase : public InspectorValue {
-private:
-    typedef HashMap<String, RefPtr<InspectorValue> > Dictionary;
-
-public:
-    typedef Dictionary::iterator iterator;
-    typedef Dictionary::const_iterator const_iterator;
-
-    virtual PassRefPtr<InspectorObject> asObject();
-    InspectorObject* openAccessors();
-
-protected:
-    ~InspectorObjectBase();
-
-    virtual bool asObject(RefPtr<InspectorObject>* output);
-
-    void setBoolean(const String& name, bool);
-    void setNumber(const String& name, double);
-    void setString(const String& name, const String&);
-    void setValue(const String& name, PassRefPtr<InspectorValue>);
-    void setObject(const String& name, PassRefPtr<InspectorObject>);
-    void setArray(const String& name, PassRefPtr<InspectorArray>);
-
-    iterator find(const String& name);
-    const_iterator find(const String& name) const;
-    bool getBoolean(const String& name, bool* output) const;
-    template<class T> bool getNumber(const String& name, T* output) const
-    {
-        RefPtr<InspectorValue> value = get(name);
-        if (!value)
-            return false;
-        return value->asNumber(output);
-    }
-    bool getString(const String& name, String* output) const;
-    PassRefPtr<InspectorObject> getObject(const String& name) const;
-    PassRefPtr<InspectorArray> getArray(const String& name) const;
-    PassRefPtr<InspectorValue> get(const String& name) const;
-
-    void remove(const String& name);
-
-    virtual void writeJSON(StringBuilder* output) const;
-
-    iterator begin() { return m_data.begin(); }
-    iterator end() { return m_data.end(); }
-    const_iterator begin() const { return m_data.begin(); }
-    const_iterator end() const { return m_data.end(); }
-
-    int size() const { return m_data.size(); }
-
-protected:
-    InspectorObjectBase();
-
-private:
-    Dictionary m_data;
-    Vector<String> m_order;
-};
-
-class InspectorObject : public InspectorObjectBase {
-public:
-    static PassRefPtr<InspectorObject> create()
-    {
-        return adoptRef(new InspectorObject());
-    }
-
-    using InspectorObjectBase::asObject;
-
-    using InspectorObjectBase::setBoolean;
-    using InspectorObjectBase::setNumber;
-    using InspectorObjectBase::setString;
-    using InspectorObjectBase::setValue;
-    using InspectorObjectBase::setObject;
-    using InspectorObjectBase::setArray;
-
-    using InspectorObjectBase::find;
-    using InspectorObjectBase::getBoolean;
-    using InspectorObjectBase::getNumber;
-    using InspectorObjectBase::getString;
-    using InspectorObjectBase::getObject;
-    using InspectorObjectBase::getArray;
-    using InspectorObjectBase::get;
-
-    using InspectorObjectBase::remove;
-
-    using InspectorObjectBase::begin;
-    using InspectorObjectBase::end;
-
-    using InspectorObjectBase::size;
-};
-
-
-class InspectorArrayBase : public InspectorValue {
-public:
-    typedef Vector<RefPtr<InspectorValue> >::iterator iterator;
-    typedef Vector<RefPtr<InspectorValue> >::const_iterator const_iterator;
-
-    virtual PassRefPtr<InspectorArray> asArray();
-
-    unsigned length() const { return m_data.size(); }
-
-protected:
-    ~InspectorArrayBase();
-
-    virtual bool asArray(RefPtr<InspectorArray>* output);
-
-    void pushBoolean(bool);
-    void pushInt(int);
-    void pushNumber(double);
-    void pushString(const String&);
-    void pushValue(PassRefPtr<InspectorValue>);
-    void pushObject(PassRefPtr<InspectorObject>);
-    void pushArray(PassRefPtr<InspectorArray>);
-
-    PassRefPtr<InspectorValue> get(size_t index);
-
-    virtual void writeJSON(StringBuilder* output) const;
-
-    iterator begin() { return m_data.begin(); }
-    iterator end() { return m_data.end(); }
-    const_iterator begin() const { return m_data.begin(); }
-    const_iterator end() const { return m_data.end(); }
-
-protected:
-    InspectorArrayBase();
-
-private:
-    Vector<RefPtr<InspectorValue> > m_data;
-};
-
-class InspectorArray : public InspectorArrayBase {
-public:
-    static PassRefPtr<InspectorArray> create()
-    {
-        return adoptRef(new InspectorArray());
-    }
-
-    using InspectorArrayBase::asArray;
-
-    using InspectorArrayBase::pushBoolean;
-    using InspectorArrayBase::pushInt;
-    using InspectorArrayBase::pushNumber;
-    using InspectorArrayBase::pushString;
-    using InspectorArrayBase::pushValue;
-    using InspectorArrayBase::pushObject;
-    using InspectorArrayBase::pushArray;
-
-    using InspectorArrayBase::get;
-
-    using InspectorArrayBase::begin;
-    using InspectorArrayBase::end;
-};
-
-
-inline InspectorObjectBase::iterator InspectorObjectBase::find(const String& name)
-{
-    return m_data.find(name);
-}
-
-inline InspectorObjectBase::const_iterator InspectorObjectBase::find(const String& name) const
-{
-    return m_data.find(name);
-}
-
-inline void InspectorObjectBase::setBoolean(const String& name, bool value)
-{
-    setValue(name, InspectorBasicValue::create(value));
-}
-
-inline void InspectorObjectBase::setNumber(const String& name, double value)
-{
-    setValue(name, InspectorBasicValue::create(value));
-}
-
-inline void InspectorObjectBase::setString(const String& name, const String& value)
-{
-    setValue(name, InspectorString::create(value));
-}
-
-inline void InspectorObjectBase::setValue(const String& name, PassRefPtr<InspectorValue> value)
-{
-    ASSERT(value);
-    if (m_data.set(name, value).isNewEntry)
-        m_order.append(name);
-}
-
-inline void InspectorObjectBase::setObject(const String& name, PassRefPtr<InspectorObject> value)
-{
-    ASSERT(value);
-    if (m_data.set(name, value).isNewEntry)
-        m_order.append(name);
-}
-
-inline void InspectorObjectBase::setArray(const String& name, PassRefPtr<InspectorArray> value)
-{
-    ASSERT(value);
-    if (m_data.set(name, value).isNewEntry)
-        m_order.append(name);
-}
-
-inline void InspectorArrayBase::pushBoolean(bool value)
-{
-    m_data.append(InspectorBasicValue::create(value));
-}
-
-inline void InspectorArrayBase::pushInt(int value)
-{
-    m_data.append(InspectorBasicValue::create(value));
-}
-
-inline void InspectorArrayBase::pushNumber(double value)
-{
-    m_data.append(InspectorBasicValue::create(value));
-}
-
-inline void InspectorArrayBase::pushString(const String& value)
-{
-    m_data.append(InspectorString::create(value));
-}
-
-inline void InspectorArrayBase::pushValue(PassRefPtr<InspectorValue> value)
-{
-    ASSERT(value);
-    m_data.append(value);
-}
-
-inline void InspectorArrayBase::pushObject(PassRefPtr<InspectorObject> value)
-{
-    ASSERT(value);
-    m_data.append(value);
-}
-
-inline void InspectorArrayBase::pushArray(PassRefPtr<InspectorArray> value)
-{
-    ASSERT(value);
-    m_data.append(value);
-}
-
-} // namespace WebCore
-
-#endif // !defined(InspectorValues_h)
diff --git a/Source/core/inspector/InspectorWorkerAgent.cpp b/Source/core/inspector/InspectorWorkerAgent.cpp
index e77d62e..4665d47 100644
--- a/Source/core/inspector/InspectorWorkerAgent.cpp
+++ b/Source/core/inspector/InspectorWorkerAgent.cpp
@@ -34,9 +34,10 @@
 
 #include "InspectorFrontend.h"
 #include "core/inspector/InspectorState.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/inspector/InstrumentingAgents.h"
-#include "core/workers/WorkerContextProxy.h"
+#include "core/inspector/JSONParser.h"
+#include "core/platform/JSONValues.h"
+#include "core/workers/WorkerGlobalScopeProxy.h"
 #include "weborigin/KURL.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/RefPtr.h"
@@ -48,10 +49,10 @@
 static const char autoconnectToWorkers[] = "autoconnectToWorkers";
 };
 
-class InspectorWorkerAgent::WorkerFrontendChannel : public WorkerContextProxy::PageInspector {
+class InspectorWorkerAgent::WorkerFrontendChannel : public WorkerGlobalScopeProxy::PageInspector {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    explicit WorkerFrontendChannel(InspectorFrontend* frontend, WorkerContextProxy* proxy)
+    explicit WorkerFrontendChannel(InspectorFrontend* frontend, WorkerGlobalScopeProxy* proxy)
         : m_frontend(frontend)
         , m_proxy(proxy)
         , m_id(s_nextId++)
@@ -60,13 +61,13 @@
     }
     virtual ~WorkerFrontendChannel()
     {
-        disconnectFromWorkerContext();
+        disconnectFromWorkerGlobalScope();
     }
 
     int id() const { return m_id; }
-    WorkerContextProxy* proxy() const { return m_proxy; }
+    WorkerGlobalScopeProxy* proxy() const { return m_proxy; }
 
-    void connectToWorkerContext()
+    void connectToWorkerGlobalScope()
     {
         if (m_connected)
             return;
@@ -74,7 +75,7 @@
         m_proxy->connectToInspector(this);
     }
 
-    void disconnectFromWorkerContext()
+    void disconnectFromWorkerGlobalScope()
     {
         if (!m_connected)
             return;
@@ -83,20 +84,20 @@
     }
 
 private:
-    // WorkerContextProxy::PageInspector implementation
+    // WorkerGlobalScopeProxy::PageInspector implementation
     virtual void dispatchMessageFromWorker(const String& message)
     {
-        RefPtr<InspectorValue> value = InspectorValue::parseJSON(message);
+        RefPtr<JSONValue> value = parseJSON(message);
         if (!value)
             return;
-        RefPtr<InspectorObject> messageObject = value->asObject();
+        RefPtr<JSONObject> messageObject = value->asObject();
         if (!messageObject)
             return;
         m_frontend->worker()->dispatchMessageFromWorker(m_id, messageObject);
     }
 
     InspectorFrontend* m_frontend;
-    WorkerContextProxy* m_proxy;
+    WorkerGlobalScopeProxy* m_proxy;
     int m_id;
     bool m_connected;
     static int s_nextId;
@@ -164,7 +165,7 @@
 {
     WorkerFrontendChannel* channel = m_idToChannel.get(workerId);
     if (channel)
-        channel->connectToWorkerContext();
+        channel->connectToWorkerGlobalScope();
     else
         *error = "Worker is gone";
 }
@@ -173,12 +174,12 @@
 {
     WorkerFrontendChannel* channel = m_idToChannel.get(workerId);
     if (channel)
-        channel->disconnectFromWorkerContext();
+        channel->disconnectFromWorkerGlobalScope();
     else
         *error = "Worker is gone";
 }
 
-void InspectorWorkerAgent::sendMessageToWorker(ErrorString* error, int workerId, const RefPtr<InspectorObject>& message)
+void InspectorWorkerAgent::sendMessageToWorker(ErrorString* error, int workerId, const RefPtr<JSONObject>& message)
 {
     WorkerFrontendChannel* channel = m_idToChannel.get(workerId);
     if (channel)
@@ -197,14 +198,14 @@
     return m_state->getBoolean(WorkerAgentState::autoconnectToWorkers);
 }
 
-void InspectorWorkerAgent::didStartWorkerContext(WorkerContextProxy* workerContextProxy, const KURL& url)
+void InspectorWorkerAgent::didStartWorkerGlobalScope(WorkerGlobalScopeProxy* workerGlobalScopeProxy, const KURL& url)
 {
-    m_dedicatedWorkers.set(workerContextProxy, url.string());
+    m_dedicatedWorkers.set(workerGlobalScopeProxy, url.string());
     if (m_inspectorFrontend && m_state->getBoolean(WorkerAgentState::workerInspectionEnabled))
-        createWorkerFrontendChannel(workerContextProxy, url.string());
+        createWorkerFrontendChannel(workerGlobalScopeProxy, url.string());
 }
 
-void InspectorWorkerAgent::workerContextTerminated(WorkerContextProxy* proxy)
+void InspectorWorkerAgent::workerGlobalScopeTerminated(WorkerGlobalScopeProxy* proxy)
 {
     m_dedicatedWorkers.remove(proxy);
     for (WorkerChannels::iterator it = m_idToChannel.begin(); it != m_idToChannel.end(); ++it) {
@@ -226,21 +227,21 @@
 void InspectorWorkerAgent::destroyWorkerFrontendChannels()
 {
     for (WorkerChannels::iterator it = m_idToChannel.begin(); it != m_idToChannel.end(); ++it) {
-        it->value->disconnectFromWorkerContext();
+        it->value->disconnectFromWorkerGlobalScope();
         delete it->value;
     }
     m_idToChannel.clear();
 }
 
-void InspectorWorkerAgent::createWorkerFrontendChannel(WorkerContextProxy* workerContextProxy, const String& url)
+void InspectorWorkerAgent::createWorkerFrontendChannel(WorkerGlobalScopeProxy* workerGlobalScopeProxy, const String& url)
 {
-    WorkerFrontendChannel* channel = new WorkerFrontendChannel(m_inspectorFrontend, workerContextProxy);
+    WorkerFrontendChannel* channel = new WorkerFrontendChannel(m_inspectorFrontend, workerGlobalScopeProxy);
     m_idToChannel.set(channel->id(), channel);
 
     ASSERT(m_inspectorFrontend);
     bool autoconnectToWorkers = m_state->getBoolean(WorkerAgentState::autoconnectToWorkers);
     if (autoconnectToWorkers)
-        channel->connectToWorkerContext();
+        channel->connectToWorkerGlobalScope();
     m_inspectorFrontend->worker()->workerCreated(channel->id(), url, autoconnectToWorkers);
 }
 
diff --git a/Source/core/inspector/InspectorWorkerAgent.h b/Source/core/inspector/InspectorWorkerAgent.h
index 4f53b1f..74146aa 100644
--- a/Source/core/inspector/InspectorWorkerAgent.h
+++ b/Source/core/inspector/InspectorWorkerAgent.h
@@ -37,11 +37,11 @@
 
 namespace WebCore {
 class InspectorFrontend;
-class InspectorObject;
 class InspectorState;
 class InstrumentingAgents;
+class JSONObject;
 class KURL;
-class WorkerContextProxy;
+class WorkerGlobalScopeProxy;
 
 typedef String ErrorString;
 
@@ -56,8 +56,8 @@
 
     // Called from InspectorInstrumentation
     bool shouldPauseDedicatedWorkerOnStart();
-    void didStartWorkerContext(WorkerContextProxy*, const KURL&);
-    void workerContextTerminated(WorkerContextProxy*);
+    void didStartWorkerGlobalScope(WorkerGlobalScopeProxy*, const KURL&);
+    void workerGlobalScopeTerminated(WorkerGlobalScopeProxy*);
 
     // Called from InspectorBackendDispatcher
     virtual void enable(ErrorString*);
@@ -65,13 +65,13 @@
     virtual void canInspectWorkers(ErrorString*, bool*);
     virtual void connectToWorker(ErrorString*, int workerId);
     virtual void disconnectFromWorker(ErrorString*, int workerId);
-    virtual void sendMessageToWorker(ErrorString*, int workerId, const RefPtr<InspectorObject>& message);
+    virtual void sendMessageToWorker(ErrorString*, int workerId, const RefPtr<JSONObject>& message);
     virtual void setAutoconnectToWorkers(ErrorString*, bool value);
 
 private:
     InspectorWorkerAgent(InstrumentingAgents*, InspectorCompositeState*);
     void createWorkerFrontendChannelsForExistingWorkers();
-    void createWorkerFrontendChannel(WorkerContextProxy*, const String& url);
+    void createWorkerFrontendChannel(WorkerGlobalScopeProxy*, const String& url);
     void destroyWorkerFrontendChannels();
 
     InspectorFrontend* m_inspectorFrontend;
@@ -79,7 +79,7 @@
     class WorkerFrontendChannel;
     typedef HashMap<int, WorkerFrontendChannel*> WorkerChannels;
     WorkerChannels m_idToChannel;
-    typedef HashMap<WorkerContextProxy*, String> DedicatedWorkers;
+    typedef HashMap<WorkerGlobalScopeProxy*, String> DedicatedWorkers;
     DedicatedWorkers m_dedicatedWorkers;
 };
 
diff --git a/Source/core/inspector/InspectorWorkerResource.h b/Source/core/inspector/InspectorWorkerResource.h
deleted file mode 100644
index f8bed52..0000000
--- a/Source/core/inspector/InspectorWorkerResource.h
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef InspectorWorkerResource_h
-#define InspectorWorkerResource_h
-
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/WTFString.h>
-
-namespace WebCore {
-
-class InspectorWorkerResource : public RefCounted<InspectorWorkerResource> {
-public:
-    static PassRefPtr<InspectorWorkerResource> create(intptr_t id, const String& url, bool isSharedWorker)
-    {
-        return adoptRef(new InspectorWorkerResource(id, url, isSharedWorker));
-    }
-
-    intptr_t id() const { return m_id; }
-    const String& url() const { return m_url; }
-    bool isSharedWorker() const { return m_isSharedWorker; }
-private:
-    InspectorWorkerResource(intptr_t id, const String& url, bool isSharedWorker)
-        : m_id(id)
-        , m_url(url)
-        , m_isSharedWorker(isSharedWorker)
-    {
-    }
-
-    intptr_t m_id;
-    String m_url;
-    bool m_isSharedWorker;
-};
-
-} // namespace WebCore
-
-#endif // InspectorWorkerResource_h
diff --git a/Source/core/inspector/JSONParser.cpp b/Source/core/inspector/JSONParser.cpp
new file mode 100644
index 0000000..bf364db
--- /dev/null
+++ b/Source/core/inspector/JSONParser.cpp
@@ -0,0 +1,478 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/inspector/JSONParser.h"
+
+#include "core/platform/JSONValues.h"
+#include "wtf/text/StringBuilder.h"
+
+namespace WebCore {
+
+namespace {
+
+const int stackLimit = 1000;
+
+enum Token {
+    ObjectBegin,
+    ObjectEnd,
+    ArrayBegin,
+    ArrayEnd,
+    StringLiteral,
+    Number,
+    BoolTrue,
+    BoolFalse,
+    NullToken,
+    ListSeparator,
+    ObjectPairSeparator,
+    InvalidToken,
+};
+
+const char* const nullString = "null";
+const char* const trueString = "true";
+const char* const falseString = "false";
+
+template<typename CharType>
+bool parseConstToken(const CharType* start, const CharType* end, const CharType** tokenEnd, const char* token)
+{
+    while (start < end && *token != '\0' && *start++ == *token++) { }
+    if (*token != '\0')
+        return false;
+    *tokenEnd = start;
+    return true;
+}
+
+template<typename CharType>
+bool readInt(const CharType* start, const CharType* end, const CharType** tokenEnd, bool canHaveLeadingZeros)
+{
+    if (start == end)
+        return false;
+    bool haveLeadingZero = '0' == *start;
+    int length = 0;
+    while (start < end && '0' <= *start && *start <= '9') {
+        ++start;
+        ++length;
+    }
+    if (!length)
+        return false;
+    if (!canHaveLeadingZeros && length > 1 && haveLeadingZero)
+        return false;
+    *tokenEnd = start;
+    return true;
+}
+
+template<typename CharType>
+bool parseNumberToken(const CharType* start, const CharType* end, const CharType** tokenEnd)
+{
+    // We just grab the number here. We validate the size in DecodeNumber.
+    // According to RFC4627, a valid number is: [minus] int [frac] [exp]
+    if (start == end)
+        return false;
+    CharType c = *start;
+    if ('-' == c)
+        ++start;
+
+    if (!readInt(start, end, &start, false))
+        return false;
+    if (start == end) {
+        *tokenEnd = start;
+        return true;
+    }
+
+    // Optional fraction part
+    c = *start;
+    if ('.' == c) {
+        ++start;
+        if (!readInt(start, end, &start, true))
+            return false;
+        if (start == end) {
+            *tokenEnd = start;
+            return true;
+        }
+        c = *start;
+    }
+
+    // Optional exponent part
+    if ('e' == c || 'E' == c) {
+        ++start;
+        if (start == end)
+            return false;
+        c = *start;
+        if ('-' == c || '+' == c) {
+            ++start;
+            if (start == end)
+                return false;
+        }
+        if (!readInt(start, end, &start, true))
+            return false;
+    }
+
+    *tokenEnd = start;
+    return true;
+}
+
+template<typename CharType>
+bool readHexDigits(const CharType* start, const CharType* end, const CharType** tokenEnd, int digits)
+{
+    if (end - start < digits)
+        return false;
+    for (int i = 0; i < digits; ++i) {
+        CharType c = *start++;
+        if (!(('0' <= c && c <= '9') || ('a' <= c && c <= 'f') || ('A' <= c && c <= 'F')))
+            return false;
+    }
+    *tokenEnd = start;
+    return true;
+}
+
+template<typename CharType>
+bool parseStringToken(const CharType* start, const CharType* end, const CharType** tokenEnd)
+{
+    while (start < end) {
+        CharType c = *start++;
+        if ('\\' == c) {
+            c = *start++;
+            // Make sure the escaped char is valid.
+            switch (c) {
+            case 'x':
+                if (!readHexDigits(start, end, &start, 2))
+                    return false;
+                break;
+            case 'u':
+                if (!readHexDigits(start, end, &start, 4))
+                    return false;
+                break;
+            case '\\':
+            case '/':
+            case 'b':
+            case 'f':
+            case 'n':
+            case 'r':
+            case 't':
+            case 'v':
+            case '"':
+                break;
+            default:
+                return false;
+            }
+        } else if ('"' == c) {
+            *tokenEnd = start;
+            return true;
+        }
+    }
+    return false;
+}
+
+template<typename CharType>
+Token parseToken(const CharType* start, const CharType* end, const CharType** tokenStart, const CharType** tokenEnd)
+{
+    while (start < end && isSpaceOrNewline(*start))
+        ++start;
+
+    if (start == end)
+        return InvalidToken;
+
+    *tokenStart = start;
+
+    switch (*start) {
+    case 'n':
+        if (parseConstToken(start, end, tokenEnd, nullString))
+            return NullToken;
+        break;
+    case 't':
+        if (parseConstToken(start, end, tokenEnd, trueString))
+            return BoolTrue;
+        break;
+    case 'f':
+        if (parseConstToken(start, end, tokenEnd, falseString))
+            return BoolFalse;
+        break;
+    case '[':
+        *tokenEnd = start + 1;
+        return ArrayBegin;
+    case ']':
+        *tokenEnd = start + 1;
+        return ArrayEnd;
+    case ',':
+        *tokenEnd = start + 1;
+        return ListSeparator;
+    case '{':
+        *tokenEnd = start + 1;
+        return ObjectBegin;
+    case '}':
+        *tokenEnd = start + 1;
+        return ObjectEnd;
+    case ':':
+        *tokenEnd = start + 1;
+        return ObjectPairSeparator;
+    case '0':
+    case '1':
+    case '2':
+    case '3':
+    case '4':
+    case '5':
+    case '6':
+    case '7':
+    case '8':
+    case '9':
+    case '-':
+        if (parseNumberToken(start, end, tokenEnd))
+            return Number;
+        break;
+    case '"':
+        if (parseStringToken(start + 1, end, tokenEnd))
+            return StringLiteral;
+        break;
+    }
+    return InvalidToken;
+}
+
+template<typename CharType>
+inline int hexToInt(CharType c)
+{
+    if ('0' <= c && c <= '9')
+        return c - '0';
+    if ('A' <= c && c <= 'F')
+        return c - 'A' + 10;
+    if ('a' <= c && c <= 'f')
+        return c - 'a' + 10;
+    ASSERT_NOT_REACHED();
+    return 0;
+}
+
+template<typename CharType>
+bool decodeString(const CharType* start, const CharType* end, StringBuilder* output)
+{
+    while (start < end) {
+        CharType c = *start++;
+        if ('\\' != c) {
+            output->append(c);
+            continue;
+        }
+        c = *start++;
+        switch (c) {
+        case '"':
+        case '/':
+        case '\\':
+            break;
+        case 'b':
+            c = '\b';
+            break;
+        case 'f':
+            c = '\f';
+            break;
+        case 'n':
+            c = '\n';
+            break;
+        case 'r':
+            c = '\r';
+            break;
+        case 't':
+            c = '\t';
+            break;
+        case 'v':
+            c = '\v';
+            break;
+        case 'x':
+            c = (hexToInt(*start) << 4) +
+                hexToInt(*(start + 1));
+            start += 2;
+            break;
+        case 'u':
+            c = (hexToInt(*start) << 12) +
+                (hexToInt(*(start + 1)) << 8) +
+                (hexToInt(*(start + 2)) << 4) +
+                hexToInt(*(start + 3));
+            start += 4;
+            break;
+        default:
+            return false;
+        }
+        output->append(c);
+    }
+    return true;
+}
+
+template<typename CharType>
+bool decodeString(const CharType* start, const CharType* end, String* output)
+{
+    if (start == end) {
+        *output = "";
+        return true;
+    }
+    if (start > end)
+        return false;
+    StringBuilder buffer;
+    buffer.reserveCapacity(end - start);
+    if (!decodeString(start, end, &buffer))
+        return false;
+    *output = buffer.toString();
+    return true;
+}
+
+template<typename CharType>
+PassRefPtr<JSONValue> buildValue(const CharType* start, const CharType* end, const CharType** valueTokenEnd, int depth)
+{
+    if (depth > stackLimit)
+        return 0;
+
+    RefPtr<JSONValue> result;
+    const CharType* tokenStart;
+    const CharType* tokenEnd;
+    Token token = parseToken(start, end, &tokenStart, &tokenEnd);
+    switch (token) {
+    case InvalidToken:
+        return 0;
+    case NullToken:
+        result = JSONValue::null();
+        break;
+    case BoolTrue:
+        result = JSONBasicValue::create(true);
+        break;
+    case BoolFalse:
+        result = JSONBasicValue::create(false);
+        break;
+    case Number: {
+        bool ok;
+        double value = charactersToDouble(tokenStart, tokenEnd - tokenStart, &ok);
+        if (!ok)
+            return 0;
+        result = JSONBasicValue::create(value);
+        break;
+    }
+    case StringLiteral: {
+        String value;
+        bool ok = decodeString(tokenStart + 1, tokenEnd - 1, &value);
+        if (!ok)
+            return 0;
+        result = JSONString::create(value);
+        break;
+    }
+    case ArrayBegin: {
+        RefPtr<JSONArray> array = JSONArray::create();
+        start = tokenEnd;
+        token = parseToken(start, end, &tokenStart, &tokenEnd);
+        while (token != ArrayEnd) {
+            RefPtr<JSONValue> arrayNode = buildValue(start, end, &tokenEnd, depth + 1);
+            if (!arrayNode)
+                return 0;
+            array->pushValue(arrayNode);
+
+            // After a list value, we expect a comma or the end of the list.
+            start = tokenEnd;
+            token = parseToken(start, end, &tokenStart, &tokenEnd);
+            if (token == ListSeparator) {
+                start = tokenEnd;
+                token = parseToken(start, end, &tokenStart, &tokenEnd);
+                if (token == ArrayEnd)
+                    return 0;
+            } else if (token != ArrayEnd) {
+                // Unexpected value after list value. Bail out.
+                return 0;
+            }
+        }
+        if (token != ArrayEnd)
+            return 0;
+        result = array.release();
+        break;
+    }
+    case ObjectBegin: {
+        RefPtr<JSONObject> object = JSONObject::create();
+        start = tokenEnd;
+        token = parseToken(start, end, &tokenStart, &tokenEnd);
+        while (token != ObjectEnd) {
+            if (token != StringLiteral)
+                return 0;
+            String key;
+            if (!decodeString(tokenStart + 1, tokenEnd - 1, &key))
+                return 0;
+            start = tokenEnd;
+
+            token = parseToken(start, end, &tokenStart, &tokenEnd);
+            if (token != ObjectPairSeparator)
+                return 0;
+            start = tokenEnd;
+
+            RefPtr<JSONValue> value = buildValue(start, end, &tokenEnd, depth + 1);
+            if (!value)
+                return 0;
+            object->setValue(key, value);
+            start = tokenEnd;
+
+            // After a key/value pair, we expect a comma or the end of the
+            // object.
+            token = parseToken(start, end, &tokenStart, &tokenEnd);
+            if (token == ListSeparator) {
+                start = tokenEnd;
+                token = parseToken(start, end, &tokenStart, &tokenEnd);
+                if (token == ObjectEnd)
+                    return 0;
+            } else if (token != ObjectEnd) {
+                // Unexpected value after last object value. Bail out.
+                return 0;
+            }
+        }
+        if (token != ObjectEnd)
+            return 0;
+        result = object.release();
+        break;
+    }
+
+    default:
+        // We got a token that's not a value.
+        return 0;
+    }
+    *valueTokenEnd = tokenEnd;
+    return result.release();
+}
+
+template<typename CharType>
+PassRefPtr<JSONValue> parseJSONInternal(const CharType* start, unsigned length)
+{
+    const CharType* end = start + length;
+    const CharType *tokenEnd;
+    RefPtr<JSONValue> value = buildValue(start, end, &tokenEnd, 0);
+    if (!value || tokenEnd != end)
+        return 0;
+    return value.release();
+}
+
+} // anonymous namespace
+
+PassRefPtr<JSONValue> parseJSON(const String& json)
+{
+    if (json.isEmpty())
+        return 0;
+    if (json.is8Bit())
+        return parseJSONInternal(json.characters8(), json.length());
+    return parseJSONInternal(json.characters16(), json.length());
+}
+
+} // namespace WebCore
diff --git a/Source/core/workers/SharedWorkerContext.idl b/Source/core/inspector/JSONParser.h
similarity index 85%
copy from Source/core/workers/SharedWorkerContext.idl
copy to Source/core/inspector/JSONParser.h
index 52fc0a2..7979944 100644
--- a/Source/core/workers/SharedWorkerContext.idl
+++ b/Source/core/inspector/JSONParser.h
@@ -28,10 +28,18 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-[
-    NoInterfaceObject
-] interface SharedWorkerContext : WorkerContext {
-    readonly attribute DOMString name;
-             attribute EventListener onconnect;
-};
+#ifndef JSONParser_h
+#define JSONParser_h
 
+#include "wtf/PassRefPtr.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class JSONValue;
+
+PassRefPtr<JSONValue> parseJSON(const String& json);
+
+} // namespace WebCore
+
+#endif // !defined(JSONParser_h)
diff --git a/Source/core/inspector/MemoryInstrumentationImpl.cpp b/Source/core/inspector/MemoryInstrumentationImpl.cpp
index b13bb9c..467d2f4 100644
--- a/Source/core/inspector/MemoryInstrumentationImpl.cpp
+++ b/Source/core/inspector/MemoryInstrumentationImpl.cpp
@@ -33,11 +33,11 @@
 
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/inspector/HeapGraphSerializer.h"
-#include <wtf/Assertions.h>
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/MemoryInstrumentationHashSet.h>
-#include <wtf/MemoryInstrumentationVector.h>
-#include <wtf/text/StringHash.h>
+#include "wtf/Assertions.h"
+#include "wtf/MemoryInstrumentationHashMap.h"
+#include "wtf/MemoryInstrumentationHashSet.h"
+#include "wtf/MemoryInstrumentationVector.h"
+#include "wtf/text/StringHash.h"
 
 namespace WebCore {
 
diff --git a/Source/core/inspector/NetworkResourcesData.h b/Source/core/inspector/NetworkResourcesData.h
index 101b9a0..6dc84e2 100644
--- a/Source/core/inspector/NetworkResourcesData.h
+++ b/Source/core/inspector/NetworkResourcesData.h
@@ -36,7 +36,6 @@
 #include "wtf/Deque.h"
 #include "wtf/HashMap.h"
 #include "wtf/RefCounted.h"
-#include "wtf/text/StringBuilder.h"
 #include "wtf/text/WTFString.h"
 
 
diff --git a/Source/core/inspector/ScriptCallFrame.cpp b/Source/core/inspector/ScriptCallFrame.cpp
index 65daa67..42433e3 100644
--- a/Source/core/inspector/ScriptCallFrame.cpp
+++ b/Source/core/inspector/ScriptCallFrame.cpp
@@ -31,8 +31,6 @@
 #include "config.h"
 #include "core/inspector/ScriptCallFrame.h"
 
-#include <wtf/RefPtr.h>
-
 namespace WebCore {
 
 ScriptCallFrame::ScriptCallFrame(const String& functionName, const String& scriptName, unsigned lineNumber, unsigned column)
diff --git a/Source/core/inspector/ScriptCallFrame.h b/Source/core/inspector/ScriptCallFrame.h
index 93fc006..941c549 100644
--- a/Source/core/inspector/ScriptCallFrame.h
+++ b/Source/core/inspector/ScriptCallFrame.h
@@ -38,8 +38,6 @@
 
 namespace WebCore {
 
-class InspectorObject;
-
 class ScriptCallFrame  {
 public:
     ScriptCallFrame(const String& functionName, const String& scriptName, unsigned lineNumber, unsigned column = 0);
diff --git a/Source/core/inspector/ScriptCallStack.h b/Source/core/inspector/ScriptCallStack.h
index 3796fe1..ce605ea 100644
--- a/Source/core/inspector/ScriptCallStack.h
+++ b/Source/core/inspector/ScriptCallStack.h
@@ -40,8 +40,6 @@
 
 namespace WebCore {
 
-class InspectorArray;
-
 class ScriptCallStack : public RefCounted<ScriptCallStack> {
 public:
     static const size_t maxCallStackSizeToCapture = 200;
diff --git a/Source/core/inspector/ScriptProfile.cpp b/Source/core/inspector/ScriptProfile.cpp
index 2683c6a..f1f76d3 100644
--- a/Source/core/inspector/ScriptProfile.cpp
+++ b/Source/core/inspector/ScriptProfile.cpp
@@ -72,6 +72,7 @@
 
     RefPtr<TypeBuilder::Profiler::CPUProfileNode> result = TypeBuilder::Profiler::CPUProfileNode::create()
         .setFunctionName(toWebCoreString(node->GetFunctionName()))
+        .setScriptId(String::number(node->GetScriptId()))
         .setUrl(toWebCoreString(node->GetScriptResourceName()))
         .setLineNumber(node->GetLineNumber())
         .setTotalTime(node->GetTotalTime())
diff --git a/Source/core/inspector/ScriptProfile.h b/Source/core/inspector/ScriptProfile.h
index de58931..19afeac 100644
--- a/Source/core/inspector/ScriptProfile.h
+++ b/Source/core/inspector/ScriptProfile.h
@@ -41,8 +41,6 @@
 
 namespace WebCore {
 
-class InspectorObject;
-
 class ScriptProfile : public RefCounted<ScriptProfile> {
 public:
     static PassRefPtr<ScriptProfile> create(const v8::CpuProfile* profile, double idleTime)
diff --git a/Source/core/inspector/TimelineRecordFactory.cpp b/Source/core/inspector/TimelineRecordFactory.cpp
index 3e12727..3f9afe3 100644
--- a/Source/core/inspector/TimelineRecordFactory.cpp
+++ b/Source/core/inspector/TimelineRecordFactory.cpp
@@ -33,19 +33,19 @@
 
 #include "bindings/v8/ScriptCallStackFactory.h"
 #include "core/dom/Event.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/inspector/ScriptCallStack.h"
+#include "core/platform/JSONValues.h"
 #include "core/platform/graphics/FloatQuad.h"
 #include "core/platform/graphics/LayoutRect.h"
 #include "core/platform/network/ResourceRequest.h"
 #include "core/platform/network/ResourceResponse.h"
-#include <wtf/CurrentTime.h>
+#include "wtf/CurrentTime.h"
 
 namespace WebCore {
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createGenericRecord(double startTime, int maxCallStackDepth, const String& type)
+PassRefPtr<JSONObject> TimelineRecordFactory::createGenericRecord(double startTime, int maxCallStackDepth, const String& type)
 {
-    RefPtr<InspectorObject> record = InspectorObject::create();
+    RefPtr<JSONObject> record = JSONObject::create();
     record->setNumber("startTime", startTime);
 
     if (maxCallStackDepth) {
@@ -57,110 +57,110 @@
     return record.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createBackgroundRecord(double startTime, const String& threadName)
+PassRefPtr<JSONObject> TimelineRecordFactory::createBackgroundRecord(double startTime, const String& threadName)
 {
-    RefPtr<InspectorObject> record = InspectorObject::create();
+    RefPtr<JSONObject> record = JSONObject::create();
     record->setNumber("startTime", startTime);
     record->setString("thread", threadName);
     return record.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createGCEventData(const size_t usedHeapSizeDelta)
+PassRefPtr<JSONObject> TimelineRecordFactory::createGCEventData(const size_t usedHeapSizeDelta)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setNumber("usedHeapSizeDelta", usedHeapSizeDelta);
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createFunctionCallData(const String& scriptName, int scriptLine)
+PassRefPtr<JSONObject> TimelineRecordFactory::createFunctionCallData(const String& scriptName, int scriptLine)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setString("scriptName", scriptName);
     data->setNumber("scriptLine", scriptLine);
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createEventDispatchData(const Event& event)
+PassRefPtr<JSONObject> TimelineRecordFactory::createEventDispatchData(const Event& event)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setString("type", event.type().string());
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createGenericTimerData(int timerId)
+PassRefPtr<JSONObject> TimelineRecordFactory::createGenericTimerData(int timerId)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setNumber("timerId", timerId);
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createTimerInstallData(int timerId, int timeout, bool singleShot)
+PassRefPtr<JSONObject> TimelineRecordFactory::createTimerInstallData(int timerId, int timeout, bool singleShot)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setNumber("timerId", timerId);
     data->setNumber("timeout", timeout);
     data->setBoolean("singleShot", singleShot);
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createXHRReadyStateChangeData(const String& url, int readyState)
+PassRefPtr<JSONObject> TimelineRecordFactory::createXHRReadyStateChangeData(const String& url, int readyState)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setString("url", url);
     data->setNumber("readyState", readyState);
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createXHRLoadData(const String& url)
+PassRefPtr<JSONObject> TimelineRecordFactory::createXHRLoadData(const String& url)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setString("url", url);
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createEvaluateScriptData(const String& url, double lineNumber)
+PassRefPtr<JSONObject> TimelineRecordFactory::createEvaluateScriptData(const String& url, double lineNumber)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setString("url", url);
     data->setNumber("lineNumber", lineNumber);
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createTimeStampData(const String& message)
+PassRefPtr<JSONObject> TimelineRecordFactory::createTimeStampData(const String& message)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setString("message", message);
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createScheduleResourceRequestData(const String& url)
+PassRefPtr<JSONObject> TimelineRecordFactory::createScheduleResourceRequestData(const String& url)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setString("url", url);
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createResourceSendRequestData(const String& requestId, const ResourceRequest& request)
+PassRefPtr<JSONObject> TimelineRecordFactory::createResourceSendRequestData(const String& requestId, const ResourceRequest& request)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setString("requestId", requestId);
     data->setString("url", request.url().string());
     data->setString("requestMethod", request.httpMethod());
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createResourceReceiveResponseData(const String& requestId, const ResourceResponse& response)
+PassRefPtr<JSONObject> TimelineRecordFactory::createResourceReceiveResponseData(const String& requestId, const ResourceResponse& response)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setString("requestId", requestId);
     data->setNumber("statusCode", response.httpStatusCode());
     data->setString("mimeType", response.mimeType());
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createResourceFinishData(const String& requestId, bool didFail, double finishTime)
+PassRefPtr<JSONObject> TimelineRecordFactory::createResourceFinishData(const String& requestId, bool didFail, double finishTime)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setString("requestId", requestId);
     data->setBoolean("didFail", didFail);
     if (finishTime)
@@ -168,61 +168,61 @@
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createReceiveResourceData(const String& requestId, int length)
+PassRefPtr<JSONObject> TimelineRecordFactory::createReceiveResourceData(const String& requestId, int length)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setString("requestId", requestId);
     data->setNumber("encodedDataLength", length);
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createLayoutData(unsigned dirtyObjects, unsigned totalObjects, bool partialLayout)
+PassRefPtr<JSONObject> TimelineRecordFactory::createLayoutData(unsigned dirtyObjects, unsigned totalObjects, bool partialLayout)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setNumber("dirtyObjects", dirtyObjects);
     data->setNumber("totalObjects", totalObjects);
     data->setBoolean("partialLayout", partialLayout);
     return data.release();
 }
     
-PassRefPtr<InspectorObject> TimelineRecordFactory::createDecodeImageData(const String& imageType)
+PassRefPtr<JSONObject> TimelineRecordFactory::createDecodeImageData(const String& imageType)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setString("imageType", imageType);
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createResizeImageData(bool shouldCache)
+PassRefPtr<JSONObject> TimelineRecordFactory::createResizeImageData(bool shouldCache)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setBoolean("cached", shouldCache);
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createMarkData(bool isMainFrame)
+PassRefPtr<JSONObject> TimelineRecordFactory::createMarkData(bool isMainFrame)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setBoolean("isMainFrame", isMainFrame);
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createParseHTMLData(unsigned startLine)
+PassRefPtr<JSONObject> TimelineRecordFactory::createParseHTMLData(unsigned startLine)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setNumber("startLine", startLine);
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createAnimationFrameData(int callbackId)
+PassRefPtr<JSONObject> TimelineRecordFactory::createAnimationFrameData(int callbackId)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     data->setNumber("id", callbackId);
     return data.release();
 }
 
-static PassRefPtr<InspectorArray> createQuad(const FloatQuad& quad)
+static PassRefPtr<JSONArray> createQuad(const FloatQuad& quad)
 {
-    RefPtr<InspectorArray> array = InspectorArray::create();
+    RefPtr<JSONArray> array = JSONArray::create();
     array->pushNumber(quad.p1().x());
     array->pushNumber(quad.p1().y());
     array->pushNumber(quad.p2().x());
@@ -234,29 +234,29 @@
     return array.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createLayerData(long long layerRootNodeId)
+PassRefPtr<JSONObject> TimelineRecordFactory::createLayerData(long long layerRootNodeId)
 {
-    RefPtr<InspectorObject> data = InspectorObject::create();
+    RefPtr<JSONObject> data = JSONObject::create();
     if (layerRootNodeId)
         data->setNumber("layerRootNode", layerRootNodeId);
     return data.release();
 }
 
-PassRefPtr<InspectorObject> TimelineRecordFactory::createPaintData(const FloatQuad& quad, long long layerRootNodeId)
+PassRefPtr<JSONObject> TimelineRecordFactory::createPaintData(const FloatQuad& quad, long long layerRootNodeId)
 {
-    RefPtr<InspectorObject> data = TimelineRecordFactory::createLayerData(layerRootNodeId);
+    RefPtr<JSONObject> data = TimelineRecordFactory::createLayerData(layerRootNodeId);
     data->setArray("clip", createQuad(quad));
     return data.release();
 }
 
-void TimelineRecordFactory::appendLayoutRoot(InspectorObject* data, const FloatQuad& quad, long long rootNodeId)
+void TimelineRecordFactory::appendLayoutRoot(JSONObject* data, const FloatQuad& quad, long long rootNodeId)
 {
     data->setArray("root", createQuad(quad));
     if (rootNodeId)
         data->setNumber("rootNode", rootNodeId);
 }
 
-void TimelineRecordFactory::appendStyleRecalcDetails(InspectorObject* data, unsigned elementCount)
+void TimelineRecordFactory::appendStyleRecalcDetails(JSONObject* data, unsigned elementCount)
 {
     data->setNumber("elementCount", elementCount);
 }
diff --git a/Source/core/inspector/TimelineRecordFactory.h b/Source/core/inspector/TimelineRecordFactory.h
index de97280..9fb244d 100644
--- a/Source/core/inspector/TimelineRecordFactory.h
+++ b/Source/core/inspector/TimelineRecordFactory.h
@@ -31,8 +31,7 @@
 #ifndef TimelineRecordFactory_h
 #define TimelineRecordFactory_h
 
-#include "core/inspector/InspectorValues.h"
-#include "core/platform/graphics/LayoutRect.h"
+#include "core/platform/JSONValues.h"
 #include "weborigin/KURL.h"
 #include "wtf/Forward.h"
 #include "wtf/text/WTFString.h"
@@ -42,67 +41,66 @@
     class Event;
     class FloatQuad;
     class InspectorFrontend;
-    class InspectorObject;
     class IntRect;
     class ResourceRequest;
     class ResourceResponse;
 
     class TimelineRecordFactory {
     public:
-        static PassRefPtr<InspectorObject> createGenericRecord(double startTime, int maxCallStackDepth, const String& type);
-        static PassRefPtr<InspectorObject> createBackgroundRecord(double startTime, const String& thread);
+        static PassRefPtr<JSONObject> createGenericRecord(double startTime, int maxCallStackDepth, const String& type);
+        static PassRefPtr<JSONObject> createBackgroundRecord(double startTime, const String& thread);
 
-        static PassRefPtr<InspectorObject> createGCEventData(const size_t usedHeapSizeDelta);
+        static PassRefPtr<JSONObject> createGCEventData(const size_t usedHeapSizeDelta);
 
-        static PassRefPtr<InspectorObject> createFunctionCallData(const String& scriptName, int scriptLine);
+        static PassRefPtr<JSONObject> createFunctionCallData(const String& scriptName, int scriptLine);
 
-        static PassRefPtr<InspectorObject> createEventDispatchData(const Event&);
+        static PassRefPtr<JSONObject> createEventDispatchData(const Event&);
 
-        static PassRefPtr<InspectorObject> createGenericTimerData(int timerId);
+        static PassRefPtr<JSONObject> createGenericTimerData(int timerId);
 
-        static PassRefPtr<InspectorObject> createTimerInstallData(int timerId, int timeout, bool singleShot);
+        static PassRefPtr<JSONObject> createTimerInstallData(int timerId, int timeout, bool singleShot);
 
-        static PassRefPtr<InspectorObject> createXHRReadyStateChangeData(const String& url, int readyState);
+        static PassRefPtr<JSONObject> createXHRReadyStateChangeData(const String& url, int readyState);
 
-        static PassRefPtr<InspectorObject> createXHRLoadData(const String& url);
+        static PassRefPtr<JSONObject> createXHRLoadData(const String& url);
 
-        static PassRefPtr<InspectorObject> createEvaluateScriptData(const String&, double lineNumber);
+        static PassRefPtr<JSONObject> createEvaluateScriptData(const String&, double lineNumber);
 
-        static PassRefPtr<InspectorObject> createTimeStampData(const String&);
+        static PassRefPtr<JSONObject> createTimeStampData(const String&);
 
-        static PassRefPtr<InspectorObject> createResourceSendRequestData(const String& requestId, const ResourceRequest&);
+        static PassRefPtr<JSONObject> createResourceSendRequestData(const String& requestId, const ResourceRequest&);
 
-        static PassRefPtr<InspectorObject> createScheduleResourceRequestData(const String&);
+        static PassRefPtr<JSONObject> createScheduleResourceRequestData(const String&);
 
-        static PassRefPtr<InspectorObject> createResourceReceiveResponseData(const String& requestId, const ResourceResponse&);
+        static PassRefPtr<JSONObject> createResourceReceiveResponseData(const String& requestId, const ResourceResponse&);
 
-        static PassRefPtr<InspectorObject> createReceiveResourceData(const String& requestId, int length);
+        static PassRefPtr<JSONObject> createReceiveResourceData(const String& requestId, int length);
 
-        static PassRefPtr<InspectorObject> createResourceFinishData(const String& requestId, bool didFail, double finishTime);
+        static PassRefPtr<JSONObject> createResourceFinishData(const String& requestId, bool didFail, double finishTime);
 
-        static PassRefPtr<InspectorObject> createLayoutData(unsigned dirtyObjects, unsigned totalObjects, bool partialLayout);
+        static PassRefPtr<JSONObject> createLayoutData(unsigned dirtyObjects, unsigned totalObjects, bool partialLayout);
 
-        static PassRefPtr<InspectorObject> createDecodeImageData(const String& imageType);
+        static PassRefPtr<JSONObject> createDecodeImageData(const String& imageType);
 
-        static PassRefPtr<InspectorObject> createResizeImageData(bool shouldCache);
+        static PassRefPtr<JSONObject> createResizeImageData(bool shouldCache);
 
-        static PassRefPtr<InspectorObject> createMarkData(bool isMainFrame);
+        static PassRefPtr<JSONObject> createMarkData(bool isMainFrame);
 
-        static PassRefPtr<InspectorObject> createParseHTMLData(unsigned startLine);
+        static PassRefPtr<JSONObject> createParseHTMLData(unsigned startLine);
 
-        static PassRefPtr<InspectorObject> createAnimationFrameData(int callbackId);
+        static PassRefPtr<JSONObject> createAnimationFrameData(int callbackId);
 
-        static PassRefPtr<InspectorObject> createLayerData(long long layerRootNodeId);
+        static PassRefPtr<JSONObject> createLayerData(long long layerRootNodeId);
 
-        static PassRefPtr<InspectorObject> createPaintData(const FloatQuad&, long long layerRootNodeId);
+        static PassRefPtr<JSONObject> createPaintData(const FloatQuad&, long long layerRootNodeId);
 
-        static void appendLayoutRoot(InspectorObject* data, const FloatQuad&, long long rootNodeId);
+        static void appendLayoutRoot(JSONObject* data, const FloatQuad&, long long rootNodeId);
 
-        static void appendStyleRecalcDetails(InspectorObject* data, unsigned elementCount);
+        static void appendStyleRecalcDetails(JSONObject* data, unsigned elementCount);
 
-        static inline PassRefPtr<InspectorObject> createWebSocketCreateData(unsigned long identifier, const KURL& url, const String& protocol)
+        static inline PassRefPtr<JSONObject> createWebSocketCreateData(unsigned long identifier, const KURL& url, const String& protocol)
         {
-            RefPtr<InspectorObject> data = InspectorObject::create();
+            RefPtr<JSONObject> data = JSONObject::create();
             data->setNumber("identifier", identifier);
             data->setString("url", url.string());
             if (!protocol.isNull())
@@ -110,9 +108,9 @@
             return data.release();
         }
 
-        static inline PassRefPtr<InspectorObject> createGenericWebSocketData(unsigned long identifier)
+        static inline PassRefPtr<JSONObject> createGenericWebSocketData(unsigned long identifier)
         {
-            RefPtr<InspectorObject> data = InspectorObject::create();
+            RefPtr<JSONObject> data = JSONObject::create();
             data->setNumber("identifier", identifier);
             return data.release();
         }
diff --git a/Source/core/inspector/TimelineTraceEventProcessor.cpp b/Source/core/inspector/TimelineTraceEventProcessor.cpp
index 70e842f..a2323e0 100644
--- a/Source/core/inspector/TimelineTraceEventProcessor.cpp
+++ b/Source/core/inspector/TimelineTraceEventProcessor.cpp
@@ -35,10 +35,9 @@
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/inspector/TimelineRecordFactory.h"
 
-#include <wtf/CurrentTime.h>
-#include <wtf/MainThread.h>
-#include <wtf/ThreadSpecific.h>
-#include <wtf/Vector.h>
+#include "wtf/CurrentTime.h"
+#include "wtf/MainThread.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -107,7 +106,7 @@
 {
 }
 
-void TimelineRecordStack::addScopedRecord(PassRefPtr<InspectorObject> record)
+void TimelineRecordStack::addScopedRecord(PassRefPtr<JSONObject> record)
 {
     m_stack.append(Entry(record));
 }
@@ -124,7 +123,7 @@
     addInstantRecord(last.record);
 }
 
-void TimelineRecordStack::addInstantRecord(PassRefPtr<InspectorObject> record)
+void TimelineRecordStack::addInstantRecord(PassRefPtr<JSONObject> record)
 {
     if (m_stack.isEmpty())
         send(record);
@@ -140,7 +139,7 @@
 }
 #endif
 
-void TimelineRecordStack::send(PassRefPtr<InspectorObject> record)
+void TimelineRecordStack::send(PassRefPtr<JSONObject> record)
 {
     InspectorTimelineAgent* timelineAgent = m_timelineAgent.get();
     if (!timelineAgent)
@@ -261,7 +260,7 @@
         return;
     unsigned long long layerId = event.asUInt(InstrumentationEventArguments::LayerId);
     ASSERT(layerId);
-    RefPtr<InspectorObject> record = createRecord(event, TimelineRecordType::Rasterize);
+    RefPtr<JSONObject> record = createRecord(event, TimelineRecordType::Rasterize);
     record->setObject("data", TimelineRecordFactory::createLayerData(m_layerToNodeMap.get(layerId)));
     state.recordStack.addScopedRecord(record.release());
 }
@@ -340,19 +339,19 @@
     m_layerToNodeMap.set(m_layerId, nodeId);
     InspectorTimelineAgent* timelineAgent = m_timelineAgent.get();
     if (timelineAgent && paintSetupStart) {
-        RefPtr<InspectorObject> paintSetupRecord = TimelineRecordFactory::createGenericRecord(paintSetupStart, 0, TimelineRecordType::PaintSetup);
+        RefPtr<JSONObject> paintSetupRecord = TimelineRecordFactory::createGenericRecord(paintSetupStart, 0, TimelineRecordType::PaintSetup);
         paintSetupRecord->setNumber("endTime", m_paintSetupEnd);
         paintSetupRecord->setObject("data", TimelineRecordFactory::createLayerData(nodeId));
         timelineAgent->addRecordToTimeline(paintSetupRecord);
     }
 }
 
-PassRefPtr<InspectorObject> TimelineTraceEventProcessor::createRecord(const TraceEvent& event, const String& recordType, PassRefPtr<InspectorObject> data)
+PassRefPtr<JSONObject> TimelineTraceEventProcessor::createRecord(const TraceEvent& event, const String& recordType, PassRefPtr<JSONObject> data)
 {
     double startTime = m_timeConverter.fromMonotonicallyIncreasingTime(event.timestamp());
-    RefPtr<InspectorObject> record = TimelineRecordFactory::createBackgroundRecord(startTime, String::number(event.threadIdentifier()));
+    RefPtr<JSONObject> record = TimelineRecordFactory::createBackgroundRecord(startTime, String::number(event.threadIdentifier()));
     record->setString("type", recordType);
-    record->setObject("data", data ? data : InspectorObject::create());
+    record->setObject("data", data ? data : JSONObject::create());
     return record.release();
 }
 
diff --git a/Source/core/inspector/TimelineTraceEventProcessor.h b/Source/core/inspector/TimelineTraceEventProcessor.h
index e2eb733..48edc09 100644
--- a/Source/core/inspector/TimelineTraceEventProcessor.h
+++ b/Source/core/inspector/TimelineTraceEventProcessor.h
@@ -33,15 +33,12 @@
 
 
 #include "core/inspector/InspectorTimelineAgent.h"
-#include "core/inspector/InspectorValues.h"
-
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Threading.h>
-#include <wtf/Vector.h>
-#include <wtf/WeakPtr.h>
+#include "core/platform/JSONValues.h"
+#include "wtf/HashMap.h"
+#include "wtf/Threading.h"
+#include "wtf/Vector.h"
+#include "wtf/WeakPtr.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -52,30 +49,30 @@
 class TimelineRecordStack {
 private:
     struct Entry {
-        Entry(PassRefPtr<InspectorObject> record)
+        Entry(PassRefPtr<JSONObject> record)
             : record(record)
-            , children(InspectorArray::create())
+            , children(JSONArray::create())
         {
         }
 
-        RefPtr<InspectorObject> record;
-        RefPtr<InspectorArray> children;
+        RefPtr<JSONObject> record;
+        RefPtr<JSONArray> children;
     };
 
 public:
     TimelineRecordStack() { }
     TimelineRecordStack(WeakPtr<InspectorTimelineAgent>);
 
-    void addScopedRecord(PassRefPtr<InspectorObject> record);
+    void addScopedRecord(PassRefPtr<JSONObject> record);
     void closeScopedRecord(double endTime);
-    void addInstantRecord(PassRefPtr<InspectorObject> record);
+    void addInstantRecord(PassRefPtr<JSONObject> record);
 
 #ifndef NDEBUG
     bool isOpenRecordOfType(const String& type);
 #endif
 
 private:
-    void send(PassRefPtr<InspectorObject>);
+    void send(PassRefPtr<JSONObject>);
 
     WeakPtr<InspectorTimelineAgent> m_timelineAgent;
     Vector<Entry> m_stack;
@@ -226,7 +223,7 @@
     void leaveLayerTask(TimelineThreadState&);
 
     void processBackgroundEvents();
-    PassRefPtr<InspectorObject> createRecord(const TraceEvent&, const String& recordType, PassRefPtr<InspectorObject> data = 0);
+    PassRefPtr<JSONObject> createRecord(const TraceEvent&, const String& recordType, PassRefPtr<JSONObject> data = 0);
 
     void registerHandler(const char* name, TraceEventPhase, TraceEventHandler);
 
diff --git a/Source/core/inspector/WorkerDebuggerAgent.cpp b/Source/core/inspector/WorkerDebuggerAgent.cpp
index 4e9cdd7..b30b39a 100644
--- a/Source/core/inspector/WorkerDebuggerAgent.cpp
+++ b/Source/core/inspector/WorkerDebuggerAgent.cpp
@@ -33,7 +33,7 @@
 #include "core/inspector/WorkerDebuggerAgent.h"
 
 #include "bindings/v8/ScriptDebugServer.h"
-#include "core/workers/WorkerContext.h"
+#include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerThread.h"
 #include <wtf/MessageQueue.h>
 
@@ -58,46 +58,46 @@
 
 class RunInspectorCommandsTask : public ScriptDebugServer::Task {
 public:
-    RunInspectorCommandsTask(WorkerThread* thread, WorkerContext* workerContext)
+    RunInspectorCommandsTask(WorkerThread* thread, WorkerGlobalScope* workerGlobalScope)
         : m_thread(thread)
-        , m_workerContext(workerContext) { }
+        , m_workerGlobalScope(workerGlobalScope) { }
     virtual ~RunInspectorCommandsTask() { }
     virtual void run()
     {
-        // Process all queued debugger commands. It is safe to use m_workerContext here
+        // Process all queued debugger commands. It is safe to use m_workerGlobalScope here
         // because it is alive if RunWorkerLoop is not terminated, otherwise it will
         // just be ignored. WorkerThread is certainly alive if this task is being executed.
-        while (MessageQueueMessageReceived == m_thread->runLoop().runInMode(m_workerContext, WorkerDebuggerAgent::debuggerTaskMode, WorkerRunLoop::DontWaitForMessage)) { }
+        while (MessageQueueMessageReceived == m_thread->runLoop().runInMode(m_workerGlobalScope, WorkerDebuggerAgent::debuggerTaskMode, WorkerRunLoop::DontWaitForMessage)) { }
     }
 
 private:
     WorkerThread* m_thread;
-    WorkerContext* m_workerContext;
+    WorkerGlobalScope* m_workerGlobalScope;
 };
 
 } // namespace
 
 const char* WorkerDebuggerAgent::debuggerTaskMode = "debugger";
 
-PassOwnPtr<WorkerDebuggerAgent> WorkerDebuggerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, WorkerScriptDebugServer* scriptDebugServer, WorkerContext* inspectedWorkerContext, InjectedScriptManager* injectedScriptManager)
+PassOwnPtr<WorkerDebuggerAgent> WorkerDebuggerAgent::create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, WorkerScriptDebugServer* scriptDebugServer, WorkerGlobalScope* inspectedWorkerGlobalScope, InjectedScriptManager* injectedScriptManager)
 {
-    return adoptPtr(new WorkerDebuggerAgent(instrumentingAgents, inspectorState, scriptDebugServer, inspectedWorkerContext, injectedScriptManager));
+    return adoptPtr(new WorkerDebuggerAgent(instrumentingAgents, inspectorState, scriptDebugServer, inspectedWorkerGlobalScope, injectedScriptManager));
 }
 
-WorkerDebuggerAgent::WorkerDebuggerAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, WorkerScriptDebugServer* scriptDebugServer, WorkerContext* inspectedWorkerContext, InjectedScriptManager* injectedScriptManager)
+WorkerDebuggerAgent::WorkerDebuggerAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* inspectorState, WorkerScriptDebugServer* scriptDebugServer, WorkerGlobalScope* inspectedWorkerGlobalScope, InjectedScriptManager* injectedScriptManager)
     : InspectorDebuggerAgent(instrumentingAgents, inspectorState, injectedScriptManager)
     , m_scriptDebugServer(scriptDebugServer)
-    , m_inspectedWorkerContext(inspectedWorkerContext)
+    , m_inspectedWorkerGlobalScope(inspectedWorkerGlobalScope)
 {
     MutexLocker lock(workerDebuggerAgentsMutex());
-    workerDebuggerAgents().set(inspectedWorkerContext->thread(), this);
+    workerDebuggerAgents().set(inspectedWorkerGlobalScope->thread(), this);
 }
 
 WorkerDebuggerAgent::~WorkerDebuggerAgent()
 {
     MutexLocker lock(workerDebuggerAgentsMutex());
-    ASSERT(workerDebuggerAgents().contains(m_inspectedWorkerContext->thread()));
-    workerDebuggerAgents().remove(m_inspectedWorkerContext->thread());
+    ASSERT(workerDebuggerAgents().contains(m_inspectedWorkerGlobalScope->thread()));
+    workerDebuggerAgents().remove(m_inspectedWorkerGlobalScope->thread());
 }
 
 void WorkerDebuggerAgent::interruptAndDispatchInspectorCommands(WorkerThread* thread)
@@ -105,7 +105,7 @@
     MutexLocker lock(workerDebuggerAgentsMutex());
     WorkerDebuggerAgent* agent = workerDebuggerAgents().get(thread);
     if (agent)
-        agent->m_scriptDebugServer->interruptAndRunTask(adoptPtr(new RunInspectorCommandsTask(thread, agent->m_inspectedWorkerContext)));
+        agent->m_scriptDebugServer->interruptAndRunTask(adoptPtr(new RunInspectorCommandsTask(thread, agent->m_inspectedWorkerGlobalScope)));
 }
 
 void WorkerDebuggerAgent::startListeningScriptDebugServer()
@@ -129,7 +129,7 @@
         *error = "Execution context id is not supported for workers as there is only one execution context.";
         return InjectedScript();
     }
-    ScriptState* scriptState = scriptStateFromWorkerContext(m_inspectedWorkerContext);
+    ScriptState* scriptState = scriptStateFromWorkerGlobalScope(m_inspectedWorkerGlobalScope);
     return injectedScriptManager()->injectedScriptFor(scriptState);
 }
 
@@ -145,7 +145,7 @@
 
 void WorkerDebuggerAgent::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL)
 {
-    ScriptExecutionContext* context = m_inspectedWorkerContext;
+    ScriptExecutionContext* context = m_inspectedWorkerGlobalScope;
     context->addConsoleMessage(source, level, message, sourceURL, 0);
 }
 
diff --git a/Source/core/inspector/WorkerDebuggerAgent.h b/Source/core/inspector/WorkerDebuggerAgent.h
index b766d85..f51b390 100644
--- a/Source/core/inspector/WorkerDebuggerAgent.h
+++ b/Source/core/inspector/WorkerDebuggerAgent.h
@@ -36,21 +36,21 @@
 
 namespace WebCore {
 
-class WorkerContext;
+class WorkerGlobalScope;
 class WorkerThread;
 
 class WorkerDebuggerAgent : public InspectorDebuggerAgent {
     WTF_MAKE_NONCOPYABLE(WorkerDebuggerAgent);
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<WorkerDebuggerAgent> create(InstrumentingAgents*, InspectorCompositeState*, WorkerScriptDebugServer*, WorkerContext*, InjectedScriptManager*);
+    static PassOwnPtr<WorkerDebuggerAgent> create(InstrumentingAgents*, InspectorCompositeState*, WorkerScriptDebugServer*, WorkerGlobalScope*, InjectedScriptManager*);
     virtual ~WorkerDebuggerAgent();
 
     static const char* debuggerTaskMode;
     static void interruptAndDispatchInspectorCommands(WorkerThread*);
 
 private:
-    WorkerDebuggerAgent(InstrumentingAgents*, InspectorCompositeState*, WorkerScriptDebugServer*, WorkerContext*, InjectedScriptManager*);
+    WorkerDebuggerAgent(InstrumentingAgents*, InspectorCompositeState*, WorkerScriptDebugServer*, WorkerGlobalScope*, InjectedScriptManager*);
 
     virtual void startListeningScriptDebugServer();
     virtual void stopListeningScriptDebugServer();
@@ -61,7 +61,7 @@
     virtual void addConsoleMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL);
 
     WorkerScriptDebugServer* m_scriptDebugServer;
-    WorkerContext* m_inspectedWorkerContext;
+    WorkerGlobalScope* m_inspectedWorkerGlobalScope;
 };
 
 } // namespace WebCore
diff --git a/Source/core/inspector/WorkerInspectorController.cpp b/Source/core/inspector/WorkerInspectorController.cpp
index cf84183..397b443 100644
--- a/Source/core/inspector/WorkerInspectorController.cpp
+++ b/Source/core/inspector/WorkerInspectorController.cpp
@@ -47,7 +47,7 @@
 #include "core/inspector/WorkerConsoleAgent.h"
 #include "core/inspector/WorkerDebuggerAgent.h"
 #include "core/inspector/WorkerRuntimeAgent.h"
-#include "core/workers/WorkerContext.h"
+#include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerReportingProxy.h"
 #include "core/workers/WorkerThread.h"
 #include <wtf/PassOwnPtr.h>
@@ -59,46 +59,46 @@
 class PageInspectorProxy : public InspectorFrontendChannel {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    explicit PageInspectorProxy(WorkerContext* workerContext) : m_workerContext(workerContext) { }
+    explicit PageInspectorProxy(WorkerGlobalScope* workerGlobalScope) : m_workerGlobalScope(workerGlobalScope) { }
     virtual ~PageInspectorProxy() { }
 private:
     virtual bool sendMessageToFrontend(const String& message)
     {
-        m_workerContext->thread()->workerReportingProxy().postMessageToPageInspector(message);
+        m_workerGlobalScope->thread()->workerReportingProxy().postMessageToPageInspector(message);
         return true;
     }
-    WorkerContext* m_workerContext;
+    WorkerGlobalScope* m_workerGlobalScope;
 };
 
 class WorkerStateClient : public InspectorStateClient {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    WorkerStateClient(WorkerContext* context) : m_workerContext(context) { }
+    WorkerStateClient(WorkerGlobalScope* context) : m_workerGlobalScope(context) { }
     virtual ~WorkerStateClient() { }
 
 private:
     virtual void updateInspectorStateCookie(const String& cookie)
     {
-        m_workerContext->thread()->workerReportingProxy().updateInspectorStateCookie(cookie);
+        m_workerGlobalScope->thread()->workerReportingProxy().updateInspectorStateCookie(cookie);
     }
 
-    WorkerContext* m_workerContext;
+    WorkerGlobalScope* m_workerGlobalScope;
 };
 
 }
 
-WorkerInspectorController::WorkerInspectorController(WorkerContext* workerContext)
-    : m_workerContext(workerContext)
-    , m_stateClient(adoptPtr(new WorkerStateClient(workerContext)))
+WorkerInspectorController::WorkerInspectorController(WorkerGlobalScope* workerGlobalScope)
+    : m_workerGlobalScope(workerGlobalScope)
+    , m_stateClient(adoptPtr(new WorkerStateClient(workerGlobalScope)))
     , m_state(adoptPtr(new InspectorCompositeState(m_stateClient.get())))
     , m_instrumentingAgents(InstrumentingAgents::create())
     , m_injectedScriptManager(InjectedScriptManager::createForWorker())
-    , m_debugServer(adoptPtr(new WorkerScriptDebugServer(workerContext, WorkerDebuggerAgent::debuggerTaskMode)))
+    , m_debugServer(adoptPtr(new WorkerScriptDebugServer(workerGlobalScope, WorkerDebuggerAgent::debuggerTaskMode)))
 {
-    m_agents.append(WorkerRuntimeAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), m_debugServer.get(), workerContext));
+    m_agents.append(WorkerRuntimeAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get(), m_debugServer.get(), workerGlobalScope));
 
     OwnPtr<InspectorConsoleAgent> consoleAgent = WorkerConsoleAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get());
-    m_agents.append(WorkerDebuggerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_debugServer.get(), workerContext, m_injectedScriptManager.get()));
+    m_agents.append(WorkerDebuggerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_debugServer.get(), workerGlobalScope, m_injectedScriptManager.get()));
 
     m_agents.append(InspectorProfilerAgent::create(m_instrumentingAgents.get(), consoleAgent.get(), m_state.get(), m_injectedScriptManager.get()));
     m_agents.append(InspectorHeapProfilerAgent::create(m_instrumentingAgents.get(), m_state.get(), m_injectedScriptManager.get()));
@@ -118,7 +118,7 @@
 {
     ASSERT(!m_frontend);
     m_state->unmute();
-    m_frontendChannel = adoptPtr(new PageInspectorProxy(m_workerContext));
+    m_frontendChannel = adoptPtr(new PageInspectorProxy(m_workerGlobalScope));
     m_frontend = adoptPtr(new InspectorFrontend(m_frontendChannel.get()));
     m_backendDispatcher = InspectorBackendDispatcher::create(m_frontendChannel.get());
     m_agents.registerInDispatcher(m_backendDispatcher.get());
diff --git a/Source/core/inspector/WorkerInspectorController.h b/Source/core/inspector/WorkerInspectorController.h
index aada5b8..4c70063 100644
--- a/Source/core/inspector/WorkerInspectorController.h
+++ b/Source/core/inspector/WorkerInspectorController.h
@@ -47,14 +47,14 @@
 class InspectorState;
 class InspectorStateClient;
 class InstrumentingAgents;
-class WorkerContext;
+class WorkerGlobalScope;
 class WorkerScriptDebugServer;
 
 class WorkerInspectorController {
     WTF_MAKE_NONCOPYABLE(WorkerInspectorController);
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    WorkerInspectorController(WorkerContext*);
+    WorkerInspectorController(WorkerGlobalScope*);
     ~WorkerInspectorController();
 
     bool hasFrontend() const { return m_frontend; }
@@ -65,9 +65,9 @@
     void resume();
 
 private:
-    friend InstrumentingAgents* instrumentationForWorkerContext(WorkerContext*);
+    friend InstrumentingAgents* instrumentationForWorkerGlobalScope(WorkerGlobalScope*);
 
-    WorkerContext* m_workerContext;
+    WorkerGlobalScope* m_workerGlobalScope;
     OwnPtr<InspectorStateClient> m_stateClient;
     OwnPtr<InspectorCompositeState> m_state;
     RefPtr<InstrumentingAgents> m_instrumentingAgents;
diff --git a/Source/core/inspector/WorkerRuntimeAgent.cpp b/Source/core/inspector/WorkerRuntimeAgent.cpp
index 8ddd4b2..d3d0c3f 100644
--- a/Source/core/inspector/WorkerRuntimeAgent.cpp
+++ b/Source/core/inspector/WorkerRuntimeAgent.cpp
@@ -36,15 +36,15 @@
 #include "core/inspector/InjectedScript.h"
 #include "core/inspector/InstrumentingAgents.h"
 #include "core/inspector/WorkerDebuggerAgent.h"
-#include "core/workers/WorkerContext.h"
+#include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerRunLoop.h"
 #include "core/workers/WorkerThread.h"
 
 namespace WebCore {
 
-WorkerRuntimeAgent::WorkerRuntimeAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer, WorkerContext* workerContext)
+WorkerRuntimeAgent::WorkerRuntimeAgent(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer, WorkerGlobalScope* workerGlobalScope)
     : InspectorRuntimeAgent(instrumentingAgents, state, injectedScriptManager, scriptDebugServer)
-    , m_workerContext(workerContext)
+    , m_workerGlobalScope(workerGlobalScope)
     , m_paused(false)
 {
     m_instrumentingAgents->setWorkerRuntimeAgent(this);
@@ -61,7 +61,7 @@
         *error = "Execution context id is not supported for workers as there is only one execution context.";
         return InjectedScript();
     }
-    ScriptState* scriptState = scriptStateFromWorkerContext(m_workerContext);
+    ScriptState* scriptState = scriptStateFromWorkerGlobalScope(m_workerGlobalScope);
     return injectedScriptManager()->injectedScriptFor(scriptState);
 }
 
@@ -80,9 +80,9 @@
     m_paused = false;
 }
 
-void WorkerRuntimeAgent::willEvaluateWorkerScript(WorkerContext* context, int workerThreadStartMode)
+void WorkerRuntimeAgent::willEvaluateWorkerScript(WorkerGlobalScope* context, int workerThreadStartMode)
 {
-    if (workerThreadStartMode != PauseWorkerContextOnStart)
+    if (workerThreadStartMode != PauseWorkerGlobalScopeOnStart)
         return;
 
     m_paused = true;
diff --git a/Source/core/inspector/WorkerRuntimeAgent.h b/Source/core/inspector/WorkerRuntimeAgent.h
index 5ceb747..226c135 100644
--- a/Source/core/inspector/WorkerRuntimeAgent.h
+++ b/Source/core/inspector/WorkerRuntimeAgent.h
@@ -36,11 +36,11 @@
 
 namespace WebCore {
 
-class WorkerContext;
+class WorkerGlobalScope;
 
 class WorkerRuntimeAgent : public InspectorRuntimeAgent {
 public:
-    static PassOwnPtr<WorkerRuntimeAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer, WorkerContext* context)
+    static PassOwnPtr<WorkerRuntimeAgent> create(InstrumentingAgents* instrumentingAgents, InspectorCompositeState* state, InjectedScriptManager* injectedScriptManager, ScriptDebugServer* scriptDebugServer, WorkerGlobalScope* context)
     {
         return adoptPtr(new WorkerRuntimeAgent(instrumentingAgents, state, injectedScriptManager, scriptDebugServer, context));
     }
@@ -49,14 +49,14 @@
     // Protocol commands.
     virtual void run(ErrorString*);
 
-    void willEvaluateWorkerScript(WorkerContext*, int workerThreadStartMode);
+    void willEvaluateWorkerScript(WorkerGlobalScope*, int workerThreadStartMode);
 
 private:
-    WorkerRuntimeAgent(InstrumentingAgents*, InspectorCompositeState*, InjectedScriptManager*, ScriptDebugServer*, WorkerContext*);
+    WorkerRuntimeAgent(InstrumentingAgents*, InspectorCompositeState*, InjectedScriptManager*, ScriptDebugServer*, WorkerGlobalScope*);
     virtual InjectedScript injectedScriptForEval(ErrorString*, const int* executionContextId);
     virtual void muteConsole();
     virtual void unmuteConsole();
-    WorkerContext* m_workerContext;
+    WorkerGlobalScope* m_workerGlobalScope;
     bool m_paused;
 };
 
diff --git a/Source/core/loader/CookieJar.h b/Source/core/loader/CookieJar.h
index a654e84..14b8cc7 100644
--- a/Source/core/loader/CookieJar.h
+++ b/Source/core/loader/CookieJar.h
@@ -26,10 +26,9 @@
 #ifndef CookieJar_h
 #define CookieJar_h
 
-#include <wtf/Forward.h>
-#include <wtf/HashSet.h>
-#include <wtf/Vector.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/Forward.h"
+#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/DocumentLoader.cpp b/Source/core/loader/DocumentLoader.cpp
index 7a6331c..b878158 100644
--- a/Source/core/loader/DocumentLoader.cpp
+++ b/Source/core/loader/DocumentLoader.cpp
@@ -30,26 +30,18 @@
 #include "config.h"
 #include "core/loader/DocumentLoader.h"
 
-#include <wtf/Assertions.h>
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/MemoryInstrumentationHashSet.h>
-#include <wtf/MemoryInstrumentationVector.h>
-#include <wtf/text/CString.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/unicode/Unicode.h>
+#include "core/dom/DOMImplementation.h"
 #include "core/dom/Document.h"
 #include "core/dom/DocumentParser.h"
 #include "core/dom/Event.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include "core/history/HistoryItem.h"
-#include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLFrameOwnerElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/DocumentWriter.h"
-#include "core/loader/FormState.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/loader/ResourceLoader.h"
+#include "core/loader/SinkDocument.h"
 #include "core/loader/TextResourceDecoder.h"
 #include "core/loader/UniqueIdentifier.h"
 #include "core/loader/appcache/ApplicationCacheHost.h"
@@ -66,6 +58,11 @@
 #include "core/platform/Logging.h"
 #include "weborigin/SchemeRegistry.h"
 #include "weborigin/SecurityPolicy.h"
+#include "wtf/Assertions.h"
+#include "wtf/MemoryInstrumentationHashMap.h"
+#include "wtf/MemoryInstrumentationHashSet.h"
+#include "wtf/MemoryInstrumentationVector.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -87,18 +84,21 @@
         loadersCopy[i]->setDefersLoading(defers);
 }
 
+static bool isArchiveMIMEType(const String& mimeType)
+{
+    return mimeType == "multipart/related";
+}
+
 DocumentLoader::DocumentLoader(const ResourceRequest& req, const SubstituteData& substituteData)
     : m_deferMainResourceDataLoad(true)
     , m_frame(0)
     , m_cachedResourceLoader(CachedResourceLoader::create(this))
-    , m_writer(m_frame)
     , m_originalRequest(req)
     , m_substituteData(substituteData)
     , m_originalRequestCopy(req)
     , m_request(req)
     , m_committed(false)
     , m_isStopping(false)
-    , m_gotFirstByte(false)
     , m_isClientRedirect(false)
     , m_wasOnloadHandled(false)
     , m_loadingMainResource(false)
@@ -130,6 +130,7 @@
 
 PassRefPtr<SharedBuffer> DocumentLoader::mainResourceData() const
 {
+    ASSERT(isArchiveMIMEType(m_response.mimeType()));
     if (m_substituteData.isValid())
         return m_substituteData.content()->copy();
     if (m_mainResource)
@@ -201,8 +202,7 @@
 
 void DocumentLoader::setMainDocumentError(const ResourceError& error)
 {
-    m_mainDocumentError = error;    
-    frameLoader()->client()->setMainDocumentError(this, error);
+    m_mainDocumentError = error;
 }
 
 void DocumentLoader::mainReceivedError(const ResourceError& error)
@@ -292,7 +292,6 @@
     if (!m_committed) {
         m_committed = true;
         frameLoader()->commitProvisionalLoad();
-        m_writer.setMIMEType(m_response.mimeType());
     }
 }
 
@@ -338,15 +337,17 @@
     if (!frameLoader())
         return;
 
-    if (!maybeCreateArchive()) {
+    if (isArchiveMIMEType(m_response.mimeType())) {
+        createArchive();
+    } else {
         // If this is an empty document, it will not have actually been created yet. Commit dummy data so that
         // DocumentWriter::begin() gets called and creates the Document.
-        if (!m_gotFirstByte)
+        if (!m_writer)
             commitData(0, 0);
-        frameLoader()->client()->finishedLoading(this);
     }
 
-    m_writer.end();
+    endWriting(m_writer.get());
+
     if (!m_mainDocumentError.isNull())
         return;
     clearMainResourceLoader();
@@ -561,6 +562,9 @@
 
     m_response = response;
 
+    if (isArchiveMIMEType(m_response.mimeType()) && m_mainResource->dataBufferingPolicy() != BufferData)
+        m_mainResource->setDataBufferingPolicy(BufferData);
+
     if (m_identifierForLoadWithoutResourceLoader)
         frameLoader()->notifier()->dispatchDidReceiveResponse(this, m_identifierForLoadWithoutResourceLoader, m_response, 0);
 
@@ -592,27 +596,6 @@
     }
 }
 
-static bool isArchiveMIMEType(const String& mimeType)
-{
-    return mimeType == "multipart/related";
-}
-
-void DocumentLoader::commitLoad(const char* data, int length)
-{
-    // Both unloading the old page and parsing the new page may execute JavaScript which destroys the datasource
-    // by starting a new load, so retain temporarily.
-    RefPtr<Frame> protectFrame(m_frame);
-    RefPtr<DocumentLoader> protectLoader(this);
-
-    commitIfReady();
-    FrameLoader* frameLoader = DocumentLoader::frameLoader();
-    if (!frameLoader)
-        return;
-    if (isArchiveMIMEType(response().mimeType()))
-        return;
-    frameLoader->client()->committedLoad(this, data, length);
-}
-
 ResourceError DocumentLoader::interruptedForPolicyChangeError() const
 {
     return frameLoader()->client()->interruptedForPolicyChangeError(request());
@@ -625,34 +608,37 @@
     cancelMainResourceLoad(error);
 }
 
+void DocumentLoader::ensureWriter()
+{
+    ensureWriter(m_response.mimeType());
+}
+
+void DocumentLoader::ensureWriter(const String& mimeType, const KURL& overridingURL)
+{
+    if (m_writer)
+        return;
+
+    String encoding = overrideEncoding().isNull() ? response().textEncodingName().impl() : overrideEncoding();
+    bool userChosen = !overrideEncoding().isNull();
+    m_writer = createWriterFor(m_frame, 0, documentURL(), mimeType, encoding, false, false);
+    m_writer->setDocumentWasLoadedAsPartOfNavigation();
+
+    if (frameLoader()->stateMachine()->creatingInitialEmptyDocument())
+        return;
+
+    // This should be set before receivedFirstData().
+    if (!overridingURL.isEmpty())
+        m_frame->document()->setBaseURLOverride(overridingURL);
+
+    // Call receivedFirstData() exactly once per load.
+    frameLoader()->receivedFirstData();
+}
+
 void DocumentLoader::commitData(const char* bytes, size_t length)
 {
-    if (!m_gotFirstByte) {
-        m_gotFirstByte = true;
-        m_writer.begin(documentURL(), false);
-        m_writer.setDocumentWasLoadedAsPartOfNavigation();
-
-        if (frameLoader()->stateMachine()->creatingInitialEmptyDocument())
-            return;
-        
-        // The origin is the MHTML file, we need to set the base URL to the document encoded in the MHTML so
-        // relative URLs are resolved properly.
-        if (m_archive)
-            m_frame->document()->setBaseURLOverride(m_archive->mainResource()->url());
-
-        // Call receivedFirstData() exactly once per load.
-        frameLoader()->receivedFirstData();
-
-        bool userChosen = true;
-        String encoding = overrideEncoding();
-        if (encoding.isNull()) {
-            userChosen = false;
-            encoding = response().textEncodingName();
-        }
-        m_writer.setEncoding(encoding, userChosen);
-    }
+    ensureWriter();
     ASSERT(m_frame->document()->parsing());
-    m_writer.addData(bytes, length);
+    m_writer->addData(bytes, length);
 }
 
 void DocumentLoader::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
@@ -683,13 +669,29 @@
     ASSERT(!m_response.isNull());
     ASSERT(!mainResourceLoader() || !mainResourceLoader()->defersLoading());
 
+    // Both unloading the old page and parsing the new page may execute JavaScript which destroys the datasource
+    // by starting a new load, so retain temporarily.
+    RefPtr<Frame> protectFrame(m_frame);
+    RefPtr<DocumentLoader> protectLoader(this);
+
     if (m_identifierForLoadWithoutResourceLoader)
         frameLoader()->notifier()->dispatchDidReceiveData(this, m_identifierForLoadWithoutResourceLoader, data, length, -1);
 
     m_applicationCacheHost->mainResourceDataReceived(data, length);
     m_timeOfLastDataReceived = monotonicallyIncreasingTime();
 
-    commitLoad(data, length);
+    commitIfReady();
+    if (!frameLoader())
+        return;
+    if (isArchiveMIMEType(response().mimeType()))
+        return;
+    frameLoader()->client()->didReceiveDocumentData(data, length);
+    commitData(data, length);
+
+    // If we are sending data to MediaDocument, we should stop here
+    // and cancel the request.
+    if (m_frame->document()->isMediaDocument())
+        cancelMainResourceLoad(frameLoader()->cancelledError(m_request));
 }
 
 void DocumentLoader::checkLoadComplete()
@@ -707,8 +709,8 @@
     if (m_frame == frame)
         return;
     ASSERT(frame && !m_frame);
+    ASSERT(!m_writer);
     m_frame = frame;
-    m_writer.setFrame(frame);
 }
 
 void DocumentLoader::detachFromFrame()
@@ -759,22 +761,19 @@
     return frameLoader()->subframeIsLoading();
 }
 
-bool DocumentLoader::maybeCreateArchive()
+void DocumentLoader::createArchive()
 {
-    // Give the archive machinery a crack at this document. If the MIME type is not an archive type, it will return 0.
-    if (!isArchiveMIMEType(m_response.mimeType()))
-        return false;
-
     m_archive = MHTMLArchive::create(m_response.url(), mainResourceData().get());
     ASSERT(m_archive);
     
     addAllArchiveResources(m_archive.get());
     ArchiveResource* mainResource = m_archive->mainResource();
-    m_writer.setMIMEType(mainResource->mimeType());
-    
-    ASSERT(m_frame->document());
+
+    // The origin is the MHTML file, we need to set the base URL to the document encoded in the MHTML so
+    // relative URLs are resolved properly.
+    ensureWriter(mainResource->mimeType(), m_archive->mainResource()->url());
+
     commitData(mainResource->data()->data(), mainResource->data()->size());
-    return true;
 }
 
 void DocumentLoader::addAllArchiveResources(MHTMLArchive* archive)
@@ -887,12 +886,6 @@
     setAllDefersLoading(m_resourceLoaders, defers);
 }
 
-void DocumentLoader::setMainResourceDataBufferingPolicy(DataBufferingPolicy dataBufferingPolicy)
-{
-    if (m_mainResource)
-        m_mainResource->setDataBufferingPolicy(dataBufferingPolicy);
-}
-
 void DocumentLoader::stopLoadingSubresources()
 {
     cancelAll(m_resourceLoaders);
@@ -903,9 +896,9 @@
     // The main resource's underlying ResourceLoader will ask to be added here.
     // It is much simpler to handle special casing of main resource loads if we don't
     // let it be added. In the main resource load case, mainResourceLoader()
-    // will still be null at this point, but m_gotFirstByte should be false here if and only
+    // will still be null at this point, but document() should be zero here if and only
     // if we are just starting the main resource load.
-    if (!m_gotFirstByte)
+    if (!document())
         return;
     ASSERT(!m_resourceLoaders.contains(loader));
     ASSERT(!mainResourceLoader() || mainResourceLoader() != loader);
@@ -968,7 +961,7 @@
 
     ResourceRequest request(m_request);
     DEFINE_STATIC_LOCAL(ResourceLoaderOptions, mainResourceLoadOptions,
-        (SendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck, CheckContentSecurityPolicy));
+        (SendCallbacks, SniffContent, DoNotBufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck, CheckContentSecurityPolicy, UseDefaultOriginRestrictionsForType));
     CachedResourceRequest cachedResourceRequest(request, cachedResourceRequestInitiators().document, mainResourceLoadOptions);
     m_mainResource = m_cachedResourceLoader->requestMainResource(cachedResourceRequest);
     if (!m_mainResource) {
@@ -1019,4 +1012,73 @@
     applicationCacheHost()->stopDeferringEvents();
 }
 
+DocumentWriter* DocumentLoader::beginWriting(const String& mimeType, const String& encoding, const KURL& url)
+{
+    m_writer = createWriterFor(m_frame, 0, url, mimeType, encoding, false, true);
+    return m_writer.get();
+}
+
+void DocumentLoader::endWriting(DocumentWriter* writer)
+{
+    ASSERT_UNUSED(writer, m_writer == writer);
+    m_writer->end();
+    m_writer.clear();
+}
+
+
+PassRefPtr<DocumentWriter> DocumentLoader::createWriterFor(Frame* frame, const Document* ownerDocument, const KURL& url, const String& mimeType, const String& encoding, bool userChosen, bool dispatch)
+{
+    // Create a new document before clearing the frame, because it may need to
+    // inherit an aliased security context.
+    RefPtr<Document> document = DOMImplementation::createDocument(mimeType, frame, url, frame->inViewSourceMode());
+    if (document->isPluginDocument() && document->isSandboxed(SandboxPlugins))
+        document = SinkDocument::create(frame, url);
+    bool shouldReuseDefaultView = frame->loader()->stateMachine()->isDisplayingInitialEmptyDocument() && frame->document()->isSecureTransitionTo(url);
+
+    RefPtr<DOMWindow> originalDOMWindow;
+    if (shouldReuseDefaultView)
+        originalDOMWindow = frame->domWindow();
+    frame->loader()->clear(!shouldReuseDefaultView, !shouldReuseDefaultView);
+
+    if (!shouldReuseDefaultView) {
+        frame->setDOMWindow(DOMWindow::create(frame));
+    } else {
+        // Note that the old Document is still attached to the DOMWindow; the
+        // setDocument() call below will detach the old Document.
+        ASSERT(originalDOMWindow);
+        frame->setDOMWindow(originalDOMWindow);
+    }
+
+    frame->loader()->setOutgoingReferrer(url);
+    frame->domWindow()->setDocument(document);
+
+    if (ownerDocument) {
+        document->setCookieURL(ownerDocument->cookieURL());
+        document->setSecurityOrigin(ownerDocument->securityOrigin());
+    }
+
+    frame->loader()->didBeginDocument(dispatch);
+
+    return DocumentWriter::create(document.get(), mimeType, encoding, userChosen);
+}
+
+String DocumentLoader::mimeType() const
+{
+    if (m_writer)
+        return m_writer->mimeType();
+    return m_response.mimeType();
+}
+
+// This is only called by ScriptController::executeScriptIfJavaScriptURL
+// and always contains the result of evaluating a javascript: url.
+// This is the <iframe src="javascript:'html'"> case.
+void DocumentLoader::replaceDocument(const String& source, Document* ownerDocument)
+{
+    m_frame->loader()->stopAllLoaders();
+    m_writer = createWriterFor(m_frame, ownerDocument, m_frame->document()->url(), mimeType(), m_writer ? m_writer->encoding() : "",  m_writer ? m_writer->encodingWasChosenByUser() : false, true);
+    if (!source.isNull())
+        m_writer->appendReplacingData(source);
+    endWriting(m_writer.get());
+}
+
 } // namespace WebCore
diff --git a/Source/core/loader/DocumentLoader.h b/Source/core/loader/DocumentLoader.h
index 48d0cce..18f3151 100644
--- a/Source/core/loader/DocumentLoader.h
+++ b/Source/core/loader/DocumentLoader.h
@@ -42,9 +42,8 @@
 #include "core/platform/network/ResourceRequest.h"
 #include "core/platform/network/ResourceResponse.h"
 #include "core/platform/text/StringWithDirection.h"
-#include <wtf/HashSet.h>
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/HashSet.h"
+#include "wtf/RefPtr.h"
 
 namespace WTF {
 class SchedulePair;
@@ -81,11 +80,14 @@
         void detachFromFrame();
 
         FrameLoader* frameLoader() const;
-        PassRefPtr<SharedBuffer> mainResourceData() const;
 
         unsigned long mainResourceIdentifier() const;
-        
-        DocumentWriter* writer() const { return &m_writer; }
+
+        void replaceDocument(const String& source, Document*);
+        DocumentWriter* beginWriting(const String& mimeType, const String& encoding, const KURL& = KURL());
+        void endWriting(DocumentWriter*);
+
+        String mimeType() const;
 
         const ResourceRequest& originalRequest() const;
         const ResourceRequest& originalRequestCopy() const;
@@ -134,7 +136,6 @@
         KURL urlForHistory() const;
         
         void setDefersLoading(bool);
-        void setMainResourceDataBufferingPolicy(DataBufferingPolicy);
 
         void startLoadingMainResource();
         void cancelMainResourceLoad(const ResourceError&);
@@ -152,10 +153,6 @@
         DocumentLoadTiming* timing() { return &m_documentLoadTiming; }
         void resetTiming() { m_documentLoadTiming = DocumentLoadTiming(); }
 
-        // The WebKit layer calls this function when it's ready for the data to
-        // actually be added to the document.
-        void commitData(const char* bytes, size_t length);
-
         ApplicationCacheHost* applicationCacheHost() const { return m_applicationCacheHost.get(); }
 
         virtual void reportMemoryUsage(MemoryObjectInfo*) const;
@@ -167,6 +164,10 @@
         bool m_deferMainResourceDataLoad;
 
     private:
+        static PassRefPtr<DocumentWriter> createWriterFor(Frame*, const Document* ownerDocument, const KURL&, const String& mimeType, const String& encoding, bool userChosen, bool dispatch);
+
+        void ensureWriter();
+        void ensureWriter(const String& mimeType, const KURL& overridingURL = KURL());
 
         // The URL of the document resulting from this DocumentLoader.
         KURL documentURL() const;
@@ -175,13 +176,14 @@
         void setRequest(const ResourceRequest&);
 
         void commitIfReady();
+        void commitData(const char* bytes, size_t length);
         void setMainDocumentError(const ResourceError&);
-        void commitLoad(const char*, int);
         void clearMainResourceLoader();
         ResourceLoader* mainResourceLoader() const;
         void clearMainResourceHandle();
+        PassRefPtr<SharedBuffer> mainResourceData() const;
 
-        bool maybeCreateArchive();
+        void createArchive();
         void clearArchiveResources();
 
         void prepareSubframeArchiveLoadIfNeeded();
@@ -216,7 +218,7 @@
         ResourceLoaderSet m_resourceLoaders;
         ResourceLoaderSet m_multipartResourceLoaders;
         
-        mutable DocumentWriter m_writer;
+        RefPtr<DocumentWriter> m_writer;
 
         // A reference to actual request used to create the data source.
         // This should only be used by the resourceLoadDelegate's
@@ -241,7 +243,6 @@
 
         bool m_committed;
         bool m_isStopping;
-        bool m_gotFirstByte;
         bool m_isClientRedirect;
 
         // FIXME: Document::m_processingLoadEvent and DocumentLoader::m_wasOnloadHandled are roughly the same
diff --git a/Source/core/loader/DocumentThreadableLoader.cpp b/Source/core/loader/DocumentThreadableLoader.cpp
index 968f3fc..8c9c383 100644
--- a/Source/core/loader/DocumentThreadableLoader.cpp
+++ b/Source/core/loader/DocumentThreadableLoader.cpp
@@ -38,7 +38,6 @@
 #include "core/loader/CrossOriginPreflightResultCache.h"
 #include "core/loader/DocumentThreadableLoaderClient.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/ResourceLoader.h"
 #include "core/loader/ThreadableLoaderClient.h"
 #include "core/loader/cache/CachedRawResource.h"
 #include "core/loader/cache/CachedResourceLoader.h"
diff --git a/Source/core/loader/DocumentThreadableLoader.h b/Source/core/loader/DocumentThreadableLoader.h
index 2904173..c3cb12d 100644
--- a/Source/core/loader/DocumentThreadableLoader.h
+++ b/Source/core/loader/DocumentThreadableLoader.h
@@ -32,18 +32,16 @@
 #ifndef DocumentThreadableLoader_h
 #define DocumentThreadableLoader_h
 
-#include "core/loader/FrameLoaderTypes.h"
 #include "core/loader/ThreadableLoader.h"
 #include "core/loader/cache/CachedRawResource.h"
 #include "core/loader/cache/CachedResourceHandle.h"
 #include "core/platform/Timer.h"
 #include "core/platform/network/ResourceError.h"
-#include <wtf/Forward.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/Forward.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
     class Document;
diff --git a/Source/core/loader/DocumentWriter.cpp b/Source/core/loader/DocumentWriter.cpp
index afe84b6..9290db5 100644
--- a/Source/core/loader/DocumentWriter.cpp
+++ b/Source/core/loader/DocumentWriter.cpp
@@ -29,176 +29,57 @@
 #include "config.h"
 #include "core/loader/DocumentWriter.h"
 
-#include "bindings/v8/ScriptController.h"
-#include "core/dom/DOMImplementation.h"
-#include "core/dom/RawDataDocumentParser.h"
+#include "core/dom/Document.h"
 #include "core/dom/ScriptableDocumentParser.h"
-#include "core/html/PluginDocument.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/FrameLoaderClient.h"
 #include "core/loader/FrameLoaderStateMachine.h"
-#include "core/loader/SinkDocument.h"
 #include "core/loader/TextResourceDecoder.h"
 #include "core/page/DOMWindow.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/page/Settings.h"
-#include "core/platform/text/SegmentedString.h"
 #include "weborigin/KURL.h"
 #include "weborigin/SecurityOrigin.h"
+#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
-static inline bool canReferToParentFrameEncoding(const Frame* frame, const Frame* parentFrame) 
+PassRefPtr<DocumentWriter> DocumentWriter::create(Document* document, const String& mimeType, const String& encoding, bool encodingUserChoosen)
 {
-    return parentFrame && parentFrame->document()->securityOrigin()->canAccess(frame->document()->securityOrigin());
+    return adoptRef(new DocumentWriter(document, mimeType, encoding, encodingUserChoosen));
 }
-    
-DocumentWriter::DocumentWriter(Frame* frame)
-    : m_frame(frame)
+
+DocumentWriter::DocumentWriter(Document* document, const String& mimeType, const String& encoding, bool encodingUserChoosen)
+    : m_document(document)
     , m_hasReceivedSomeData(false)
-    , m_encodingWasChosenByUser(false)
-    , m_state(NotStartedWritingState)
-{
-}
-
-// This is only called by ScriptController::executeScriptIfJavaScriptURL
-// and always contains the result of evaluating a javascript: url.
-// This is the <iframe src="javascript:'html'"> case.
-void DocumentWriter::replaceDocument(const String& source, Document* ownerDocument)
-{
-    m_frame->loader()->stopAllLoaders();
-    begin(m_frame->document()->url(), true, ownerDocument);
-
-    if (!source.isNull()) {
-        if (!m_hasReceivedSomeData) {
-            m_hasReceivedSomeData = true;
-            m_frame->document()->setCompatibilityMode(Document::NoQuirksMode);
-        }
-
-        // FIXME: This should call DocumentParser::appendBytes instead of append
-        // to support RawDataDocumentParsers.
-        if (DocumentParser* parser = m_frame->document()->parser()) {
-            parser->pinToMainThread();
-            // Because we're pinned to the main thread we don't need to worry about
-            // passing ownership of the source string.
-            parser->append(source.impl());
-        }
-    }
-
-    end();
-}
-
-void DocumentWriter::clear()
-{
-    m_decoder = 0;
-    m_hasReceivedSomeData = false;
-    if (!m_encodingWasChosenByUser)
-        m_encoding = String();
-}
-
-void DocumentWriter::begin()
-{
-    begin(KURL());
-}
-
-PassRefPtr<Document> DocumentWriter::createDocument(const KURL& url)
-{
-    return DOMImplementation::createDocument(m_mimeType, m_frame, url, m_frame->inViewSourceMode());
-}
-
-void DocumentWriter::begin(const KURL& urlReference, bool dispatch, Document* ownerDocument)
-{
-    // We grab a local copy of the URL because it's easy for callers to supply
-    // a URL that will be deallocated during the execution of this function.
-    // For example, see <https://bugs.webkit.org/show_bug.cgi?id=66360>.
-    KURL url = urlReference;
-
-    // Create a new document before clearing the frame, because it may need to
-    // inherit an aliased security context.
-    RefPtr<Document> document = createDocument(url);
-    
-    // If the new document is for a Plugin but we're supposed to be sandboxed from Plugins,
-    // then replace the document with one whose parser will ignore the incoming data (bug 39323)
-    if (document->isPluginDocument() && document->isSandboxed(SandboxPlugins))
-        document = SinkDocument::create(m_frame, url);
-
-    // FIXME: Do we need to consult the content security policy here about blocked plug-ins?
-
-    bool shouldReuseDefaultView = m_frame->loader()->stateMachine()->isDisplayingInitialEmptyDocument() && m_frame->document()->isSecureTransitionTo(url);
-
-    RefPtr<DOMWindow> originalDOMWindow;
-    if (shouldReuseDefaultView)
-        originalDOMWindow = m_frame->domWindow();
-    m_frame->loader()->clear(!shouldReuseDefaultView, !shouldReuseDefaultView);
-    clear();
-
-    if (!shouldReuseDefaultView)
-        m_frame->setDOMWindow(DOMWindow::create(m_frame));
-    else {
-        // Note that the old Document is still attached to the DOMWindow; the
-        // setDocument() call below will detach the old Document.
-        ASSERT(originalDOMWindow);
-        m_frame->setDOMWindow(originalDOMWindow);
-    }
-
-    m_frame->loader()->setOutgoingReferrer(url);
-    m_frame->domWindow()->setDocument(document);
-
-    if (m_decoder)
-        document->setDecoder(m_decoder.get());
-    if (ownerDocument) {
-        document->setCookieURL(ownerDocument->cookieURL());
-        document->setSecurityOrigin(ownerDocument->securityOrigin());
-    }
-
-    m_frame->loader()->didBeginDocument(dispatch);
-
-    document->implicitOpen();
-
+    , m_decoderBuilder(mimeType, encoding, encodingUserChoosen)
     // We grab a reference to the parser so that we'll always send data to the
     // original parser, even if the document acquires a new parser (e.g., via
     // document.open).
-    m_parser = document->parser();
-
-    if (m_frame->view())
-        m_frame->view()->setContentsSize(IntSize());
-
-    m_state = StartedWritingState;
+    , m_parser(m_document->implicitOpen())
+{
+    if (FrameView* view = m_document->frame()->view())
+        view->setContentsSize(IntSize());
 }
 
-TextResourceDecoder* DocumentWriter::createDecoderIfNeeded()
+DocumentWriter::~DocumentWriter()
 {
-    if (!m_decoder) {
-        if (Settings* settings = m_frame->settings()) {
-            m_decoder = TextResourceDecoder::create(m_mimeType,
-                settings->defaultTextEncodingName(),
-                settings->usesEncodingDetector());
-            Frame* parentFrame = m_frame->tree()->parent();
-            // Set the hint encoding to the parent frame encoding only if
-            // the parent and the current frames share the security origin.
-            // We impose this condition because somebody can make a child frame 
-            // containing a carefully crafted html/javascript in one encoding
-            // that can be mistaken for hintEncoding (or related encoding) by
-            // an auto detector. When interpreted in the latter, it could be
-            // an attack vector.
-            // FIXME: This might be too cautious for non-7bit-encodings and
-            // we may consider relaxing this later after testing.
-            if (canReferToParentFrameEncoding(m_frame, parentFrame))
-                m_decoder->setHintEncoding(parentFrame->document()->decoder());
-        } else
-            m_decoder = TextResourceDecoder::create(m_mimeType, String());
-        Frame* parentFrame = m_frame->tree()->parent();
-        if (m_encoding.isEmpty()) {
-            if (canReferToParentFrameEncoding(m_frame, parentFrame))
-                m_decoder->setEncoding(parentFrame->document()->inputEncoding(), TextResourceDecoder::EncodingFromParentFrame);
-        } else {
-            m_decoder->setEncoding(m_encoding,
-                m_encodingWasChosenByUser ? TextResourceDecoder::UserChosenEncoding : TextResourceDecoder::EncodingFromHTTPHeader);
-        }
-        m_frame->document()->setDecoder(m_decoder.get());
+}
+
+void DocumentWriter::appendReplacingData(const String& source)
+{
+    ASSERT(!m_hasReceivedSomeData);
+    m_hasReceivedSomeData = true;
+    m_document->setCompatibilityMode(Document::NoQuirksMode);
+
+    // FIXME: This should call DocumentParser::appendBytes instead of append
+    // to support RawDataDocumentParsers.
+    if (DocumentParser* parser = m_document->parser()) {
+        parser->pinToMainThread();
+        // Because we're pinned to the main thread we don't need to worry about
+        // passing ownership of the source string.
+        parser->append(source.impl());
     }
-    return m_decoder.get();
 }
 
 void DocumentWriter::reportDataReceived()
@@ -208,51 +89,46 @@
         return;
     m_hasReceivedSomeData = true;
     if (m_decoder->encoding().usesVisualOrdering())
-        m_frame->document()->setVisuallyOrdered();
+        m_document->setVisuallyOrdered();
 }
 
 void DocumentWriter::addData(const char* bytes, size_t length)
 {
-    // Check that we're inside begin()/end().
-    // FIXME: Change these to ASSERT once https://bugs.webkit.org/show_bug.cgi?id=80427 has
-    // been resolved.
-    if (m_state == NotStartedWritingState)
-        CRASH();
-    if (m_state == FinishedWritingState)
-        CRASH();
-
     ASSERT(m_parser);
-    m_parser->appendBytes(this, bytes, length);
+    if (!m_decoder && m_parser->needsDecoder() && 0 < length)
+        m_decoder = m_decoderBuilder.buildFor(m_document);
+    // appendBytes() can result replacing DocumentLoader::m_writer.
+    RefPtr<DocumentWriter> protectingThis(this);
+    size_t consumedChars = m_parser->appendBytes(bytes, length);
+    if (consumedChars)
+        reportDataReceived();
 }
 
 void DocumentWriter::end()
 {
-    ASSERT(m_frame->page());
-    ASSERT(m_frame->document());
-
-    // The parser is guaranteed to be released after this point. begin() would
-    // have to be called again before we can start writing more data.
-    m_state = FinishedWritingState;
+    ASSERT(m_document);
 
     // http://bugs.webkit.org/show_bug.cgi?id=10854
     // The frame's last ref may be removed and it can be deleted by checkCompleted(), 
     // so we'll add a protective refcount
-    RefPtr<Frame> protector(m_frame);
+    RefPtr<Frame> protector(m_document->frame());
 
     if (!m_parser)
         return;
-    // FIXME: m_parser->finish() should imply m_parser->flush().
-    m_parser->flush(this);
+
+    if (!m_decoder && m_parser->needsDecoder())
+        m_decoder = m_decoderBuilder.buildFor(m_document);
+    // flush() can result replacing DocumentLoader::m_writer.
+    RefPtr<DocumentWriter> protectingThis(this);
+    size_t consumedChars = m_parser->flush();
+    if (consumedChars)
+        reportDataReceived();
     if (!m_parser)
         return;
+
     m_parser->finish();
     m_parser = 0;
-}
-
-void DocumentWriter::setEncoding(const String& name, bool userChosen)
-{
-    m_encoding = name;
-    m_encodingWasChosenByUser = userChosen;
+    m_document = 0;
 }
 
 void DocumentWriter::setDocumentWasLoadedAsPartOfNavigation()
diff --git a/Source/core/loader/DocumentWriter.h b/Source/core/loader/DocumentWriter.h
index b662b7e..35667be 100644
--- a/Source/core/loader/DocumentWriter.h
+++ b/Source/core/loader/DocumentWriter.h
@@ -29,6 +29,8 @@
 #ifndef DocumentWriter_h
 #define DocumentWriter_h
 
+#include "core/loader/TextResourceDecoderBuilder.h"
+#include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
@@ -40,53 +42,43 @@
 class SecurityOrigin;
 class TextResourceDecoder;
 
-class DocumentWriter {
+class DocumentWriter : public RefCounted<DocumentWriter> {
     WTF_MAKE_NONCOPYABLE(DocumentWriter);
 public:
-    explicit DocumentWriter(Frame*);
+    static PassRefPtr<DocumentWriter> create(Document*, const String& mimeType = "", const String& encoding = "", bool encodingUserChoosen = false);
+
+    ~DocumentWriter();
+
+    void end();
 
     // This is only called by ScriptController::executeScriptIfJavaScriptURL
     // and always contains the result of evaluating a javascript: url.
     void replaceDocument(const String&, Document* ownerDocument);
 
-    void begin();
-    void begin(const KURL&, bool dispatchWindowObjectAvailable = true, Document* ownerDocument = 0);
     void addData(const char* bytes, size_t length);
-    void end();
     
-    void setFrame(Frame* frame) { m_frame = frame; }
-
-    void setEncoding(const String& encoding, bool userChosen);
-
-    const String& mimeType() const { return m_mimeType; }
-    void setMIMEType(const String& type) { m_mimeType = type; }
+    const String& mimeType() const { return m_decoderBuilder.mimeType(); }
+    const String& encoding() const { return m_decoderBuilder.encoding(); }
+    bool encodingWasChosenByUser() const { return m_decoderBuilder.encodingWasChosenByUser(); }
 
     // Exposed for DocumentParser::appendBytes.
-    TextResourceDecoder* createDecoderIfNeeded();
     void reportDataReceived();
+    // Exposed for DocumentLoader::replaceDocument.
+    void appendReplacingData(const String&);
 
     void setDocumentWasLoadedAsPartOfNavigation();
 
 private:
+    DocumentWriter(Document*, const String& mimeType, const String& encoding, bool encodingUserChoosen);
+
     PassRefPtr<Document> createDocument(const KURL&);
-    void clear();
 
-    Frame* m_frame;
-
+    Document* m_document;
     bool m_hasReceivedSomeData;
-    String m_mimeType;
+    TextResourceDecoderBuilder m_decoderBuilder;
 
-    bool m_encodingWasChosenByUser;
-    String m_encoding;
     RefPtr<TextResourceDecoder> m_decoder;
     RefPtr<DocumentParser> m_parser;
-
-    enum WriterState {
-        NotStartedWritingState,
-        StartedWritingState,
-        FinishedWritingState,
-    };
-    WriterState m_state;
 };
 
 } // namespace WebCore
diff --git a/Source/core/loader/EmptyClients.cpp b/Source/core/loader/EmptyClients.cpp
index d3135f4..447962f 100644
--- a/Source/core/loader/EmptyClients.cpp
+++ b/Source/core/loader/EmptyClients.cpp
@@ -91,11 +91,6 @@
     return String();
 }
 
-PolicyAction EmptyFrameLoaderClient::policyForNewWindowAction(const NavigationAction&, const String&)
-{
-    return PolicyUse;
-}
-
 PolicyAction EmptyFrameLoaderClient::decidePolicyForNavigationAction(const NavigationAction&, const ResourceRequest&)
 {
     return PolicyUse;
diff --git a/Source/core/loader/EmptyClients.h b/Source/core/loader/EmptyClients.h
index 4856e60..e065823 100644
--- a/Source/core/loader/EmptyClients.h
+++ b/Source/core/loader/EmptyClients.h
@@ -39,12 +39,14 @@
 #include "core/page/EditorClient.h"
 #include "core/page/FocusDirection.h"
 #include "core/page/Page.h"
+#include "core/platform/DragImage.h"
 #include "core/platform/graphics/FloatRect.h"
 #include "core/platform/network/ResourceError.h"
 #include "core/platform/text/TextCheckerClient.h"
 #include "modules/device_orientation/DeviceMotionClient.h"
-
 #include "public/platform/WebScreenInfo.h"
+#include "wtf/Forward.h"
+
 #include <v8.h>
 
 /*
@@ -83,8 +85,8 @@
     virtual void takeFocus(FocusDirection) OVERRIDE { }
 
     virtual void focusedNodeChanged(Node*) OVERRIDE { }
-    virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, const NavigationAction&) OVERRIDE { return 0; }
-    virtual void show() OVERRIDE { }
+    virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, const NavigationAction&, NavigationPolicy) OVERRIDE { return 0; }
+    virtual void show(NavigationPolicy) OVERRIDE { }
 
     virtual bool canRunModal() OVERRIDE { return false; }
     virtual void runModal() OVERRIDE { }
@@ -211,10 +213,6 @@
     virtual void dispatchDidFinishLoad() OVERRIDE { }
     virtual void dispatchDidLayout(LayoutMilestones) OVERRIDE { }
 
-    virtual Frame* dispatchCreatePage(const NavigationAction&) OVERRIDE { return 0; }
-    virtual void dispatchShow() OVERRIDE { }
-
-    virtual PolicyAction policyForNewWindowAction(const NavigationAction&, const String&) OVERRIDE;
     virtual PolicyAction decidePolicyForNavigationAction(const NavigationAction&, const ResourceRequest&) OVERRIDE;
 
     virtual void dispatchUnableToImplementPolicy(const ResourceError&) OVERRIDE { }
@@ -222,16 +220,13 @@
     virtual void dispatchWillSendSubmitEvent(PassRefPtr<FormState>) OVERRIDE;
     virtual void dispatchWillSubmitForm(PassRefPtr<FormState>) OVERRIDE;
 
-    virtual void setMainDocumentError(DocumentLoader*, const ResourceError&) OVERRIDE { }
-
     virtual void postProgressStartedNotification() OVERRIDE { }
     virtual void postProgressEstimateChangedNotification() OVERRIDE { }
     virtual void postProgressFinishedNotification() OVERRIDE { }
 
     virtual void startDownload(const ResourceRequest&, const String& suggestedName = String()) OVERRIDE { UNUSED_PARAM(suggestedName); }
 
-    virtual void committedLoad(DocumentLoader*, const char*, int) OVERRIDE { }
-    virtual void finishedLoading(DocumentLoader*) OVERRIDE { }
+    virtual void didReceiveDocumentData(const char*, int) OVERRIDE { }
 
     virtual ResourceError cancelledError(const ResourceRequest&) OVERRIDE { ResourceError error("", 0, "", ""); error.setIsCancellation(true); return error; }
     virtual ResourceError cannotShowURLError(const ResourceRequest&) OVERRIDE { return ResourceError("", 0, "", ""); }
@@ -267,7 +262,6 @@
 
     virtual ObjectContentType objectContentType(const KURL&, const String&, bool) OVERRIDE { return ObjectContentType(); }
 
-    virtual void redirectDataToPlugin(Widget*) OVERRIDE { }
     virtual void dispatchDidClearWindowObjectInWorld(DOMWrapperWorld*) OVERRIDE { }
     virtual void documentElementAvailable() OVERRIDE { }
 
@@ -360,7 +354,7 @@
     EmptyDragClient() { }
     virtual ~EmptyDragClient() {}
     virtual DragDestinationAction actionMaskForDrag(DragData*) OVERRIDE { return DragDestinationActionNone; }
-    virtual void startDrag(DragImageRef, const IntPoint&, const IntPoint&, Clipboard*, Frame*, bool) OVERRIDE { }
+    virtual void startDrag(DragImage*, const IntPoint&, const IntPoint&, Clipboard*, Frame*, bool) OVERRIDE { }
 };
 
 class EmptyInspectorClient : public InspectorClient {
diff --git a/Source/core/loader/FormSubmission.cpp b/Source/core/loader/FormSubmission.cpp
index 22bc20c..09bfb9e 100644
--- a/Source/core/loader/FormSubmission.cpp
+++ b/Source/core/loader/FormSubmission.cpp
@@ -142,7 +142,7 @@
     if (event && event->target()) {
         for (Node* node = event->target()->toNode(); node; node = node->parentNode()) {
             if (node->isElementNode() && toElement(node)->isFormControlElement()) {
-                submitButton = static_cast<HTMLFormControlElement*>(node);
+                submitButton = toHTMLFormControlElement(node);
                 break;
             }
         }
diff --git a/Source/core/loader/FrameLoader.cpp b/Source/core/loader/FrameLoader.cpp
index c994290..e10e317 100644
--- a/Source/core/loader/FrameLoader.cpp
+++ b/Source/core/loader/FrameLoader.cpp
@@ -35,20 +35,12 @@
 #include "config.h"
 #include "core/loader/FrameLoader.h"
 
-#include <wtf/CurrentTime.h>
-#include <wtf/MemoryInstrumentationHashSet.h>
-#include <wtf/StdLibExtras.h>
-#include <wtf/text/CString.h>
-#include <wtf/text/WTFString.h>
 #include "HTMLNames.h"
-#include "SVGNames.h"
 #include "bindings/v8/DOMWrapperWorld.h"
 #include "bindings/v8/ScriptController.h"
-#include "bindings/v8/ScriptSourceCode.h"
 #include "bindings/v8/SerializedScriptValue.h"
 #include "core/accessibility/AXObjectCache.h"
 #include "core/dom/BeforeUnloadEvent.h"
-#include "core/dom/DOMImplementation.h"
 #include "core/dom/Document.h"
 #include "core/dom/Element.h"
 #include "core/dom/Event.h"
@@ -58,15 +50,12 @@
 #include "core/editing/Editor.h"
 #include "core/history/BackForwardController.h"
 #include "core/history/HistoryItem.h"
-#include "core/html/HTMLAnchorElement.h"
 #include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLInputElement.h"
 #include "core/html/HTMLObjectElement.h"
-#include "core/html/PluginDocument.h"
 #include "core/html/parser/HTMLParserIdioms.h"
 #include "core/inspector/InspectorController.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/inspector/ScriptCallStack.h"
 #include "core/loader/DocumentLoadTiming.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FormState.h"
@@ -75,17 +64,13 @@
 #include "core/loader/FrameLoaderClient.h"
 #include "core/loader/IconController.h"
 #include "core/loader/ProgressTracker.h"
-#include "core/loader/TextResourceDecoder.h"
 #include "core/loader/UniqueIdentifier.h"
 #include "core/loader/appcache/ApplicationCacheHost.h"
 #include "core/loader/cache/CachedResourceLoader.h"
-#include "core/loader/cache/MemoryCache.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
-#include "core/page/Console.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "core/page/DOMWindow.h"
-#include "core/page/EditorClient.h"
 #include "core/page/EventHandler.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameTree.h"
@@ -94,32 +79,22 @@
 #include "core/page/Settings.h"
 #include "core/page/WindowFeatures.h"
 #include "core/platform/Logging.h"
-#include "core/platform/MIMETypeFromURL.h"
-#include "core/platform/MIMETypeRegistry.h"
 #include "core/platform/ScrollAnimator.h"
 #include "core/platform/graphics/FloatRect.h"
 #include "core/platform/network/HTTPParsers.h"
 #include "core/platform/network/ResourceHandle.h"
 #include "core/platform/network/ResourceRequest.h"
-#include "core/platform/text/SegmentedString.h"
-#include "core/plugins/PluginData.h"
-#include "core/svg/SVGDocument.h"
-#include "core/svg/SVGLocatable.h"
-#include "core/svg/SVGPreserveAspectRatio.h"
-#include "core/svg/SVGSVGElement.h"
-#include "core/svg/SVGViewElement.h"
-#include "core/svg/SVGViewSpec.h"
 #include "core/xml/parser/XMLDocumentParser.h"
 #include "modules/webdatabase/DatabaseManager.h"
-#include "weborigin/SchemeRegistry.h"
 #include "weborigin/SecurityOrigin.h"
 #include "weborigin/SecurityPolicy.h"
-
+#include "wtf/MemoryInstrumentationHashSet.h"
+#include "wtf/text/CString.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
 using namespace HTMLNames;
-using namespace SVGNames;
 
 static const char defaultAcceptHeader[] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
 
@@ -965,18 +940,6 @@
     }
 }
 
-void FrameLoader::prepareForLoadStart()
-{
-    m_progressTracker->progressStarted();
-    m_client->dispatchDidStartProvisionalLoad();
-
-    // Notify accessibility.
-    if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache()) {
-        AXObjectCache::AXLoadingEvent loadingEvent = loadType() == FrameLoadTypeReload ? AXObjectCache::AXLoadingReloaded : AXObjectCache::AXLoadingStarted;
-        cache->frameLoadingEventNotification(m_frame, loadingEvent);
-    }
-}
-
 void FrameLoader::loadFrameRequest(const FrameLoadRequest& request, bool lockBackForwardList,
     PassRefPtr<Event> event, PassRefPtr<FormState> formState, ShouldSendReferrer shouldSendReferrer)
 {    
@@ -1010,7 +973,7 @@
     FrameLoadType loadType;
     if (resourceRequest.cachePolicy() == ReloadIgnoringCacheData)
         loadType = FrameLoadTypeReload;
-    else if (lockBackForwardList || history()->currentItemShouldBeReplaced())
+    else if (lockBackForwardList)
         loadType = FrameLoadTypeRedirectWithLockedBackForwardList;
     else
         loadType = FrameLoadTypeStandard;
@@ -1029,8 +992,7 @@
     }
 }
 
-void FrameLoader::loadURL(const ResourceRequest& request, const String& frameName, FrameLoadType newLoadType,
-    PassRefPtr<Event> event, PassRefPtr<FormState> formState)
+void FrameLoader::loadURL(const ResourceRequest& request, const String& frameName, FrameLoadType newLoadType, PassRefPtr<Event> event, PassRefPtr<FormState> formState)
 {
     if (m_inStopAllLoaders)
         return;
@@ -1125,14 +1087,13 @@
     if (type == FrameLoadTypeRedirectWithLockedBackForwardList)
         loader->setIsClientRedirect(true);
 
-    m_loadType = type;
     bool isFormSubmission = formState;
 
     if (shouldPerformFragmentNavigation(isFormSubmission, request.httpMethod(), type, request.url()))
-        checkNavigationPolicyAndContinueFragmentScroll(action);
+        checkNavigationPolicyAndContinueFragmentScroll(action, type != FrameLoadTypeRedirectWithLockedBackForwardList);
     else {
         setPolicyDocumentLoader(loader.get());
-        checkNavigationPolicyAndContinueLoad(formState);
+        checkNavigationPolicyAndContinueLoad(formState, type);
     }
 }
 
@@ -1170,6 +1131,9 @@
     frame()->loader()->history()->saveDocumentAndScrollState();
 
     ResourceRequest request = documentLoader->request();
+    // FIXME: We need to reset cache policy to prevent it from being incorrectly propagted to the reload.
+    // Do we need to propagate anything other than the url?
+    request.setCachePolicy(UseProtocolCachePolicy);
     if (!overrideURL.isEmpty())
         request.setURL(overrideURL);
     else if (!documentLoader->unreachableURL().isEmpty())
@@ -1927,7 +1891,7 @@
         checkLoadComplete();
 }
 
-void FrameLoader::checkNavigationPolicyAndContinueFragmentScroll(const NavigationAction& action)
+void FrameLoader::checkNavigationPolicyAndContinueFragmentScroll(const NavigationAction& action, bool isNewNavigation)
 {
     m_documentLoader->setTriggeringAction(action);
 
@@ -1940,7 +1904,7 @@
         m_provisionalDocumentLoader->stopLoading();
         setProvisionalDocumentLoader(0);
     }
-    loadInSameDocument(request.url(), 0, m_loadType != FrameLoadTypeRedirectWithLockedBackForwardList);
+    loadInSameDocument(request.url(), 0, isNewNavigation);
 }
 
 bool FrameLoader::shouldPerformFragmentNavigation(bool isFormSubmission, const String& httpMethod, FrameLoadType loadType, const KURL& url)
@@ -2037,7 +2001,7 @@
     return chrome.runBeforeUnloadConfirmPanel(text, m_frame);
 }
 
-void FrameLoader::checkNavigationPolicyAndContinueLoad(PassRefPtr<FormState> formState)
+void FrameLoader::checkNavigationPolicyAndContinueLoad(PassRefPtr<FormState> formState, FrameLoadType type)
 {
     // If we loaded an alternate page to replace an unreachableURL, we'll get in here with a
     // nil policyDataSource because loading the alternate page will have passed
@@ -2077,7 +2041,7 @@
         // If the navigation request came from the back/forward menu, and we punt on it, we have the 
         // problem that we have optimistically moved the b/f cursor already, so move it back.  For sanity, 
         // we only do this when punting a navigation for the target frame or top-level frame.  
-        if ((isTargetItem || isLoadingMainFrame()) && isBackForwardLoadType(m_loadType)) {
+        if ((isTargetItem || isLoadingMainFrame()) && isBackForwardLoadType(type)) {
             if (Page* page = m_frame->page()) {
                 Frame* mainFrame = page->mainFrame();
                 if (HistoryItem* resetItem = mainFrame->loader()->history()->currentItem())
@@ -2101,6 +2065,7 @@
     }
 
     setProvisionalDocumentLoader(m_policyDocumentLoader.get());
+    m_loadType = type;
     setState(FrameStateProvisional);
 
     setPolicyDocumentLoader(0);
@@ -2108,16 +2073,14 @@
     if (formState)
         m_client->dispatchWillSubmitForm(formState);
 
-    prepareForLoadStart();
+    m_progressTracker->progressStarted();
+    m_client->dispatchDidStartProvisionalLoad();
+    ASSERT(m_provisionalDocumentLoader);
 
-    // The load might be cancelled inside of prepareForLoadStart(), nulling out the m_provisionalDocumentLoader,
-    // so we need to null check it again.
-    if (!m_provisionalDocumentLoader)
-        return;
-
-    DocumentLoader* activeDocLoader = activeDocumentLoader();
-    if (activeDocLoader && activeDocLoader->isLoadingMainResource())
-        return;
+    if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache()) {
+        AXObjectCache::AXLoadingEvent loadingEvent = loadType() == FrameLoadTypeReload ? AXObjectCache::AXLoadingReloaded : AXObjectCache::AXLoadingStarted;
+        cache->frameLoadingEventNotification(m_frame, loadingEvent);
+    }
 
     m_provisionalDocumentLoader->startLoadingMainResource();
 }
@@ -2130,23 +2093,33 @@
     if (!DOMWindow::allowPopUp(m_frame))
         return;
 
-    PolicyAction policy = m_client->policyForNewWindowAction(action, frameName);
-    ASSERT(policy != PolicyIgnore);
-    if (policy == PolicyDownload) {
+    NavigationPolicy navigationPolicy = NavigationPolicyNewForegroundTab;
+    action.specifiesNavigationPolicy(&navigationPolicy);
+
+    if (navigationPolicy == NavigationPolicyDownload) {
         m_client->startDownload(action.resourceRequest());
         return;
     }
 
     RefPtr<Frame> frame = m_frame;
-    RefPtr<Frame> mainFrame = m_client->dispatchCreatePage(action);
-    if (!mainFrame)
-        return;
+    RefPtr<Frame> mainFrame = m_frame;
+
+    if (!m_frame->settings() || m_frame->settings()->supportsMultipleWindows()) {
+        struct WindowFeatures features;
+        Page* newPage = m_frame->page()->chrome().client()->createWindow(m_frame, FrameLoadRequest(m_frame->document()->securityOrigin()),
+            features, action, navigationPolicy);
+
+        // createWindow can return null (e.g., popup blocker denies the window).
+        if (!newPage)
+            return;
+        mainFrame = newPage->mainFrame();
+    }
 
     if (frameName != "_blank")
         mainFrame->tree()->setName(frameName);
 
     mainFrame->page()->setOpenedByDOM();
-    mainFrame->loader()->m_client->dispatchShow();
+    mainFrame->page()->chrome().show(navigationPolicy);
     if (!m_suppressOpenerInNewFrame) {
         mainFrame->loader()->setOpener(frame.get());
         mainFrame->document()->setReferrerPolicy(frame->document()->referrerPolicy());
@@ -2502,7 +2475,7 @@
         return 0;
 
     NavigationAction action(requestWithReferrer.resourceRequest());
-    Page* page = oldPage->chrome().createWindow(openerFrame, requestWithReferrer, features, action);
+    Page* page = oldPage->chrome().client()->createWindow(openerFrame, requestWithReferrer, features, action);
     if (!page)
         return 0;
 
diff --git a/Source/core/loader/FrameLoader.h b/Source/core/loader/FrameLoader.h
index 4b6e46e..af5f5a8 100644
--- a/Source/core/loader/FrameLoader.h
+++ b/Source/core/loader/FrameLoader.h
@@ -276,8 +276,8 @@
     
     bool fireBeforeUnloadEvent(Chrome&);
 
-    void checkNavigationPolicyAndContinueLoad(PassRefPtr<FormState>);
-    void checkNavigationPolicyAndContinueFragmentScroll(const NavigationAction&);
+    void checkNavigationPolicyAndContinueLoad(PassRefPtr<FormState>, FrameLoadType);
+    void checkNavigationPolicyAndContinueFragmentScroll(const NavigationAction&, bool isNewNavigation);
     void checkNewWindowPolicyAndContinue(PassRefPtr<FormState>, const String& frameName, const NavigationAction&);
 
     bool shouldPerformFragmentNavigation(bool isFormSubmission, const String& httpMethod, FrameLoadType, const KURL&);
@@ -313,8 +313,6 @@
 
     void loadInSameDocument(const KURL&, PassRefPtr<SerializedScriptValue> stateObject, bool isNewNavigation);
 
-    void prepareForLoadStart();
-
     bool didOpenURL();
 
     void scheduleCheckCompleted();
diff --git a/Source/core/loader/FrameLoaderClient.h b/Source/core/loader/FrameLoaderClient.h
index 1a41b4c..011dc65 100644
--- a/Source/core/loader/FrameLoaderClient.h
+++ b/Source/core/loader/FrameLoaderClient.h
@@ -117,10 +117,6 @@
 
         virtual void dispatchDidLayout(LayoutMilestones) { }
 
-        virtual Frame* dispatchCreatePage(const NavigationAction&) = 0;
-        virtual void dispatchShow() = 0;
-
-        virtual PolicyAction policyForNewWindowAction(const NavigationAction&, const String& frameName) = 0;
         virtual PolicyAction decidePolicyForNavigationAction(const NavigationAction&, const ResourceRequest&) = 0;
 
         virtual void dispatchUnableToImplementPolicy(const ResourceError&) = 0;
@@ -130,8 +126,6 @@
         virtual void dispatchWillSendSubmitEvent(PassRefPtr<FormState>) = 0;
         virtual void dispatchWillSubmitForm(PassRefPtr<FormState>) = 0;
 
-        virtual void setMainDocumentError(DocumentLoader*, const ResourceError&) = 0;
-
         // Maybe these should go into a ProgressTrackerClient some day
         virtual void postProgressStartedNotification() = 0;
         virtual void postProgressEstimateChangedNotification() = 0;
@@ -139,8 +133,7 @@
 
         virtual void startDownload(const ResourceRequest&, const String& suggestedName = String()) = 0;
 
-        virtual void committedLoad(DocumentLoader*, const char*, int) = 0;
-        virtual void finishedLoading(DocumentLoader*) = 0;
+        virtual void didReceiveDocumentData(const char*, int) = 0;
 
         virtual bool shouldGoToHistoryItem(HistoryItem*) const = 0;
         virtual bool shouldStopLoadingForHistoryItem(HistoryItem*) const = 0;
@@ -190,7 +183,6 @@
 
         virtual PassRefPtr<Frame> createFrame(const KURL& url, const String& name, HTMLFrameOwnerElement* ownerElement, const String& referrer, bool allowsScrolling, int marginWidth, int marginHeight) = 0;
         virtual PassRefPtr<Widget> createPlugin(const IntSize&, HTMLPlugInElement*, const KURL&, const Vector<String>&, const Vector<String>&, const String&, bool loadManually) = 0;
-        virtual void redirectDataToPlugin(Widget* pluginWidget) = 0;
 
         virtual PassRefPtr<Widget> createJavaAppletWidget(const IntSize&, HTMLAppletElement*, const KURL& baseURL, const Vector<String>& paramNames, const Vector<String>& paramValues) = 0;
 
diff --git a/Source/core/loader/HistoryController.cpp b/Source/core/loader/HistoryController.cpp
index 73408cc..621d739 100644
--- a/Source/core/loader/HistoryController.cpp
+++ b/Source/core/loader/HistoryController.cpp
@@ -42,10 +42,9 @@
 #include "core/page/FrameTree.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
-#include "core/page/Settings.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/platform/Logging.h"
-#include <wtf/text/CString.h>
+#include "wtf/text/CString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/HistoryController.h b/Source/core/loader/HistoryController.h
index 0901ed2..de855f8 100644
--- a/Source/core/loader/HistoryController.h
+++ b/Source/core/loader/HistoryController.h
@@ -30,11 +30,10 @@
 #ifndef HistoryController_h
 #define HistoryController_h
 
-#include "bindings/v8/SerializedScriptValue.h"
 #include "core/loader/FrameLoaderTypes.h"
-#include <wtf/Noncopyable.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/Noncopyable.h"
+#include "wtf/RefPtr.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/NavigationAction.cpp b/Source/core/loader/NavigationAction.cpp
index 6ac91d1..baa43db 100644
--- a/Source/core/loader/NavigationAction.cpp
+++ b/Source/core/loader/NavigationAction.cpp
@@ -29,7 +29,7 @@
 #include "config.h"
 #include "core/loader/NavigationAction.h"
 
-#include "core/dom/Event.h"
+#include "core/dom/MouseEvent.h"
 #include "core/loader/FrameLoader.h"
 
 namespace WebCore {
@@ -87,4 +87,17 @@
 {
 }
 
+bool NavigationAction::specifiesNavigationPolicy(NavigationPolicy* policy) const
+{
+    const MouseEvent* event = 0;
+    if (m_type == NavigationTypeLinkClicked && m_event->isMouseEvent())
+        event = toMouseEvent(m_event.get());
+    else if (m_type == NavigationTypeFormSubmitted && m_event && m_event->underlyingEvent() && m_event->underlyingEvent()->isMouseEvent())
+        event = toMouseEvent(m_event->underlyingEvent());
+
+    if (!event)
+        return false;
+    return navigationPolicyFromMouseEvent(event->button(), event->ctrlKey(), event->shiftKey(), event->altKey(), event->metaKey(), policy);
+}
+
 }
diff --git a/Source/core/loader/NavigationAction.h b/Source/core/loader/NavigationAction.h
index ee42406..5681e48 100644
--- a/Source/core/loader/NavigationAction.h
+++ b/Source/core/loader/NavigationAction.h
@@ -31,6 +31,7 @@
 
 #include "core/dom/Event.h"
 #include "core/loader/FrameLoaderTypes.h"
+#include "core/loader/NavigationPolicy.h"
 #include "core/platform/network/ResourceRequest.h"
 #include "weborigin/KURL.h"
 #include "wtf/Forward.h"
@@ -52,7 +53,9 @@
         const ResourceRequest& resourceRequest() const { return m_resourceRequest; }
 
         NavigationType type() const { return m_type; }
-        const Event* event() const { return m_event.get(); }
+        Event* event() const { return m_event.get(); }
+
+        bool specifiesNavigationPolicy(NavigationPolicy*) const;
 
     private:
         ResourceRequest m_resourceRequest;
diff --git a/Source/core/editing/chromium/FrameSelectionChromium.cpp b/Source/core/loader/NavigationPolicy.cpp
similarity index 66%
rename from Source/core/editing/chromium/FrameSelectionChromium.cpp
rename to Source/core/loader/NavigationPolicy.cpp
index ef88491..e581670 100644
--- a/Source/core/editing/chromium/FrameSelectionChromium.cpp
+++ b/Source/core/loader/NavigationPolicy.cpp
@@ -1,10 +1,10 @@
 /*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- * 
+ * Copyright (C) 2009 Google Inc. All rights reserved.
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
  * met:
- * 
+ *
  *     * Redistributions of source code must retain the above copyright
  * notice, this list of conditions and the following disclaimer.
  *     * Redistributions in binary form must reproduce the above
@@ -14,7 +14,7 @@
  *     * Neither the name of Google Inc. nor the names of its
  * contributors may be used to endorse or promote products derived from
  * this software without specific prior written permission.
- * 
+ *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
@@ -29,21 +29,34 @@
  */
 
 #include "config.h"
-#include "core/editing/FrameSelection.h"
-
-#include "core/accessibility/AXObjectCache.h"
-#include "core/dom/Document.h"
-#include "core/page/Frame.h"
+#include "NavigationPolicy.h"
 
 namespace WebCore {
 
-void FrameSelection::notifyAccessibilityForSelectionChange()
+bool navigationPolicyFromMouseEvent(unsigned short button, bool ctrl, bool shift, bool alt, bool meta, NavigationPolicy* policy)
 {
-    // FIXME: Support editable text in chromium.
-    if (m_selection.start().isNotNull() && m_selection.end().isNotNull()) {
-        if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache())
-            cache->postNotification(m_selection.start().deprecatedNode(), AXObjectCache::AXSelectedTextChanged, false);
+#if OS(DARWIN)
+    const bool newTabModifier = (button == 1) || meta;
+#else
+    const bool newTabModifier = (button == 1) || ctrl;
+#endif
+    if (!newTabModifier && !shift && !alt)
+        return false;
+
+    ASSERT(policy);
+    if (newTabModifier) {
+        if (shift)
+            *policy = NavigationPolicyNewForegroundTab;
+        else
+            *policy = NavigationPolicyNewBackgroundTab;
+    } else {
+        if (shift)
+            *policy = NavigationPolicyNewWindow;
+        else
+            *policy = NavigationPolicyDownload;
     }
+    return true;
 }
 
 } // namespace WebCore
+
diff --git a/Source/core/fileapi/ThreadableBlobRegistry.h b/Source/core/loader/NavigationPolicy.h
similarity index 75%
copy from Source/core/fileapi/ThreadableBlobRegistry.h
copy to Source/core/loader/NavigationPolicy.h
index a72b202..63af6aa 100644
--- a/Source/core/fileapi/ThreadableBlobRegistry.h
+++ b/Source/core/loader/NavigationPolicy.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010 Google Inc. All rights reserved.
+ * Copyright (C) 2009 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,25 +28,23 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ThreadableBlobRegistry_h
-#define ThreadableBlobRegistry_h
-
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
+#ifndef NavigationPolicy_h
+#define NavigationPolicy_h
 
 namespace WebCore {
 
-class BlobData;
-class KURL;
-class SecurityOrigin;
-
-class ThreadableBlobRegistry {
-public:
-    static void registerBlobURL(const KURL&, PassOwnPtr<BlobData>);
-    static void registerBlobURL(SecurityOrigin*, const KURL&, const KURL& srcURL);
-    static void unregisterBlobURL(const KURL&);
+enum NavigationPolicy {
+    NavigationPolicyIgnore,
+    NavigationPolicyDownload,
+    NavigationPolicyCurrentTab,
+    NavigationPolicyNewBackgroundTab,
+    NavigationPolicyNewForegroundTab,
+    NavigationPolicyNewWindow,
+    NavigationPolicyNewPopup,
 };
 
+bool navigationPolicyFromMouseEvent(unsigned short button, bool ctrl, bool shift, bool alt, bool meta, NavigationPolicy*);
+
 } // namespace WebCore
 
-#endif // ThreadableBlobRegistry_h
+#endif
diff --git a/Source/core/loader/NavigationScheduler.cpp b/Source/core/loader/NavigationScheduler.cpp
index 999d90e..56d2e0b 100644
--- a/Source/core/loader/NavigationScheduler.cpp
+++ b/Source/core/loader/NavigationScheduler.cpp
@@ -36,9 +36,7 @@
 #include "core/dom/Event.h"
 #include "core/dom/UserGestureIndicator.h"
 #include "core/history/BackForwardController.h"
-#include "core/history/HistoryItem.h"
 #include "core/html/HTMLFormElement.h"
-#include "core/html/HTMLFrameOwnerElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/DocumentLoader.h"
 #include "core/loader/FormState.h"
@@ -46,10 +44,9 @@
 #include "core/loader/FrameLoadRequest.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderStateMachine.h"
-#include "core/page/DOMWindow.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
-#include <wtf/CurrentTime.h>
+#include "wtf/CurrentTime.h"
 
 namespace WebCore {
 
@@ -78,6 +75,7 @@
 
     double delay() const { return m_delay; }
     bool lockBackForwardList() const { return m_lockBackForwardList; }
+    void setLockBackForwardList(bool lockBackForwardList) { m_lockBackForwardList = lockBackForwardList; }
     bool wasDuringLoad() const { return m_wasDuringLoad; }
     bool isLocationChange() const { return m_isLocationChange; }
     PassOwnPtr<UserGestureIndicator> createUserGestureIndicator()
@@ -124,6 +122,8 @@
 
         OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
         frame->loader()->clientRedirected(KURL(ParsedURLString, m_url), delay(), currentTime() + timer->nextFireInterval());
+        if (frame->loader()->history()->currentItemShouldBeReplaced())
+            setLockBackForwardList(true);
     }
 
     virtual void didStopTimer(Frame* frame)
@@ -250,6 +250,8 @@
 
         OwnPtr<UserGestureIndicator> gestureIndicator = createUserGestureIndicator();
         frame->loader()->clientRedirected(m_submission->requestURL(), delay(), currentTime() + timer->nextFireInterval());
+        if (frame->loader()->history()->currentItemShouldBeReplaced())
+            setLockBackForwardList(true);
     }
 
     virtual void didStopTimer(Frame* frame)
diff --git a/Source/core/loader/PingLoader.cpp b/Source/core/loader/PingLoader.cpp
index 2968fe7..4ec9a72 100644
--- a/Source/core/loader/PingLoader.cpp
+++ b/Source/core/loader/PingLoader.cpp
@@ -32,22 +32,19 @@
 #include "config.h"
 #include "core/loader/PingLoader.h"
 
-#include <wtf/OwnPtr.h>
-#include <wtf/text/CString.h>
-#include <wtf/UnusedParam.h>
 #include "core/dom/Document.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/FrameLoaderClient.h"
 #include "core/loader/UniqueIdentifier.h"
 #include "core/page/Frame.h"
-#include "core/page/Page.h"
 #include "core/platform/network/FormData.h"
 #include "core/platform/network/ResourceHandle.h"
 #include "core/platform/network/ResourceRequest.h"
 #include "core/platform/network/ResourceResponse.h"
 #include "weborigin/SecurityOrigin.h"
 #include "weborigin/SecurityPolicy.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/UnusedParam.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/Prerenderer.h b/Source/core/loader/Prerenderer.h
index 5db3750..91259f7 100644
--- a/Source/core/loader/Prerenderer.h
+++ b/Source/core/loader/Prerenderer.h
@@ -34,11 +34,9 @@
 
 #include "core/dom/ActiveDOMObject.h"
 #include "weborigin/KURL.h"
-#include "wtf/OwnPtr.h"
 #include "wtf/PassOwnPtr.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefPtr.h"
-#include "wtf/SinglyLinkedList.h"
 #include "wtf/Vector.h"
 
 namespace WebCore {
diff --git a/Source/core/loader/PrerendererClient.h b/Source/core/loader/PrerendererClient.h
index 8756738..4a9eafe 100644
--- a/Source/core/loader/PrerendererClient.h
+++ b/Source/core/loader/PrerendererClient.h
@@ -33,7 +33,6 @@
 #define PrerendererClient_h
 
 #include "core/platform/Supplementable.h"
-#include <wtf/PassRefPtr.h>
 
 namespace WebCore {
 
diff --git a/Source/core/loader/ProgressTracker.cpp b/Source/core/loader/ProgressTracker.cpp
index 349ae67..d3520ae 100644
--- a/Source/core/loader/ProgressTracker.cpp
+++ b/Source/core/loader/ProgressTracker.cpp
@@ -27,15 +27,14 @@
 #include "core/loader/ProgressTracker.h"
 
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/loader/DocumentLoader.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/platform/Logging.h"
 #include "core/platform/network/ResourceResponse.h"
-#include <wtf/CurrentTime.h>
-#include <wtf/text/CString.h>
+#include "wtf/CurrentTime.h"
+#include "wtf/text/CString.h"
 
 using std::min;
 
diff --git a/Source/core/loader/ResourceLoadNotifier.cpp b/Source/core/loader/ResourceLoadNotifier.cpp
index 1d3aba8..a28d931 100644
--- a/Source/core/loader/ResourceLoadNotifier.cpp
+++ b/Source/core/loader/ResourceLoadNotifier.cpp
@@ -36,7 +36,6 @@
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
 #include "core/loader/ProgressTracker.h"
-#include "core/loader/ResourceLoader.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 
diff --git a/Source/core/loader/ResourceLoader.cpp b/Source/core/loader/ResourceLoader.cpp
index 7cbc6ea..ca965c8 100644
--- a/Source/core/loader/ResourceLoader.cpp
+++ b/Source/core/loader/ResourceLoader.cpp
@@ -269,7 +269,7 @@
 
     ASSERT(!request.isNull());
     if (!redirectResponse.isNull()) {
-        if (!m_documentLoader->cachedResourceLoader()->canRequest(m_resource->type(), request.url(), m_options.contentSecurityPolicyOption)) {
+        if (!m_documentLoader->cachedResourceLoader()->canRequest(m_resource->type(), request.url(), m_options)) {
             cancel();
             return;
         }
diff --git a/Source/core/loader/ResourceLoader.h b/Source/core/loader/ResourceLoader.h
index 364dd1f..9582dac 100644
--- a/Source/core/loader/ResourceLoader.h
+++ b/Source/core/loader/ResourceLoader.h
@@ -30,13 +30,12 @@
 #define ResourceLoader_h
 
 #include "core/loader/ResourceLoaderOptions.h"
-#include "core/loader/ResourceLoaderTypes.h"
 #include "core/platform/network/ResourceHandleClient.h"
 #include "core/platform/network/ResourceRequest.h"
 #include "core/platform/network/ResourceResponse.h"
 
-#include <wtf/Forward.h>
-#include <wtf/RefCounted.h>
+#include "wtf/Forward.h"
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/ResourceLoaderOptions.h b/Source/core/loader/ResourceLoaderOptions.h
index 155757e..a0836d3 100644
--- a/Source/core/loader/ResourceLoaderOptions.h
+++ b/Source/core/loader/ResourceLoaderOptions.h
@@ -66,6 +66,12 @@
     DoNotCheckContentSecurityPolicy
 };
 
+enum RequestOriginPolicy {
+    UseDefaultOriginRestrictionsForType,
+    RestrictToSameOrigin,
+    PotentiallyCrossOriginEnabled // Indicates "potentially CORS-enabled fetch" in HTML standard.
+};
+
 struct ResourceLoaderOptions {
     ResourceLoaderOptions()
         : sendLoadCallbacks(DoNotSendCallbacks)
@@ -75,7 +81,10 @@
         , credentialsRequested(ClientDidNotRequestCredentials)
         , crossOriginCredentialPolicy(DoNotAskClientForCrossOriginCredentials)
         , securityCheck(DoSecurityCheck)
-        , contentSecurityPolicyOption(CheckContentSecurityPolicy) { }
+        , contentSecurityPolicyOption(CheckContentSecurityPolicy)
+        , requestOriginPolicy(UseDefaultOriginRestrictionsForType)
+    {
+    }
 
     ResourceLoaderOptions(
         SendCallbackPolicy sendLoadCallbacks,
@@ -85,7 +94,8 @@
         CredentialRequest credentialsRequested,
         ClientCrossOriginCredentialPolicy crossOriginCredentialPolicy,
         SecurityCheckPolicy securityCheck,
-        ContentSecurityPolicyCheck contentSecurityPolicyOption)
+        ContentSecurityPolicyCheck contentSecurityPolicyOption,
+        RequestOriginPolicy requestOriginPolicy)
         : sendLoadCallbacks(sendLoadCallbacks)
         , sniffContent(sniffContent)
         , dataBufferingPolicy(dataBufferingPolicy)
@@ -94,6 +104,7 @@
         , crossOriginCredentialPolicy(crossOriginCredentialPolicy)
         , securityCheck(securityCheck)
         , contentSecurityPolicyOption(contentSecurityPolicyOption)
+        , requestOriginPolicy(requestOriginPolicy)
     {
     }
     SendCallbackPolicy sendLoadCallbacks;
@@ -105,6 +116,7 @@
     SecurityCheckPolicy securityCheck;
     ContentSecurityPolicyCheck contentSecurityPolicyOption;
     CachedResourceInitiatorInfo initiatorInfo;
+    RequestOriginPolicy requestOriginPolicy;
 };
 
 } // namespace WebCore
diff --git a/Source/core/loader/ResourceLoaderTypes.h b/Source/core/loader/ResourceLoaderTypes.h
deleted file mode 100644
index e85c3c2..0000000
--- a/Source/core/loader/ResourceLoaderTypes.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ResourceLoaderTypes_h
-#define ResourceLoaderTypes_h
-
-namespace WebCore {
-
-// DataPayloadType describes the nature of an invocation of the ResourceLoader::didReceiveData callback.
-//  - DataPayloadWholeResource indicates that the buffer points to a whole resource. There will only be one such didReceiveData callback for the load.
-//  - DataPayloadBytes indicates that the buffer points to a range of bytes, which may or may not be a whole resource.
-//    There may have been previous didReceieveData callbacks, and there may be future didReceieveData callbacks.
-
-enum DataPayloadType {
-    DataPayloadWholeResource,
-    DataPayloadBytes,
-};
-
-} // namespace WebCore
-
-#endif // ResourceLoaderTypes_h
diff --git a/Source/core/loader/SinkDocument.cpp b/Source/core/loader/SinkDocument.cpp
index 8a0b5e3..a4464ab 100644
--- a/Source/core/loader/SinkDocument.cpp
+++ b/Source/core/loader/SinkDocument.cpp
@@ -44,7 +44,7 @@
     }
 
     // Ignore all data.
-    virtual void appendBytes(DocumentWriter*, const char*, size_t) { }
+    virtual size_t appendBytes(const char*, size_t) OVERRIDE { return 0; }
 };
 
 SinkDocument::SinkDocument(Frame* frame, const KURL& url)
diff --git a/Source/core/loader/SubframeLoader.cpp b/Source/core/loader/SubframeLoader.cpp
index d36cdb9..1c7e25b 100644
--- a/Source/core/loader/SubframeLoader.cpp
+++ b/Source/core/loader/SubframeLoader.cpp
@@ -41,10 +41,7 @@
 #include "core/html/PluginDocument.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/page/Chrome.h"
-#include "core/page/ChromeClient.h"
 #include "core/page/ContentSecurityPolicy.h"
-#include "core/page/DiagnosticLoggingKeys.h"
 #include "core/page/Frame.h"
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
diff --git a/Source/core/loader/SubframeLoader.h b/Source/core/loader/SubframeLoader.h
index a5b68e8..56aae81 100644
--- a/Source/core/loader/SubframeLoader.h
+++ b/Source/core/loader/SubframeLoader.h
@@ -32,11 +32,10 @@
 #define SubframeLoader_h
 
 #include "core/loader/FrameLoaderTypes.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/Vector.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/TextResourceDecoder.cpp b/Source/core/loader/TextResourceDecoder.cpp
index bffc89c..b245b7f 100644
--- a/Source/core/loader/TextResourceDecoder.cpp
+++ b/Source/core/loader/TextResourceDecoder.cpp
@@ -27,7 +27,6 @@
 #include "core/dom/DOMImplementation.h"
 #include "core/html/parser/HTMLMetaCharsetParser.h"
 #include "core/platform/text/TextEncodingDetector.h"
-#include "wtf/ASCIICType.h"
 #include "wtf/StringExtras.h"
 #include "wtf/text/TextCodec.h"
 #include "wtf/text/TextEncoding.h"
diff --git a/Source/core/loader/TextResourceDecoderBuilder.cpp b/Source/core/loader/TextResourceDecoderBuilder.cpp
new file mode 100644
index 0000000..1ad3782
--- /dev/null
+++ b/Source/core/loader/TextResourceDecoderBuilder.cpp
@@ -0,0 +1,107 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/loader/TextResourceDecoderBuilder.h"
+
+#include "core/dom/Document.h"
+#include "core/page/Frame.h"
+#include "core/page/Settings.h"
+#include "weborigin/SecurityOrigin.h"
+
+namespace WebCore {
+
+static inline bool canReferToParentFrameEncoding(const Frame* frame, const Frame* parentFrame)
+{
+    return parentFrame && parentFrame->document()->securityOrigin()->canAccess(frame->document()->securityOrigin());
+}
+
+
+TextResourceDecoderBuilder::TextResourceDecoderBuilder(const String& mimeType, const String& encoding, bool encodingUserChoosen)
+    : m_mimeType(mimeType)
+    , m_encoding(encoding)
+    , m_encodingWasChosenByUser(encodingUserChoosen)
+{
+}
+
+TextResourceDecoderBuilder::~TextResourceDecoderBuilder()
+{
+}
+
+
+inline PassRefPtr<TextResourceDecoder> TextResourceDecoderBuilder::createDecoderInstance(Document* document)
+{
+    if (Frame* frame = document->frame()) {
+        if (Settings* settings = frame->settings())
+            return TextResourceDecoder::create(m_mimeType, settings->defaultTextEncodingName(), settings->usesEncodingDetector());
+    }
+
+    return TextResourceDecoder::create(m_mimeType, String());
+}
+
+inline void TextResourceDecoderBuilder::setupEncoding(TextResourceDecoder* decoder, Document* document)
+{
+    Frame* frame = document->frame();
+    Frame* parentFrame = frame ? frame->tree()->parent() : 0;
+
+    if (!m_encoding.isEmpty())
+        decoder->setEncoding(m_encoding, m_encodingWasChosenByUser ? TextResourceDecoder::UserChosenEncoding : TextResourceDecoder::EncodingFromHTTPHeader);
+
+    // Set the hint encoding to the parent frame encoding only if
+    // the parent and the current frames share the security origin.
+    // We impose this condition because somebody can make a child frameg63
+    // containing a carefully crafted html/javascript in one encoding
+    // that can be mistaken for hintEncoding (or related encoding) by
+    // an auto detector. When interpreted in the latter, it could be
+    // an attack vector.
+    // FIXME: This might be too cautious for non-7bit-encodings and
+    // we may consider relaxing this later after testing.
+    if (frame && canReferToParentFrameEncoding(frame, parentFrame)) {
+        decoder->setHintEncoding(parentFrame->document()->decoder());
+        if (m_encoding.isEmpty())
+            decoder->setEncoding(parentFrame->document()->inputEncoding(), TextResourceDecoder::EncodingFromParentFrame);
+    }
+}
+
+PassRefPtr<TextResourceDecoder> TextResourceDecoderBuilder::buildFor(Document* document)
+{
+    RefPtr<TextResourceDecoder> decoder = createDecoderInstance(document);
+    setupEncoding(decoder.get(), document);
+    document->setDecoder(decoder);
+    return decoder.release();
+}
+
+void TextResourceDecoderBuilder::clear()
+{
+    if (!m_encodingWasChosenByUser)
+        m_encoding = String();
+}
+
+}
diff --git a/Source/core/fileapi/ThreadableBlobRegistry.h b/Source/core/loader/TextResourceDecoderBuilder.h
similarity index 62%
copy from Source/core/fileapi/ThreadableBlobRegistry.h
copy to Source/core/loader/TextResourceDecoderBuilder.h
index a72b202..ba71e5a 100644
--- a/Source/core/fileapi/ThreadableBlobRegistry.h
+++ b/Source/core/loader/TextResourceDecoderBuilder.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,25 +28,40 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ThreadableBlobRegistry_h
-#define ThreadableBlobRegistry_h
+#ifndef TextResourceDecoderBuilder_h
+#define TextResourceDecoderBuilder_h
 
-#include "wtf/PassOwnPtr.h"
+#include "core/loader/TextResourceDecoder.h"
 #include "wtf/PassRefPtr.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
-class BlobData;
-class KURL;
-class SecurityOrigin;
+class Document;
+class TextResourceDecoder;
 
-class ThreadableBlobRegistry {
+class TextResourceDecoderBuilder {
 public:
-    static void registerBlobURL(const KURL&, PassOwnPtr<BlobData>);
-    static void registerBlobURL(SecurityOrigin*, const KURL&, const KURL& srcURL);
-    static void unregisterBlobURL(const KURL&);
+    TextResourceDecoderBuilder(const String& mimeType, const String& encoding, bool encodingUserChoosen);
+    ~TextResourceDecoderBuilder();
+
+    PassRefPtr<TextResourceDecoder> buildFor(Document*);
+
+    const String& mimeType() const { return m_mimeType; }
+    const String& encoding() const { return m_encoding; }
+    bool encodingWasChosenByUser() const { return m_encodingWasChosenByUser; }
+
+    void clear();
+
+private:
+    PassRefPtr<TextResourceDecoder> createDecoderInstance(Document*);
+    void setupEncoding(TextResourceDecoder*, Document*);
+
+    String m_mimeType;
+    String m_encoding;
+    bool m_encodingWasChosenByUser;
 };
 
 } // namespace WebCore
 
-#endif // ThreadableBlobRegistry_h
+#endif // TextResourceDecoderBuilder_h
diff --git a/Source/core/loader/TextTrackLoader.cpp b/Source/core/loader/TextTrackLoader.cpp
index f001e6a..6f4ee8b 100644
--- a/Source/core/loader/TextTrackLoader.cpp
+++ b/Source/core/loader/TextTrackLoader.cpp
@@ -29,7 +29,6 @@
 
 #include "core/dom/Document.h"
 #include "core/html/track/WebVTTParser.h"
-#include "core/inspector/ScriptCallStack.h"
 #include "core/loader/CrossOriginAccessControl.h"
 #include "core/loader/cache/CachedResourceLoader.h"
 #include "core/loader/cache/CachedResourceRequest.h"
@@ -37,7 +36,6 @@
 #include "core/loader/cache/CachedTextTrack.h"
 #include "core/platform/Logging.h"
 #include "core/platform/SharedBuffer.h"
-#include "core/platform/network/ResourceHandle.h"
 #include "weborigin/SecurityOrigin.h"
 
 namespace WebCore {
diff --git a/Source/core/loader/ThreadableLoader.cpp b/Source/core/loader/ThreadableLoader.cpp
index f766fe9..9af52fc 100644
--- a/Source/core/loader/ThreadableLoader.cpp
+++ b/Source/core/loader/ThreadableLoader.cpp
@@ -35,7 +35,7 @@
 #include "core/dom/ScriptExecutionContext.h"
 #include "core/loader/DocumentThreadableLoader.h"
 #include "core/loader/WorkerThreadableLoader.h"
-#include "core/workers/WorkerContext.h"
+#include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerRunLoop.h"
 
 namespace WebCore {
@@ -45,8 +45,8 @@
     ASSERT(client);
     ASSERT(context);
 
-    if (context->isWorkerContext())
-        return WorkerThreadableLoader::create(static_cast<WorkerContext*>(context), client, WorkerRunLoop::defaultMode(), request, options);
+    if (context->isWorkerGlobalScope())
+        return WorkerThreadableLoader::create(toWorkerGlobalScope(context), client, WorkerRunLoop::defaultMode(), request, options);
 
     return DocumentThreadableLoader::create(toDocument(context), client, request, options);
 }
@@ -55,8 +55,8 @@
 {
     ASSERT(context);
 
-    if (context->isWorkerContext()) {
-        WorkerThreadableLoader::loadResourceSynchronously(static_cast<WorkerContext*>(context), request, client, options);
+    if (context->isWorkerGlobalScope()) {
+        WorkerThreadableLoader::loadResourceSynchronously(toWorkerGlobalScope(context), request, client, options);
         return;
     }
 
diff --git a/Source/core/loader/ThreadableLoader.h b/Source/core/loader/ThreadableLoader.h
index 695d049..b5f5f68 100644
--- a/Source/core/loader/ThreadableLoader.h
+++ b/Source/core/loader/ThreadableLoader.h
@@ -33,11 +33,9 @@
 
 #include "core/loader/ResourceLoaderOptions.h"
 #include "weborigin/SecurityOrigin.h"
-#include "core/platform/network/ResourceHandle.h"
-#include <wtf/Noncopyable.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/Noncopyable.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/WorkerThreadableLoader.cpp b/Source/core/loader/WorkerThreadableLoader.cpp
index 1b2f38c..b0abbf8 100644
--- a/Source/core/loader/WorkerThreadableLoader.cpp
+++ b/Source/core/loader/WorkerThreadableLoader.cpp
@@ -39,7 +39,7 @@
 #include "core/platform/network/ResourceError.h"
 #include "core/platform/network/ResourceRequest.h"
 #include "core/platform/network/ResourceResponse.h"
-#include "core/workers/WorkerContext.h"
+#include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerLoaderProxy.h"
 #include "core/workers/WorkerThread.h"
 #include <wtf/MainThread.h>
@@ -52,10 +52,10 @@
 
 static const char loadResourceSynchronouslyMode[] = "loadResourceSynchronouslyMode";
 
-WorkerThreadableLoader::WorkerThreadableLoader(WorkerContext* workerContext, ThreadableLoaderClient* client, const String& taskMode, const ResourceRequest& request, const ThreadableLoaderOptions& options)
-    : m_workerContext(workerContext)
+WorkerThreadableLoader::WorkerThreadableLoader(WorkerGlobalScope* workerGlobalScope, ThreadableLoaderClient* client, const String& taskMode, const ResourceRequest& request, const ThreadableLoaderOptions& options)
+    : m_workerGlobalScope(workerGlobalScope)
     , m_workerClientWrapper(ThreadableLoaderClientWrapper::create(client))
-    , m_bridge(*(new MainThreadBridge(m_workerClientWrapper, m_workerContext->thread()->workerLoaderProxy(), taskMode, request, options, workerContext->url().strippedForUseAsReferrer())))
+    , m_bridge(*(new MainThreadBridge(m_workerClientWrapper, m_workerGlobalScope->thread()->workerLoaderProxy(), taskMode, request, options, workerGlobalScope->url().strippedForUseAsReferrer())))
 {
 }
 
@@ -64,18 +64,18 @@
     m_bridge.destroy();
 }
 
-void WorkerThreadableLoader::loadResourceSynchronously(WorkerContext* workerContext, const ResourceRequest& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
+void WorkerThreadableLoader::loadResourceSynchronously(WorkerGlobalScope* workerGlobalScope, const ResourceRequest& request, ThreadableLoaderClient& client, const ThreadableLoaderOptions& options)
 {
-    WorkerRunLoop& runLoop = workerContext->thread()->runLoop();
+    WorkerRunLoop& runLoop = workerGlobalScope->thread()->runLoop();
 
     // Create a unique mode just for this synchronous resource load.
     String mode = loadResourceSynchronouslyMode;
     mode.append(String::number(runLoop.createUniqueId()));
 
-    RefPtr<WorkerThreadableLoader> loader = WorkerThreadableLoader::create(workerContext, &client, mode, request, options);
+    RefPtr<WorkerThreadableLoader> loader = WorkerThreadableLoader::create(workerGlobalScope, &client, mode, request, options);
     MessageQueueWaitResult result = MessageQueueMessageReceived;
     while (!loader->done() && result != MessageQueueTerminated)
-        result = runLoop.runInMode(workerContext, mode);
+        result = runLoop.runInMode(workerGlobalScope, mode);
 
     if (!loader->done() && result == MessageQueueTerminated)
         loader->cancel();
@@ -164,32 +164,32 @@
     m_workerClientWrapper->clearClient();
 }
 
-static void workerContextDidSendData(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
+static void workerGlobalScopeDidSendData(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
 {
-    ASSERT_UNUSED(context, context->isWorkerContext());
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
     workerClientWrapper->didSendData(bytesSent, totalBytesToBeSent);
 }
 
 void WorkerThreadableLoader::MainThreadBridge::didSendData(unsigned long long bytesSent, unsigned long long totalBytesToBeSent)
 {
-    m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidSendData, m_workerClientWrapper, bytesSent, totalBytesToBeSent), m_taskMode);
+    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidSendData, m_workerClientWrapper, bytesSent, totalBytesToBeSent), m_taskMode);
 }
 
-static void workerContextDidReceiveResponse(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long identifier, PassOwnPtr<CrossThreadResourceResponseData> responseData)
+static void workerGlobalScopeDidReceiveResponse(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long identifier, PassOwnPtr<CrossThreadResourceResponseData> responseData)
 {
-    ASSERT_UNUSED(context, context->isWorkerContext());
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
     OwnPtr<ResourceResponse> response(ResourceResponse::adopt(responseData));
     workerClientWrapper->didReceiveResponse(identifier, *response);
 }
 
 void WorkerThreadableLoader::MainThreadBridge::didReceiveResponse(unsigned long identifier, const ResourceResponse& response)
 {
-    m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveResponse, m_workerClientWrapper, identifier, response), m_taskMode);
+    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidReceiveResponse, m_workerClientWrapper, identifier, response), m_taskMode);
 }
 
-static void workerContextDidReceiveData(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, PassOwnPtr<Vector<char> > vectorData)
+static void workerGlobalScopeDidReceiveData(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, PassOwnPtr<Vector<char> > vectorData)
 {
-    ASSERT_UNUSED(context, context->isWorkerContext());
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
     workerClientWrapper->didReceiveData(vectorData->data(), vectorData->size());
 }
 
@@ -197,12 +197,12 @@
 {
     OwnPtr<Vector<char> > vector = adoptPtr(new Vector<char>(dataLength)); // needs to be an OwnPtr for usage with createCallbackTask.
     memcpy(vector->data(), data, dataLength);
-    m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveData, m_workerClientWrapper, vector.release()), m_taskMode);
+    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidReceiveData, m_workerClientWrapper, vector.release()), m_taskMode);
 }
 
-static void workerContextDidReceiveCachedMetadata(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, PassOwnPtr<Vector<char> > vectorData)
+static void workerGlobalScopeDidReceiveCachedMetadata(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, PassOwnPtr<Vector<char> > vectorData)
 {
-    ASSERT_UNUSED(context, context->isWorkerContext());
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
     workerClientWrapper->didReceiveCachedMetadata(vectorData->data(), vectorData->size());
 }
 
@@ -210,51 +210,51 @@
 {
     OwnPtr<Vector<char> > vector = adoptPtr(new Vector<char>(dataLength)); // needs to be an OwnPtr for usage with createCallbackTask.
     memcpy(vector->data(), data, dataLength);
-    m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidReceiveCachedMetadata, m_workerClientWrapper, vector.release()), m_taskMode);
+    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidReceiveCachedMetadata, m_workerClientWrapper, vector.release()), m_taskMode);
 }
 
-static void workerContextDidFinishLoading(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long identifier, double finishTime)
+static void workerGlobalScopeDidFinishLoading(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, unsigned long identifier, double finishTime)
 {
-    ASSERT_UNUSED(context, context->isWorkerContext());
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
     workerClientWrapper->didFinishLoading(identifier, finishTime);
 }
 
 void WorkerThreadableLoader::MainThreadBridge::didFinishLoading(unsigned long identifier, double finishTime)
 {
-    m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFinishLoading, m_workerClientWrapper, identifier, finishTime), m_taskMode);
+    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidFinishLoading, m_workerClientWrapper, identifier, finishTime), m_taskMode);
 }
 
-static void workerContextDidFail(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error)
+static void workerGlobalScopeDidFail(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error)
 {
-    ASSERT_UNUSED(context, context->isWorkerContext());
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
     workerClientWrapper->didFail(error);
 }
 
 void WorkerThreadableLoader::MainThreadBridge::didFail(const ResourceError& error)
 {
-    m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFail, m_workerClientWrapper, error), m_taskMode);
+    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidFail, m_workerClientWrapper, error), m_taskMode);
 }
 
-static void workerContextDidFailAccessControlCheck(ScriptExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error)
+static void workerGlobalScopeDidFailAccessControlCheck(ScriptExecutionContext* context, PassRefPtr<ThreadableLoaderClientWrapper> workerClientWrapper, const ResourceError& error)
 {
-    ASSERT_UNUSED(context, context->isWorkerContext());
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
     workerClientWrapper->didFailAccessControlCheck(error);
 }
 
 void WorkerThreadableLoader::MainThreadBridge::didFailAccessControlCheck(const ResourceError& error)
 {
-    m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFailAccessControlCheck, m_workerClientWrapper, error), m_taskMode);
+    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidFailAccessControlCheck, m_workerClientWrapper, error), m_taskMode);
 }
 
-static void workerContextDidFailRedirectCheck(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper)
+static void workerGlobalScopeDidFailRedirectCheck(ScriptExecutionContext* context, RefPtr<ThreadableLoaderClientWrapper> workerClientWrapper)
 {
-    ASSERT_UNUSED(context, context->isWorkerContext());
+    ASSERT_UNUSED(context, context->isWorkerGlobalScope());
     workerClientWrapper->didFailRedirectCheck();
 }
 
 void WorkerThreadableLoader::MainThreadBridge::didFailRedirectCheck()
 {
-    m_loaderProxy.postTaskForModeToWorkerContext(createCallbackTask(&workerContextDidFailRedirectCheck, m_workerClientWrapper), m_taskMode);
+    m_loaderProxy.postTaskForModeToWorkerGlobalScope(createCallbackTask(&workerGlobalScopeDidFailRedirectCheck, m_workerClientWrapper), m_taskMode);
 }
 
 } // namespace WebCore
diff --git a/Source/core/loader/WorkerThreadableLoader.h b/Source/core/loader/WorkerThreadableLoader.h
index a8cfab7..ac4b7d9 100644
--- a/Source/core/loader/WorkerThreadableLoader.h
+++ b/Source/core/loader/WorkerThreadableLoader.h
@@ -46,7 +46,7 @@
 
     class ResourceError;
     class ResourceRequest;
-    class WorkerContext;
+    class WorkerGlobalScope;
     class WorkerLoaderProxy;
     struct CrossThreadResourceResponseData;
     struct CrossThreadResourceRequestData;
@@ -54,10 +54,10 @@
     class WorkerThreadableLoader : public RefCounted<WorkerThreadableLoader>, public ThreadableLoader {
         WTF_MAKE_FAST_ALLOCATED;
     public:
-        static void loadResourceSynchronously(WorkerContext*, const ResourceRequest&, ThreadableLoaderClient&, const ThreadableLoaderOptions&);
-        static PassRefPtr<WorkerThreadableLoader> create(WorkerContext* workerContext, ThreadableLoaderClient* client, const String& taskMode, const ResourceRequest& request, const ThreadableLoaderOptions& options)
+        static void loadResourceSynchronously(WorkerGlobalScope*, const ResourceRequest&, ThreadableLoaderClient&, const ThreadableLoaderOptions&);
+        static PassRefPtr<WorkerThreadableLoader> create(WorkerGlobalScope* workerGlobalScope, ThreadableLoaderClient* client, const String& taskMode, const ResourceRequest& request, const ThreadableLoaderOptions& options)
         {
-            return adoptRef(new WorkerThreadableLoader(workerContext, client, taskMode, request, options));
+            return adoptRef(new WorkerThreadableLoader(workerGlobalScope, client, taskMode, request, options));
         }
 
         ~WorkerThreadableLoader();
@@ -85,7 +85,7 @@
         //
         // case 1. worker.terminate is called.
         //    In this case, no more tasks are posted from the worker object's thread to the worker
-        //    context's thread -- WorkerContextProxy implementation enforces this.
+        //    context's thread -- WorkerGlobalScopeProxy implementation enforces this.
         //
         // case 2. xhr gets aborted and the worker context continues running.
         //    The ThreadableLoaderClientWrapper has the underlying client cleared, so no more calls
@@ -133,9 +133,9 @@
             String m_taskMode;
         };
 
-        WorkerThreadableLoader(WorkerContext*, ThreadableLoaderClient*, const String& taskMode, const ResourceRequest&, const ThreadableLoaderOptions&);
+        WorkerThreadableLoader(WorkerGlobalScope*, ThreadableLoaderClient*, const String& taskMode, const ResourceRequest&, const ThreadableLoaderOptions&);
 
-        RefPtr<WorkerContext> m_workerContext;
+        RefPtr<WorkerGlobalScope> m_workerGlobalScope;
         RefPtr<ThreadableLoaderClientWrapper> m_workerClientWrapper;
         MainThreadBridge& m_bridge;
     };
diff --git a/Source/core/loader/appcache/DOMApplicationCache.h b/Source/core/loader/appcache/DOMApplicationCache.h
index 1eedf54..a20d8fa 100644
--- a/Source/core/loader/appcache/DOMApplicationCache.h
+++ b/Source/core/loader/appcache/DOMApplicationCache.h
@@ -31,12 +31,9 @@
 #include "core/dom/EventTarget.h"
 #include "core/loader/appcache/ApplicationCacheHost.h"
 #include "core/page/DOMWindowProperty.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/text/AtomicStringHash.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/archive/ArchiveResourceCollection.h b/Source/core/loader/archive/ArchiveResourceCollection.h
index ad9215f..7b5ae62 100644
--- a/Source/core/loader/archive/ArchiveResourceCollection.h
+++ b/Source/core/loader/archive/ArchiveResourceCollection.h
@@ -32,7 +32,6 @@
 #include "core/loader/archive/ArchiveResource.h"
 #include "core/loader/archive/MHTMLArchive.h"
 #include "wtf/HashMap.h"
-#include "wtf/RefCounted.h"
 #include "wtf/text/WTFString.h"
 
 namespace WebCore {
diff --git a/Source/core/loader/archive/MHTMLParser.cpp b/Source/core/loader/archive/MHTMLParser.cpp
index 13ea9cd..cf8ae64 100644
--- a/Source/core/loader/archive/MHTMLParser.cpp
+++ b/Source/core/loader/archive/MHTMLParser.cpp
@@ -35,9 +35,7 @@
 #include "core/platform/MIMETypeRegistry.h"
 #include "core/platform/network/MIMEHeader.h"
 #include "core/platform/text/QuotedPrintable.h"
-#include <wtf/HashMap.h>
-#include <wtf/NotFound.h>
-#include <wtf/text/Base64.h>
+#include "wtf/text/Base64.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/CachedCSSStyleSheet.cpp b/Source/core/loader/cache/CachedCSSStyleSheet.cpp
index 1836871..d7aee75 100644
--- a/Source/core/loader/cache/CachedCSSStyleSheet.cpp
+++ b/Source/core/loader/cache/CachedCSSStyleSheet.cpp
@@ -32,11 +32,10 @@
 #include "core/loader/TextResourceDecoder.h"
 #include "core/loader/cache/CachedResourceClientWalker.h"
 #include "core/loader/cache/CachedStyleSheetClient.h"
-#include "core/loader/cache/MemoryCache.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/platform/network/HTTPParsers.h"
-#include <wtf/CurrentTime.h>
-#include <wtf/Vector.h>
+#include "wtf/CurrentTime.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/CachedCSSStyleSheet.h b/Source/core/loader/cache/CachedCSSStyleSheet.h
index bc2160d..e1cbf0d 100644
--- a/Source/core/loader/cache/CachedCSSStyleSheet.h
+++ b/Source/core/loader/cache/CachedCSSStyleSheet.h
@@ -27,7 +27,6 @@
 #define CachedCSSStyleSheet_h
 
 #include "core/loader/cache/CachedResource.h"
-#include <wtf/Vector.h>
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/CachedFont.cpp b/Source/core/loader/cache/CachedFont.cpp
index 77ac964..129de3e 100644
--- a/Source/core/loader/cache/CachedFont.cpp
+++ b/Source/core/loader/cache/CachedFont.cpp
@@ -31,20 +31,15 @@
 #include "core/loader/TextResourceDecoder.h"
 #include "core/loader/cache/CachedResourceClient.h"
 #include "core/loader/cache/CachedResourceClientWalker.h"
-#include "core/loader/cache/CachedResourceLoader.h"
-#include "core/loader/cache/MemoryCache.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/platform/graphics/FontCustomPlatformData.h"
 #include "core/platform/graphics/FontPlatformData.h"
-#include <wtf/Vector.h>
 
 #if ENABLE(SVG_FONTS)
 #include "SVGNames.h"
 #include "core/dom/NodeList.h"
 #include "core/svg/SVGDocument.h"
-#include "core/svg/SVGElement.h"
 #include "core/svg/SVGFontElement.h"
-#include "core/svg/SVGGElement.h"
 #endif
 
 namespace WebCore {
diff --git a/Source/core/loader/cache/CachedImage.cpp b/Source/core/loader/cache/CachedImage.cpp
index 8409b0c..efdd5d6 100644
--- a/Source/core/loader/cache/CachedImage.cpp
+++ b/Source/core/loader/cache/CachedImage.cpp
@@ -24,7 +24,6 @@
 #include "config.h"
 #include "core/loader/cache/CachedImage.h"
 
-#include "RuntimeEnabledFeatures.h"
 #include "core/loader/cache/CachedImageClient.h"
 #include "core/loader/cache/CachedResourceClient.h"
 #include "core/loader/cache/CachedResourceClientWalker.h"
@@ -281,9 +280,7 @@
 void CachedImage::setCustomAcceptHeader()
 {
     DEFINE_STATIC_LOCAL(const AtomicString, acceptWebP, ("image/webp,*/*;q=0.8", AtomicString::ConstructFromLiteral));
-
-    if (RuntimeEnabledFeatures::webPInAcceptHeaderEnabled())
-        setAccept(acceptWebP);
+    setAccept(acceptWebP);
 }
 
 inline void CachedImage::createImage()
diff --git a/Source/core/loader/cache/CachedImage.h b/Source/core/loader/cache/CachedImage.h
index 1f8b084..e3d4320 100644
--- a/Source/core/loader/cache/CachedImage.h
+++ b/Source/core/loader/cache/CachedImage.h
@@ -29,8 +29,7 @@
 #include "core/platform/graphics/IntSizeHash.h"
 #include "core/platform/graphics/LayoutSize.h"
 #include "core/svg/graphics/SVGImageCache.h"
-#include <wtf/HashMap.h>
-#include <wtf/Vector.h>
+#include "wtf/HashMap.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/CachedImageTest.cpp b/Source/core/loader/cache/CachedImageTest.cpp
index 1468726..8781434 100644
--- a/Source/core/loader/cache/CachedImageTest.cpp
+++ b/Source/core/loader/cache/CachedImageTest.cpp
@@ -31,10 +31,22 @@
 #include "config.h"
 #include "core/loader/cache/CachedImage.h"
 
+#include "core/loader/DocumentLoader.h"
+#include "core/loader/EmptyClients.h"
 #include "core/loader/cache/CachedImageClient.h"
 #include "core/loader/cache/CachedResourceHandle.h"
+#include "core/loader/cache/CachedResourceLoader.h"
+#include "core/loader/cache/MemoryCache.h"
+#include "core/page/Frame.h"
+#include "core/page/FrameView.h"
+#include "core/page/Page.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/platform/graphics/Image.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebThread.h"
+#include "public/platform/WebURL.h"
+#include "public/platform/WebURLResponse.h"
+#include "public/platform/WebUnitTestSupport.h"
 #include <gtest/gtest.h>
 
 using namespace WebCore;
@@ -69,6 +81,20 @@
     bool m_notifyFinishedCalled;
 };
 
+class QuitTask : public WebKit::WebThread::Task {
+public:
+    virtual void run()
+    {
+        WebKit::Platform::current()->currentThread()->exitRunLoop();
+    }
+};
+
+void runPendingTasks()
+{
+    WebKit::Platform::current()->currentThread()->postTask(new QuitTask);
+    WebKit::Platform::current()->currentThread()->enterRunLoop();
+}
+
 TEST(CachedImageTest, MultipartImage)
 {
     CachedResourceHandle<CachedImage> cachedImage = new CachedImage(ResourceRequest());
@@ -113,4 +139,48 @@
     ASSERT_TRUE(client.notifyFinishedCalled());
 }
 
+TEST(CachedImageTest, CancelOnDetach)
+{
+    KURL testURL(ParsedURLString, "http://www.test.com/cancelTest.html");
+
+    WebKit::WebURLResponse response;
+    response.initialize();
+    response.setMIMEType("text/html");
+    WTF::String localPath = WebKit::Platform::current()->unitTestSupport()->webKitRootDir();
+    localPath.append("/Source/WebKit/chromium/tests/data/cancelTest.html");
+    WebKit::Platform::current()->unitTestSupport()->registerMockedURL(testURL, response, localPath);
+
+    // Create enough of a mocked world to get a functioning ResourceLoader.
+    Page::PageClients pageClients;
+    fillWithEmptyClients(pageClients);
+    EmptyFrameLoaderClient frameLoaderClient;
+    Page page(pageClients);
+    RefPtr<Frame> frame = Frame::create(&page, 0, &frameLoaderClient);
+    frame->setView(FrameView::create(frame.get()));
+    frame->init();
+    RefPtr<DocumentLoader> documentLoader = DocumentLoader::create(ResourceRequest(testURL), SubstituteData());
+    documentLoader->setFrame(frame.get());
+
+    // Emulate starting a real load.
+    CachedResourceHandle<CachedImage> cachedImage = new CachedImage(ResourceRequest(testURL));
+    cachedImage->load(documentLoader->cachedResourceLoader(), ResourceLoaderOptions());
+    memoryCache()->add(cachedImage.get());
+
+    MockCachedImageClient client;
+    cachedImage->addClient(&client);
+    EXPECT_EQ(CachedResource::Pending, cachedImage->status());
+
+    // The load should still be alive, but a timer should be started to cancel the load inside removeClient().
+    cachedImage->removeClient(&client);
+    EXPECT_EQ(CachedResource::Pending, cachedImage->status());
+    EXPECT_NE(reinterpret_cast<CachedResource*>(0), memoryCache()->resourceForURL(testURL));
+
+    // Trigger the cancel timer, ensure the load was cancelled and the resource was evicted from the cache.
+    runPendingTasks();
+    EXPECT_EQ(CachedResource::LoadError, cachedImage->status());
+    EXPECT_EQ(reinterpret_cast<CachedResource*>(0), memoryCache()->resourceForURL(testURL));
+
+    WebKit::Platform::current()->unitTestSupport()->unregisterMockedURL(testURL);
+}
+
 } // namespace
diff --git a/Source/core/loader/cache/CachedRawResource.cpp b/Source/core/loader/cache/CachedRawResource.cpp
index b777962..bee1e68 100644
--- a/Source/core/loader/cache/CachedRawResource.cpp
+++ b/Source/core/loader/cache/CachedRawResource.cpp
@@ -32,7 +32,6 @@
 #include "core/loader/cache/CachedResourceClientWalker.h"
 #include "core/loader/cache/CachedResourceLoader.h"
 #include "core/platform/SharedBuffer.h"
-#include <wtf/PassRefPtr.h>
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/CachedResource.cpp b/Source/core/loader/cache/CachedResource.cpp
index e41d4db..f2220a2 100644
--- a/Source/core/loader/cache/CachedResource.cpp
+++ b/Source/core/loader/cache/CachedResource.cpp
@@ -24,12 +24,10 @@
 #include "config.h"
 #include "core/loader/cache/CachedResource.h"
 
-#include "core/dom/Document.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/CachedMetadata.h"
 #include "core/loader/CrossOriginAccessControl.h"
-#include "core/loader/DocumentLoader.h"
 #include "core/loader/ResourceLoader.h"
 #include "core/loader/cache/CachedResourceClient.h"
 #include "core/loader/cache/CachedResourceClientWalker.h"
@@ -169,10 +167,7 @@
 
 void CachedResource::failBeforeStarting()
 {
-    // FIXME: What if resources in other frames were waiting for this revalidation?
     LOG(ResourceLoading, "Cannot start loading '%s'", url().string().latin1().data());
-    if (m_resourceToRevalidate) 
-        revalidationFailed();
     error(CachedResource::LoadError);
 }
 
@@ -235,6 +230,9 @@
     if (m_resourceToRevalidate)
         revalidationFailed();
 
+    if (!m_error.isNull() && (m_error.isCancellation() || !isPreloaded()))
+        memoryCache()->remove(this);
+
     setStatus(status);
     ASSERT(errorOccurred());
     m_data.clear();
@@ -447,6 +445,8 @@
 
 void CachedResource::allClientsRemoved()
 {
+    if (!m_loader)
+        return;
     if (m_type == MainResource || m_type == RawResource)
         cancelTimerFired(&m_cancelTimer);
     else if (!m_cancelTimer.isActive())
@@ -459,6 +459,8 @@
     if (hasClients() || !m_loader)
         return;
     m_loader->cancelIfNotFinishing();
+    if (m_status != Cached)
+        memoryCache()->remove(this);
 }
 
 void CachedResource::destroyDecodedDataIfNeeded()
@@ -696,8 +698,6 @@
     LOG(ResourceLoading, "Revalidation failed for %p", this);
     ASSERT(resourceToRevalidate());
     clearResourceToRevalidate();
-    if (!m_error.isNull() && (m_error.isCancellation() || !isPreloaded()))
-        memoryCache()->remove(this);
 }
 
 void CachedResource::updateForAccess()
diff --git a/Source/core/loader/cache/CachedResource.h b/Source/core/loader/cache/CachedResource.h
index 32677bb..e78d903 100644
--- a/Source/core/loader/cache/CachedResource.h
+++ b/Source/core/loader/cache/CachedResource.h
@@ -23,8 +23,6 @@
 #ifndef CachedResource_h
 #define CachedResource_h
 
-#include <time.h>
-#include "core/loader/FrameLoaderTypes.h"
 #include "core/loader/ResourceLoaderOptions.h"
 #include "core/loader/cache/CachePolicy.h"
 #include "core/platform/Timer.h"
@@ -32,11 +30,10 @@
 #include "core/platform/network/ResourceLoadPriority.h"
 #include "core/platform/network/ResourceRequest.h"
 #include "core/platform/network/ResourceResponse.h"
-#include <wtf/HashCountedSet.h>
-#include <wtf/HashSet.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Vector.h>
+#include "wtf/HashCountedSet.h"
+#include "wtf/HashSet.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -104,6 +101,7 @@
     ResourceRequest& resourceRequest() { return m_resourceRequest; }
     const KURL& url() const { return m_resourceRequest.url();}
     Type type() const { return static_cast<Type>(m_type); }
+    const ResourceLoaderOptions& options() const {  return m_options; }
 
     void didChangePriority(ResourceLoadPriority);
 
@@ -162,6 +160,7 @@
     // FIXME: Remove the stringless variant once all the callsites' error messages are updated.
     bool passesAccessControlCheck(SecurityOrigin*);
     bool passesAccessControlCheck(SecurityOrigin*, String& errorDescription);
+    bool canBeAccessedBy(SecurityOrigin*, String& error);
 
     // Called by the cache if the object has been removed from the cache
     // while still being referenced. This means the object should delete itself
diff --git a/Source/core/loader/cache/CachedResourceLoader.cpp b/Source/core/loader/cache/CachedResourceLoader.cpp
index 2a3f01e..a534f01 100644
--- a/Source/core/loader/cache/CachedResourceLoader.cpp
+++ b/Source/core/loader/cache/CachedResourceLoader.cpp
@@ -27,12 +27,6 @@
 #include "config.h"
 #include "core/loader/cache/CachedResourceLoader.h"
 
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/MemoryInstrumentationHashSet.h>
-#include <wtf/MemoryInstrumentationListHashSet.h>
-#include <wtf/text/CString.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/UnusedParam.h>
 #include "bindings/v8/ScriptController.h"
 #include "core/dom/Document.h"
 #include "core/html/HTMLElement.h"
@@ -53,7 +47,6 @@
 #include "core/loader/cache/CachedTextTrack.h"
 #include "core/loader/cache/CachedXSLStyleSheet.h"
 #include "core/loader/cache/MemoryCache.h"
-#include "core/page/Console.h"
 #include "core/page/ContentSecurityPolicy.h"
 #include "core/page/DOMWindow.h"
 #include "core/page/Frame.h"
@@ -64,6 +57,11 @@
 #include "public/platform/WebURL.h"
 #include "weborigin/SecurityOrigin.h"
 #include "weborigin/SecurityPolicy.h"
+#include "wtf/MemoryInstrumentationHashMap.h"
+#include "wtf/MemoryInstrumentationHashSet.h"
+#include "wtf/MemoryInstrumentationListHashSet.h"
+#include "wtf/text/CString.h"
+#include "wtf/text/WTFString.h"
 
 #define PRELOAD_DEBUG 0
 
@@ -198,7 +196,7 @@
     if (Frame* f = frame()) {
         if (f->loader()->pageDismissalEventBeingDispatched() != FrameLoader::NoDismissal) {
             KURL requestURL = request.resourceRequest().url();
-            if (requestURL.isValid() && canRequest(CachedResource::ImageResource, requestURL, CheckContentSecurityPolicy))
+            if (requestURL.isValid() && canRequest(CachedResource::ImageResource, requestURL, request.options(), request.forPreload()))
                 PingLoader::loadImage(f, requestURL);
             return 0;
         }
@@ -253,7 +251,7 @@
         memoryCache()->remove(existing);
     }
 
-    request.setOptions(ResourceLoaderOptions(DoNotSendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck, CheckContentSecurityPolicy));
+    request.setOptions(ResourceLoaderOptions(DoNotSendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, SkipSecurityCheck, CheckContentSecurityPolicy, UseDefaultOriginRestrictionsForType));
     return static_cast<CachedCSSStyleSheet*>(requestResource(CachedResource::CSSStyleSheet, request).get());
 }
 
@@ -324,7 +322,7 @@
     return true;
 }
 
-bool CachedResourceLoader::canRequest(CachedResource::Type type, const KURL& url, ContentSecurityPolicyCheck contentSecurityPolicyCheck, bool forPreload)
+bool CachedResourceLoader::canRequest(CachedResource::Type type, const KURL& url, const ResourceLoaderOptions& options, bool forPreload)
 {
     if (document() && !document()->securityOrigin()->canDisplay(url)) {
         if (!forPreload)
@@ -334,7 +332,7 @@
     }
 
     // FIXME: Convert this to check the isolated world's Content Security Policy once webkit.org/b/104520 is solved.
-    bool shouldBypassMainWorldContentSecurityPolicy = (frame() && frame()->script()->shouldBypassMainWorldContentSecurityPolicy()) || (contentSecurityPolicyCheck == DoNotCheckContentSecurityPolicy);
+    bool shouldBypassMainWorldContentSecurityPolicy = (frame() && frame()->script()->shouldBypassMainWorldContentSecurityPolicy()) || (options.contentSecurityPolicyOption == DoNotCheckContentSecurityPolicy);
 
     // Some types of resources can be loaded only from the same origin.  Other
     // types of resources, like Images, Scripts, and CSS, can be loaded from
@@ -350,8 +348,12 @@
     case CachedResource::LinkSubresource:
     case CachedResource::TextTrackResource:
     case CachedResource::ShaderResource:
-        // These types of resources can be loaded from any origin.
+        // By default these types of resources can be loaded from any origin.
         // FIXME: Are we sure about CachedResource::FontResource?
+        if (options.requestOriginPolicy == RestrictToSameOrigin && !m_document->securityOrigin()->canRequest(url)) {
+            printAccessDeniedMessage(url);
+            return false;
+        }
         break;
     case CachedResource::SVGDocumentResource:
     case CachedResource::XSLStyleSheet:
@@ -419,6 +421,31 @@
     return true;
 }
 
+bool CachedResourceLoader::canAccess(CachedResource* resource)
+{
+    // Redirects can change the response URL different from one of request.
+    if (!canRequest(resource->type(), resource->response().url(), resource->options(), false))
+        return false;
+
+    String error;
+    switch (resource->type()) {
+    case CachedResource::Script:
+        if (resource->options().requestOriginPolicy == PotentiallyCrossOriginEnabled
+            && !m_document->securityOrigin()->canRequest(resource->response().url())
+            && !resource->passesAccessControlCheck(m_document->securityOrigin(), error)) {
+            m_document->addConsoleMessage(JSMessageSource, ErrorMessageLevel, "Script from origin '" + SecurityOrigin::create(resource->response().url())->toString() + "' has been blocked from loading by Cross-Origin Resource Sharing policy: " + error);
+            return false;
+        }
+
+        break;
+    default:
+        ASSERT_NOT_REACHED(); // FIXME: generalize to non-script resources
+        return false;
+    }
+
+    return true;
+}
+
 CachedResourceHandle<CachedResource> CachedResourceLoader::requestResource(CachedResource::Type type, CachedResourceRequest& request)
 {
     KURL url = request.resourceRequest().url();
@@ -431,7 +458,7 @@
     if (!url.isValid())
         return 0;
 
-    if (!canRequest(type, url, request.options().contentSecurityPolicyOption, request.forPreload()))
+    if (!canRequest(type, url, request.options(), request.forPreload()))
         return 0;
 
     if (Frame* f = frame())
@@ -1112,7 +1139,7 @@
 
 const ResourceLoaderOptions& CachedResourceLoader::defaultCachedResourceOptions()
 {
-    DEFINE_STATIC_LOCAL(ResourceLoaderOptions, options, (SendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, DoSecurityCheck, CheckContentSecurityPolicy));
+    DEFINE_STATIC_LOCAL(ResourceLoaderOptions, options, (SendCallbacks, SniffContent, BufferData, AllowStoredCredentials, ClientRequestedCredentials, AskClientForCrossOriginCredentials, DoSecurityCheck, CheckContentSecurityPolicy, UseDefaultOriginRestrictionsForType));
     return options;
 }
 
diff --git a/Source/core/loader/cache/CachedResourceLoader.h b/Source/core/loader/cache/CachedResourceLoader.h
index 027ecd1..5ff24d9 100644
--- a/Source/core/loader/cache/CachedResourceLoader.h
+++ b/Source/core/loader/cache/CachedResourceLoader.h
@@ -32,12 +32,11 @@
 #include "core/loader/cache/CachedResourceInitiatorInfo.h"
 #include "core/loader/cache/CachedResourceRequest.h"
 #include "core/platform/Timer.h"
-#include "core/platform/network/ResourceLoadPriority.h"
-#include <wtf/Deque.h>
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/ListHashSet.h>
-#include <wtf/text/StringHash.h>
+#include "wtf/Deque.h"
+#include "wtf/HashMap.h"
+#include "wtf/HashSet.h"
+#include "wtf/ListHashSet.h"
+#include "wtf/text/StringHash.h"
 
 namespace WebCore {
 
@@ -124,8 +123,8 @@
     void preload(CachedResource::Type, CachedResourceRequest&, const String& charset);
     void checkForPendingPreloads();
     void printPreloadStats();
-    bool canRequest(CachedResource::Type, const KURL&, ContentSecurityPolicyCheck, bool forPreload = false);
-    
+    bool canRequest(CachedResource::Type, const KURL&, const ResourceLoaderOptions&, bool forPreload = false);
+    bool canAccess(CachedResource*);
     void reportMemoryUsage(MemoryObjectInfo*) const;
 
     static const ResourceLoaderOptions& defaultCachedResourceOptions();
diff --git a/Source/core/loader/cache/CachedResourceRequest.cpp b/Source/core/loader/cache/CachedResourceRequest.cpp
index 9c8b62e..9162ff5 100644
--- a/Source/core/loader/cache/CachedResourceRequest.cpp
+++ b/Source/core/loader/cache/CachedResourceRequest.cpp
@@ -27,6 +27,7 @@
 #include "core/loader/cache/CachedResourceRequest.h"
 
 #include "core/dom/Element.h"
+#include "core/loader/CrossOriginAccessControl.h"
 #include "core/loader/cache/CachedResourceInitiatorInfo.h"
 #include "core/loader/cache/CachedResourceLoader.h"
 
@@ -67,4 +68,11 @@
 {
 }
 
+void CachedResourceRequest::setPotentiallyCrossOriginEnabled(SecurityOrigin* origin, StoredCredentials allowCredentials)
+{
+    updateRequestForAccessControl(m_resourceRequest, origin, allowCredentials);
+    ASSERT(m_options.requestOriginPolicy == UseDefaultOriginRestrictionsForType); // Allows only tightening from the default value.
+    m_options.requestOriginPolicy = PotentiallyCrossOriginEnabled;
+}
+
 } // namespace WebCore
diff --git a/Source/core/loader/cache/CachedResourceRequest.h b/Source/core/loader/cache/CachedResourceRequest.h
index 20cf727..fbfcf04 100644
--- a/Source/core/loader/cache/CachedResourceRequest.h
+++ b/Source/core/loader/cache/CachedResourceRequest.h
@@ -31,11 +31,10 @@
 #include "core/loader/cache/CachedResourceInitiatorInfo.h"
 #include "core/platform/network/ResourceLoadPriority.h"
 #include "core/platform/network/ResourceRequest.h"
-#include <wtf/RefPtr.h>
-#include <wtf/text/AtomicString.h>
+#include "wtf/text/AtomicString.h"
 
 namespace WebCore {
-class Document;
+class SecurityOrigin;
 
 class CachedResourceRequest {
 public:
@@ -58,6 +57,7 @@
     DeferOption defer() const { return m_defer; }
     void setDefer(DeferOption defer) { m_defer = defer; }
     void setContentSecurityCheck(ContentSecurityPolicyCheck contentSecurityPolicyOption) { m_options.contentSecurityPolicyOption = contentSecurityPolicyOption; }
+    void setPotentiallyCrossOriginEnabled(SecurityOrigin*, StoredCredentials);
 
 private:
     ResourceRequest m_resourceRequest;
diff --git a/Source/core/loader/cache/CachedScript.cpp b/Source/core/loader/cache/CachedScript.cpp
index 0c764d0..c580e4e 100644
--- a/Source/core/loader/cache/CachedScript.cpp
+++ b/Source/core/loader/cache/CachedScript.cpp
@@ -29,11 +29,9 @@
 
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/loader/TextResourceDecoder.h"
-#include "core/loader/cache/MemoryCache.h"
 #include "core/platform/MIMETypeRegistry.h"
 #include "core/platform/SharedBuffer.h"
 #include "core/platform/network/HTTPParsers.h"
-#include <wtf/Vector.h>
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/CachedTextTrack.cpp b/Source/core/loader/cache/CachedTextTrack.cpp
index f275552..7ec45bd 100644
--- a/Source/core/loader/cache/CachedTextTrack.cpp
+++ b/Source/core/loader/cache/CachedTextTrack.cpp
@@ -29,7 +29,6 @@
 
 #include "core/loader/cache/CachedResourceClient.h"
 #include "core/loader/cache/CachedResourceClientWalker.h"
-#include <wtf/Vector.h>
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/CachedTextTrack.h b/Source/core/loader/cache/CachedTextTrack.h
index 1cc9be0..a9a7f22 100644
--- a/Source/core/loader/cache/CachedTextTrack.h
+++ b/Source/core/loader/cache/CachedTextTrack.h
@@ -27,7 +27,6 @@
 #define CachedTextTrack_h
 
 #include "core/loader/cache/CachedResource.h"
-#include "core/platform/graphics/FontOrientation.h"
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/CachedXSLStyleSheet.h b/Source/core/loader/cache/CachedXSLStyleSheet.h
index d647e67..a851bfa 100644
--- a/Source/core/loader/cache/CachedXSLStyleSheet.h
+++ b/Source/core/loader/cache/CachedXSLStyleSheet.h
@@ -27,7 +27,6 @@
 #define CachedXSLStyleSheet_h
 
 #include "core/loader/cache/CachedResource.h"
-#include <wtf/Vector.h>
 
 namespace WebCore {
 
diff --git a/Source/core/loader/cache/MemoryCache.cpp b/Source/core/loader/cache/MemoryCache.cpp
index 861c898..8e5c4cf 100644
--- a/Source/core/loader/cache/MemoryCache.cpp
+++ b/Source/core/loader/cache/MemoryCache.cpp
@@ -27,15 +27,11 @@
 #include "core/dom/CrossThreadTask.h"
 #include "core/dom/Document.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
-#include "core/loader/FrameLoader.h"
-#include "core/loader/FrameLoaderTypes.h"
 #include "core/loader/cache/CachedResource.h"
 #include "core/loader/cache/CachedResourceHandle.h"
 #include "core/page/FrameView.h"
 #include "core/platform/Logging.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/network/ResourceHandle.h"
-#include "core/workers/WorkerContext.h"
+#include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerLoaderProxy.h"
 #include "core/workers/WorkerThread.h"
 #include "weborigin/SecurityOrigin.h"
@@ -514,9 +510,9 @@
 
 void MemoryCache::removeURLFromCache(ScriptExecutionContext* context, const KURL& url)
 {
-    if (context->isWorkerContext()) {
-        WorkerContext* workerContext = static_cast<WorkerContext*>(context);
-        workerContext->thread()->workerLoaderProxy().postTaskToLoader(createCallbackTask(&removeURLFromCacheInternal, url));
+    if (context->isWorkerGlobalScope()) {
+        WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
+        workerGlobalScope->thread()->workerLoaderProxy().postTaskToLoader(createCallbackTask(&removeURLFromCacheInternal, url));
         return;
     }
     removeURLFromCacheInternal(context, url);
diff --git a/Source/core/loader/cache/MemoryCache.h b/Source/core/loader/cache/MemoryCache.h
index da6ea03..4b5faa1 100644
--- a/Source/core/loader/cache/MemoryCache.h
+++ b/Source/core/loader/cache/MemoryCache.h
@@ -25,14 +25,11 @@
 #ifndef Cache_h
 #define Cache_h
 
-#include "core/loader/cache/CachedResource.h"
-#include "weborigin/SecurityOriginHash.h"
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/text/StringHash.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Vector.h>
+#include "wtf/HashMap.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/Vector.h"
+#include "wtf/text/StringHash.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore  {
 
diff --git a/Source/core/make_derived_sources.target.darwin-arm.mk b/Source/core/make_derived_sources.target.darwin-arm.mk
index 16ead4b..c018bf8 100644
--- a/Source/core/make_derived_sources.target.darwin-arm.mk
+++ b/Source/core/make_derived_sources.target.darwin-arm.mk
@@ -72,7 +72,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp ;
 
@@ -95,7 +95,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp ;
 
@@ -106,7 +106,7 @@
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.h: $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp ;
@@ -131,7 +131,7 @@
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGNames.h" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGNames.h" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.h: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp ;
@@ -144,9 +144,9 @@
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/webkit/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/webkit/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(gyp_shared_intermediate_dir)/EventNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventFactory ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_event_factory.py dom/EventNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/EventNames.in" dom/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
 
 $(gyp_shared_intermediate_dir)/webkit/EventHeaders.h: $(gyp_shared_intermediate_dir)/webkit/Event.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/EventInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/Event.cpp ;
@@ -162,19 +162,6 @@
 
 $(gyp_shared_intermediate_dir)/webkit/EventTargetInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/EventTargetHeaders.h ;
 
-### Rules for action "ExceptionCodeDescription":
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_dom_exceptions.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/DOMExceptions.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_ExceptionCodeDescription ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_dom_exceptions.py dom/DOMExceptions.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
-
-$(gyp_shared_intermediate_dir)/webkit/DOMException.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/DOMExceptionHeaders.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/DOMExceptionInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-
 ### Rules for action "MathMLNames":
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -182,11 +169,9 @@
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.h: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
 
 ### Rules for action "UserAgentStyleSheets":
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: gyp_local_path := $(LOCAL_PATH)
@@ -195,7 +180,7 @@
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mathml.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsChromium.css css/mediaControlsChromiumAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsChromium.css css/mediaControlsChromiumAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h ;
 
@@ -239,7 +224,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.h: $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp ;
 
@@ -250,7 +235,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h: $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp ;
 
@@ -261,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.h: $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp ;
 
@@ -272,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSGrammar.y: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSGrammar.y: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.includes $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_preprocess_grammar ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; perl -Iscripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/webkit/" --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\"" --preprocessOnly --preprocessor "/usr/bin/gcc -E -P -x c++" css/CSSGrammar.y.in css/CSSGrammar.y.includes
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; perl -Iscripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/webkit/" --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\"" --preprocessOnly --preprocessor "/usr/bin/gcc -E -P -x c++" css/CSSGrammar.y.in css/CSSGrammar.y.includes
 
 
 
@@ -348,14 +333,8 @@
 	$(gyp_shared_intermediate_dir)/webkit/EventInterfaces.h \
 	$(gyp_shared_intermediate_dir)/webkit/EventTargetHeaders.h \
 	$(gyp_shared_intermediate_dir)/webkit/EventTargetInterfaces.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp \
-	$(gyp_shared_intermediate_dir)/webkit/DOMException.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMExceptionHeaders.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMExceptionInterfaces.h \
 	$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h \
-	$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp \
-	$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h \
 	$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h \
 	$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp \
 	$(gyp_shared_intermediate_dir)/webkit/PickerCommon.h \
@@ -389,7 +368,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -424,9 +403,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -448,18 +425,16 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -470,6 +445,89 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
diff --git a/Source/core/make_derived_sources.target.darwin-mips.mk b/Source/core/make_derived_sources.target.darwin-mips.mk
index 5b33cbd..451a719 100644
--- a/Source/core/make_derived_sources.target.darwin-mips.mk
+++ b/Source/core/make_derived_sources.target.darwin-mips.mk
@@ -72,7 +72,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp ;
 
@@ -95,7 +95,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp ;
 
@@ -106,7 +106,7 @@
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.h: $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp ;
@@ -131,7 +131,7 @@
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGNames.h" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGNames.h" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.h: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp ;
@@ -144,9 +144,9 @@
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/webkit/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/webkit/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(gyp_shared_intermediate_dir)/EventNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventFactory ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_event_factory.py dom/EventNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/EventNames.in" dom/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
 
 $(gyp_shared_intermediate_dir)/webkit/EventHeaders.h: $(gyp_shared_intermediate_dir)/webkit/Event.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/EventInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/Event.cpp ;
@@ -162,19 +162,6 @@
 
 $(gyp_shared_intermediate_dir)/webkit/EventTargetInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/EventTargetHeaders.h ;
 
-### Rules for action "ExceptionCodeDescription":
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_dom_exceptions.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/DOMExceptions.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_ExceptionCodeDescription ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_dom_exceptions.py dom/DOMExceptions.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
-
-$(gyp_shared_intermediate_dir)/webkit/DOMException.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/DOMExceptionHeaders.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/DOMExceptionInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-
 ### Rules for action "MathMLNames":
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -182,11 +169,9 @@
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.h: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
 
 ### Rules for action "UserAgentStyleSheets":
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: gyp_local_path := $(LOCAL_PATH)
@@ -195,7 +180,7 @@
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mathml.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsChromium.css css/mediaControlsChromiumAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsChromium.css css/mediaControlsChromiumAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h ;
 
@@ -239,7 +224,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.h: $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp ;
 
@@ -250,7 +235,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h: $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp ;
 
@@ -261,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.h: $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp ;
 
@@ -272,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSGrammar.y: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSGrammar.y: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.includes $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_preprocess_grammar ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; perl -Iscripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/webkit/" --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\"" --preprocessOnly --preprocessor "/usr/bin/gcc -E -P -x c++" css/CSSGrammar.y.in css/CSSGrammar.y.includes
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; perl -Iscripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/webkit/" --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\"" --preprocessOnly --preprocessor "/usr/bin/gcc -E -P -x c++" css/CSSGrammar.y.in css/CSSGrammar.y.includes
 
 
 
@@ -348,14 +333,8 @@
 	$(gyp_shared_intermediate_dir)/webkit/EventInterfaces.h \
 	$(gyp_shared_intermediate_dir)/webkit/EventTargetHeaders.h \
 	$(gyp_shared_intermediate_dir)/webkit/EventTargetInterfaces.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp \
-	$(gyp_shared_intermediate_dir)/webkit/DOMException.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMExceptionHeaders.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMExceptionInterfaces.h \
 	$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h \
-	$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp \
-	$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h \
 	$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h \
 	$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp \
 	$(gyp_shared_intermediate_dir)/webkit/PickerCommon.h \
@@ -389,7 +368,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -424,9 +403,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -447,18 +424,16 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -469,6 +444,88 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
diff --git a/Source/core/make_derived_sources.target.darwin-x86.mk b/Source/core/make_derived_sources.target.darwin-x86.mk
index d2b2989..4bba7a8 100644
--- a/Source/core/make_derived_sources.target.darwin-x86.mk
+++ b/Source/core/make_derived_sources.target.darwin-x86.mk
@@ -72,7 +72,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp ;
 
@@ -95,7 +95,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp ;
 
@@ -106,7 +106,7 @@
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.h: $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp ;
@@ -131,7 +131,7 @@
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGNames.h" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGNames.h" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.h: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp ;
@@ -144,9 +144,9 @@
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/webkit/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/webkit/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(gyp_shared_intermediate_dir)/EventNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventFactory ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_event_factory.py dom/EventNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/EventNames.in" dom/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
 
 $(gyp_shared_intermediate_dir)/webkit/EventHeaders.h: $(gyp_shared_intermediate_dir)/webkit/Event.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/EventInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/Event.cpp ;
@@ -162,19 +162,6 @@
 
 $(gyp_shared_intermediate_dir)/webkit/EventTargetInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/EventTargetHeaders.h ;
 
-### Rules for action "ExceptionCodeDescription":
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_dom_exceptions.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/DOMExceptions.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_ExceptionCodeDescription ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_dom_exceptions.py dom/DOMExceptions.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
-
-$(gyp_shared_intermediate_dir)/webkit/DOMException.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/DOMExceptionHeaders.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/DOMExceptionInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-
 ### Rules for action "MathMLNames":
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -182,11 +169,9 @@
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.h: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
 
 ### Rules for action "UserAgentStyleSheets":
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: gyp_local_path := $(LOCAL_PATH)
@@ -195,7 +180,7 @@
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mathml.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsChromium.css css/mediaControlsChromiumAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsChromium.css css/mediaControlsChromiumAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h ;
 
@@ -239,7 +224,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.h: $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp ;
 
@@ -250,7 +235,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h: $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp ;
 
@@ -261,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.h: $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp ;
 
@@ -272,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSGrammar.y: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSGrammar.y: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.includes $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_preprocess_grammar ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; perl -Iscripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/webkit/" --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\"" --preprocessOnly --preprocessor "/usr/bin/gcc -E -P -x c++" css/CSSGrammar.y.in css/CSSGrammar.y.includes
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; perl -Iscripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/webkit/" --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\"" --preprocessOnly --preprocessor "/usr/bin/gcc -E -P -x c++" css/CSSGrammar.y.in css/CSSGrammar.y.includes
 
 
 
@@ -348,14 +333,8 @@
 	$(gyp_shared_intermediate_dir)/webkit/EventInterfaces.h \
 	$(gyp_shared_intermediate_dir)/webkit/EventTargetHeaders.h \
 	$(gyp_shared_intermediate_dir)/webkit/EventTargetInterfaces.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp \
-	$(gyp_shared_intermediate_dir)/webkit/DOMException.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMExceptionHeaders.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMExceptionInterfaces.h \
 	$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h \
-	$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp \
-	$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h \
 	$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h \
 	$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp \
 	$(gyp_shared_intermediate_dir)/webkit/PickerCommon.h \
@@ -389,7 +368,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -426,9 +405,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -450,18 +427,16 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -471,6 +446,92 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
diff --git a/Source/core/make_derived_sources.target.linux-arm.mk b/Source/core/make_derived_sources.target.linux-arm.mk
index 16ead4b..c018bf8 100644
--- a/Source/core/make_derived_sources.target.linux-arm.mk
+++ b/Source/core/make_derived_sources.target.linux-arm.mk
@@ -72,7 +72,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp ;
 
@@ -95,7 +95,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp ;
 
@@ -106,7 +106,7 @@
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.h: $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp ;
@@ -131,7 +131,7 @@
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGNames.h" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGNames.h" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.h: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp ;
@@ -144,9 +144,9 @@
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/webkit/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/webkit/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(gyp_shared_intermediate_dir)/EventNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventFactory ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_event_factory.py dom/EventNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/EventNames.in" dom/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
 
 $(gyp_shared_intermediate_dir)/webkit/EventHeaders.h: $(gyp_shared_intermediate_dir)/webkit/Event.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/EventInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/Event.cpp ;
@@ -162,19 +162,6 @@
 
 $(gyp_shared_intermediate_dir)/webkit/EventTargetInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/EventTargetHeaders.h ;
 
-### Rules for action "ExceptionCodeDescription":
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_dom_exceptions.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/DOMExceptions.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_ExceptionCodeDescription ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_dom_exceptions.py dom/DOMExceptions.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
-
-$(gyp_shared_intermediate_dir)/webkit/DOMException.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/DOMExceptionHeaders.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/DOMExceptionInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-
 ### Rules for action "MathMLNames":
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -182,11 +169,9 @@
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.h: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
 
 ### Rules for action "UserAgentStyleSheets":
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: gyp_local_path := $(LOCAL_PATH)
@@ -195,7 +180,7 @@
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mathml.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsChromium.css css/mediaControlsChromiumAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsChromium.css css/mediaControlsChromiumAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h ;
 
@@ -239,7 +224,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.h: $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp ;
 
@@ -250,7 +235,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h: $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp ;
 
@@ -261,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.h: $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp ;
 
@@ -272,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSGrammar.y: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSGrammar.y: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.includes $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_preprocess_grammar ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; perl -Iscripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/webkit/" --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\"" --preprocessOnly --preprocessor "/usr/bin/gcc -E -P -x c++" css/CSSGrammar.y.in css/CSSGrammar.y.includes
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; perl -Iscripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/webkit/" --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\"" --preprocessOnly --preprocessor "/usr/bin/gcc -E -P -x c++" css/CSSGrammar.y.in css/CSSGrammar.y.includes
 
 
 
@@ -348,14 +333,8 @@
 	$(gyp_shared_intermediate_dir)/webkit/EventInterfaces.h \
 	$(gyp_shared_intermediate_dir)/webkit/EventTargetHeaders.h \
 	$(gyp_shared_intermediate_dir)/webkit/EventTargetInterfaces.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp \
-	$(gyp_shared_intermediate_dir)/webkit/DOMException.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMExceptionHeaders.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMExceptionInterfaces.h \
 	$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h \
-	$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp \
-	$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h \
 	$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h \
 	$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp \
 	$(gyp_shared_intermediate_dir)/webkit/PickerCommon.h \
@@ -389,7 +368,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -424,9 +403,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -448,18 +425,16 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -470,6 +445,89 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
diff --git a/Source/core/make_derived_sources.target.linux-mips.mk b/Source/core/make_derived_sources.target.linux-mips.mk
index 5b33cbd..451a719 100644
--- a/Source/core/make_derived_sources.target.linux-mips.mk
+++ b/Source/core/make_derived_sources.target.linux-mips.mk
@@ -72,7 +72,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp ;
 
@@ -95,7 +95,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp ;
 
@@ -106,7 +106,7 @@
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.h: $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp ;
@@ -131,7 +131,7 @@
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGNames.h" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGNames.h" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.h: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp ;
@@ -144,9 +144,9 @@
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/webkit/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/webkit/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(gyp_shared_intermediate_dir)/EventNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventFactory ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_event_factory.py dom/EventNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/EventNames.in" dom/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
 
 $(gyp_shared_intermediate_dir)/webkit/EventHeaders.h: $(gyp_shared_intermediate_dir)/webkit/Event.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/EventInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/Event.cpp ;
@@ -162,19 +162,6 @@
 
 $(gyp_shared_intermediate_dir)/webkit/EventTargetInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/EventTargetHeaders.h ;
 
-### Rules for action "ExceptionCodeDescription":
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_dom_exceptions.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/DOMExceptions.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_ExceptionCodeDescription ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_dom_exceptions.py dom/DOMExceptions.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
-
-$(gyp_shared_intermediate_dir)/webkit/DOMException.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/DOMExceptionHeaders.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/DOMExceptionInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-
 ### Rules for action "MathMLNames":
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -182,11 +169,9 @@
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.h: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
 
 ### Rules for action "UserAgentStyleSheets":
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: gyp_local_path := $(LOCAL_PATH)
@@ -195,7 +180,7 @@
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mathml.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsChromium.css css/mediaControlsChromiumAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsChromium.css css/mediaControlsChromiumAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h ;
 
@@ -239,7 +224,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.h: $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp ;
 
@@ -250,7 +235,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h: $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp ;
 
@@ -261,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.h: $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp ;
 
@@ -272,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSGrammar.y: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSGrammar.y: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.includes $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_preprocess_grammar ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; perl -Iscripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/webkit/" --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\"" --preprocessOnly --preprocessor "/usr/bin/gcc -E -P -x c++" css/CSSGrammar.y.in css/CSSGrammar.y.includes
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; perl -Iscripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/webkit/" --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\"" --preprocessOnly --preprocessor "/usr/bin/gcc -E -P -x c++" css/CSSGrammar.y.in css/CSSGrammar.y.includes
 
 
 
@@ -348,14 +333,8 @@
 	$(gyp_shared_intermediate_dir)/webkit/EventInterfaces.h \
 	$(gyp_shared_intermediate_dir)/webkit/EventTargetHeaders.h \
 	$(gyp_shared_intermediate_dir)/webkit/EventTargetInterfaces.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp \
-	$(gyp_shared_intermediate_dir)/webkit/DOMException.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMExceptionHeaders.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMExceptionInterfaces.h \
 	$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h \
-	$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp \
-	$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h \
 	$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h \
 	$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp \
 	$(gyp_shared_intermediate_dir)/webkit/PickerCommon.h \
@@ -389,7 +368,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -424,9 +403,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -447,18 +424,16 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -469,6 +444,88 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
diff --git a/Source/core/make_derived_sources.target.linux-x86.mk b/Source/core/make_derived_sources.target.linux-x86.mk
index d2b2989..4bba7a8 100644
--- a/Source/core/make_derived_sources.target.linux-x86.mk
+++ b/Source/core/make_derived_sources.target.linux-x86.mk
@@ -72,7 +72,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_property_names.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSPropertyNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSPropertyNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSPropertyNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_css_property_names.py css/CSSPropertyNames.in css/SVGCSSPropertyNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.h: $(gyp_shared_intermediate_dir)/webkit/CSSPropertyNames.cpp ;
 
@@ -95,7 +95,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_css_value_keywords.py $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSValueKeywords.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/SVGCSSValueKeywords.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_CSSValueKeywords ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; scripts/make_css_value_keywords.py css/CSSValueKeywords.in css/SVGCSSValueKeywords.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/" --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.h: $(gyp_shared_intermediate_dir)/webkit/CSSValueKeywords.cpp ;
 
@@ -106,7 +106,7 @@
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLTagNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/html/HTMLAttributeNames.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_HTMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/HTMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8HTMLElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl html/HTMLTagNames.in html/HTMLAttributeNames.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/HTMLNames.h: $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/HTMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/HTMLNames.cpp ;
@@ -131,7 +131,7 @@
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/svgattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_SVGNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGNames.h" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGNames.h" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.h" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/V8SVGElementWrapperFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/svgtags.in svg/svgattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/SVGNames.h: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/SVGElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp ;
@@ -144,9 +144,9 @@
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
 $(gyp_shared_intermediate_dir)/webkit/Event.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/webkit/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventNames.in $(GYP_TARGET_DEPENDENCIES)
+$(gyp_shared_intermediate_dir)/webkit/Event.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_event_factory.py $(gyp_shared_intermediate_dir)/EventNames.in $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/EventAliases.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_EventFactory ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_event_factory.py dom/EventNames.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_event_factory.py "$(gyp_shared_intermediate_dir)/EventNames.in" dom/EventAliases.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
 
 $(gyp_shared_intermediate_dir)/webkit/EventHeaders.h: $(gyp_shared_intermediate_dir)/webkit/Event.cpp ;
 $(gyp_shared_intermediate_dir)/webkit/EventInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/Event.cpp ;
@@ -162,19 +162,6 @@
 
 $(gyp_shared_intermediate_dir)/webkit/EventTargetInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/EventTargetHeaders.h ;
 
-### Rules for action "ExceptionCodeDescription":
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_local_path := $(LOCAL_PATH)
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: gyp_shared_intermediate_dir := $(abspath $(gyp_shared_intermediate_dir))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
-$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_file.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/in_generator.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/license.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/name_macros.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/template_expander.py $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/templates/macros.tmpl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_dom_exceptions.py $(LOCAL_PATH)/third_party/WebKit/Source/core/dom/DOMExceptions.in $(GYP_TARGET_DEPENDENCIES)
-	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_ExceptionCodeDescription ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/make_dom_exceptions.py dom/DOMExceptions.in --output_dir "$(gyp_shared_intermediate_dir)/webkit/"
-
-$(gyp_shared_intermediate_dir)/webkit/DOMException.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/DOMExceptionHeaders.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/DOMExceptionInterfaces.h: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp ;
-
 ### Rules for action "MathMLNames":
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: gyp_local_path := $(LOCAL_PATH)
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: gyp_intermediate_dir := $(abspath $(gyp_intermediate_dir))
@@ -182,11 +169,9 @@
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathtags.in $(LOCAL_PATH)/third_party/WebKit/Source/core/mathml/mathattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_MathMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h" "$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --factory --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl mathml/mathtags.in mathml/mathattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/MathMLNames.h: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
-$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp ;
 
 ### Rules for action "UserAgentStyleSheets":
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: gyp_local_path := $(LOCAL_PATH)
@@ -195,7 +180,7 @@
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/make-css-file-arrays.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/preprocessor.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/css/html.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/quirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/view-source.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumLinux.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeChromiumSkia.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWin.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/themeWinQuirks.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/svg.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mathml.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControls.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsChromium.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/mediaControlsChromiumAndroid.css $(LOCAL_PATH)/third_party/WebKit/Source/core/css/fullscreen.css $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_UserAgentStyleSheets ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsChromium.css css/mediaControlsChromiumAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_useragentstylesheets.py "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h" "$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp" css/html.css css/quirks.css css/view-source.css css/themeChromium.css css/themeChromiumAndroid.css css/themeChromiumLinux.css css/themeChromiumSkia.css css/themeWin.css css/themeWinQuirks.css css/svg.css css/mathml.css css/mediaControls.css css/mediaControlsChromium.css css/mediaControlsChromiumAndroid.css css/fullscreen.css -- css/make-css-file-arrays.pl scripts/preprocessor.pm -- --defines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h ;
 
@@ -239,7 +224,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/svg/xlinkattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XLinkNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XLinkNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl svg/xlinkattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XLinkNames.h: $(gyp_shared_intermediate_dir)/webkit/XLinkNames.cpp ;
 
@@ -250,7 +235,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlnsattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNSNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlnsattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.h: $(gyp_shared_intermediate_dir)/webkit/XMLNSNames.cpp ;
 
@@ -261,7 +246,7 @@
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp: $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/Hasher.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/StaticString.pm $(LOCAL_PATH)/third_party/WebKit/Source/core/scripts/make_names.pl $(LOCAL_PATH)/third_party/WebKit/Source/core/xml/xmlattrs.in $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_XMLNames ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\""
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; python scripts/action_makenames.py "$(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp" "$(gyp_shared_intermediate_dir)/webkit/XMLNames.h" -- scripts/Hasher.pm scripts/StaticString.pm scripts/make_names.pl xml/xmlattrs.in -- --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\""
 
 $(gyp_shared_intermediate_dir)/webkit/XMLNames.h: $(gyp_shared_intermediate_dir)/webkit/XMLNames.cpp ;
 
@@ -272,7 +257,7 @@
 $(gyp_shared_intermediate_dir)/webkit/CSSGrammar.y: export PATH := $(subst $(ANDROID_BUILD_PATHS),,$(PATH))
 $(gyp_shared_intermediate_dir)/webkit/CSSGrammar.y: $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.in $(LOCAL_PATH)/third_party/WebKit/Source/core/css/CSSGrammar.y.includes $(GYP_TARGET_DEPENDENCIES)
 	@echo "Gyp action: third_party_WebKit_Source_core_core_derived_sources_gyp_make_derived_sources_target_preprocess_grammar ($@)"
-	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; perl -Iscripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/webkit/" --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\" \"ENABLE_PARTITION_ALLOC=1\"" --preprocessOnly --preprocessor "/usr/bin/gcc -E -P -x c++" css/CSSGrammar.y.in css/CSSGrammar.y.includes
+	$(hide)cd $(gyp_local_path)/third_party/WebKit/Source/core; mkdir -p $(gyp_shared_intermediate_dir)/webkit; perl -Iscripts css/makegrammar.pl --outputDir "$(gyp_shared_intermediate_dir)/webkit/" --extraDefines "\"ENABLE_CANVAS_USES_MAILBOX=1\" \"ENABLE_CSS3_TEXT=0\" \"ENABLE_CSS_EXCLUSIONS=1\" \"ENABLE_CSS_REGIONS=1\" \"ENABLE_CUSTOM_SCHEME_HANDLER=0\" \"ENABLE_ENCRYPTED_MEDIA_V2=1\" \"ENABLE_SVG_FONTS=1\" \"ENABLE_TOUCH_ICON_LOADING=1\" \"ENABLE_XHR_TIMEOUT=0\" \"ENABLE_GDI_FONTS_ON_WINDOWS=1\" \"ENABLE_PARTITION_ALLOC=1\" \"WTF_USE_CONCATENATED_IMPULSE_RESPONSES=1\" \"ENABLE_CALENDAR_PICKER=0\" \"ENABLE_FAST_MOBILE_SCROLLING=1\" \"ENABLE_INPUT_SPEECH=0\" \"ENABLE_LEGACY_NOTIFICATIONS=0\" \"ENABLE_MEDIA_CAPTURE=1\" \"ENABLE_NOTIFICATIONS=0\" \"ENABLE_ORIENTATION_EVENTS=1\" \"ENABLE_PRINTING=0\" \"ENABLE_NAVIGATOR_CONTENT_UTILS=0\" \"WTF_USE_NATIVE_FULLSCREEN_VIDEO=1\" \"ENABLE_8BIT_TEXTRUN=1\" \"ENABLE_OPENTYPE_VERTICAL=1\" \"WTF_USE_HARFBUZZ=1\"" --preprocessOnly --preprocessor "/usr/bin/gcc -E -P -x c++" css/CSSGrammar.y.in css/CSSGrammar.y.includes
 
 
 
@@ -348,14 +333,8 @@
 	$(gyp_shared_intermediate_dir)/webkit/EventInterfaces.h \
 	$(gyp_shared_intermediate_dir)/webkit/EventTargetHeaders.h \
 	$(gyp_shared_intermediate_dir)/webkit/EventTargetInterfaces.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMException.cpp \
-	$(gyp_shared_intermediate_dir)/webkit/DOMException.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMExceptionHeaders.h \
-	$(gyp_shared_intermediate_dir)/webkit/DOMExceptionInterfaces.h \
 	$(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp \
 	$(gyp_shared_intermediate_dir)/webkit/MathMLNames.h \
-	$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp \
-	$(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.h \
 	$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheets.h \
 	$(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp \
 	$(gyp_shared_intermediate_dir)/webkit/PickerCommon.h \
@@ -389,7 +368,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -426,9 +405,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -450,18 +427,16 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(PWD)/frameworks/wilhelm/include \
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -471,6 +446,92 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 # Add target alias to "gyp_all_modules" target.
 .PHONY: gyp_all_modules
diff --git a/Source/core/mathml/mathattrs.in b/Source/core/mathml/mathattrs.in
index afa5fec..45a6e3a 100644
--- a/Source/core/mathml/mathattrs.in
+++ b/Source/core/mathml/mathattrs.in
@@ -1,6 +1,5 @@
 namespace="MathML"
 namespaceURI="http://www.w3.org/1998/Math/MathML"
-guardFactoryWith="ENABLE(MATHML)"
 attrsNullNamespace
 
 alttext
diff --git a/Source/core/mathml/mathtags.in b/Source/core/mathml/mathtags.in
index 6f68c73..95688e1 100644
--- a/Source/core/mathml/mathtags.in
+++ b/Source/core/mathml/mathtags.in
@@ -1,27 +1,11 @@
 namespace="MathML"
 namespaceURI="http://www.w3.org/1998/Math/MathML"
-guardFactoryWith="ENABLE(MATHML)"
-fallbackInterfaceName="MathMLElement"
 
 math
-mfrac interfaceName=MathMLInlineContainerElement
-mfenced interfaceName=MathMLInlineContainerElement
-msubsup interfaceName=MathMLInlineContainerElement
-mrow interfaceName=MathMLInlineContainerElement
-mover interfaceName=MathMLInlineContainerElement
-munder interfaceName=MathMLInlineContainerElement
-munderover interfaceName=MathMLInlineContainerElement
-msqrt interfaceName=MathMLInlineContainerElement
-mroot interfaceName=MathMLInlineContainerElement
-mi interfaceName=MathMLTextElement
-mn interfaceName=MathMLTextElement
-mo interfaceName=MathMLTextElement
-mtext interfaceName=MathMLTextElement
-msub interfaceName=MathMLInlineContainerElement
-msup interfaceName=MathMLInlineContainerElement
-mtable interfaceName=MathMLInlineContainerElement
-mtr interfaceName=MathMLElement
-mtd interfaceName=MathMLElement
+mi
+mn
+mo
+mtext
 
 #if 0 // Curently only for MathMLNames used by HTMLTreeBuilder.
 ms
diff --git a/Source/core/page/AutoscrollController.cpp b/Source/core/page/AutoscrollController.cpp
index fb597bf..c9c8020 100644
--- a/Source/core/page/AutoscrollController.cpp
+++ b/Source/core/page/AutoscrollController.cpp
@@ -119,7 +119,7 @@
     RenderObject* renderer = m_autoscrollRenderer;
 
 #if ENABLE(PAN_SCROLLING)
-    HitTestResult hitTest = renderer->frame()->eventHandler()->hitTestResultAtPoint(m_panScrollStartPos, true);
+    HitTestResult hitTest = renderer->frame()->eventHandler()->hitTestResultAtPoint(m_panScrollStartPos, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
 
     if (Node* nodeAtPoint = hitTest.innerNode())
         renderer = nodeAtPoint->renderer();
diff --git a/Source/core/page/Chrome.cpp b/Source/core/page/Chrome.cpp
index ba649ef..aaafe0e 100644
--- a/Source/core/page/Chrome.cpp
+++ b/Source/core/page/Chrome.cpp
@@ -23,10 +23,6 @@
 #include "core/page/Chrome.h"
 
 #include "public/platform/WebScreenInfo.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/StringBuilder.h>
-#include <wtf/Vector.h>
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
 #include "core/html/HTMLInputElement.h"
@@ -43,7 +39,8 @@
 #include "core/platform/graphics/FloatRect.h"
 #include "core/platform/network/DNS.h"
 #include "core/rendering/HitTestResult.h"
-#include "core/storage/StorageNamespace.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -148,21 +145,9 @@
     m_client->focusedNodeChanged(node);
 }
 
-Page* Chrome::createWindow(Frame* frame, const FrameLoadRequest& request, const WindowFeatures& features, const NavigationAction& action) const
+void Chrome::show(NavigationPolicy policy) const
 {
-    Page* newPage = m_client->createWindow(frame, request, features, action);
-
-    if (newPage) {
-        if (StorageNamespace* oldSessionStorage = m_page->sessionStorage(false))
-            newPage->setSessionStorage(oldSessionStorage->copy());
-    }
-
-    return newPage;
-}
-
-void Chrome::show() const
-{
-    m_client->show();
+    m_client->show(policy);
 }
 
 bool Chrome::canRunModal() const
diff --git a/Source/core/page/Chrome.h b/Source/core/page/Chrome.h
index 006a53f..e5a0f24 100644
--- a/Source/core/page/Chrome.h
+++ b/Source/core/page/Chrome.h
@@ -22,11 +22,11 @@
 #ifndef Chrome_h
 #define Chrome_h
 
+#include "core/loader/NavigationPolicy.h"
 #include "core/page/FocusDirection.h"
 #include "core/platform/Cursor.h"
 #include "core/platform/HostWindow.h"
-#include <wtf/Forward.h>
-#include <wtf/RefPtr.h>
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
@@ -42,7 +42,6 @@
 class Geolocation;
 class HitTestResult;
 class IntRect;
-class NavigationAction;
 class Node;
 class Page;
 class PopupMenu;
@@ -51,9 +50,7 @@
 class SearchPopupMenu;
 
 struct DateTimeChooserParameters;
-struct FrameLoadRequest;
 struct ViewportArguments;
-struct WindowFeatures;
     
 class Chrome : public HostWindow {
 public:
@@ -90,8 +87,7 @@
 
     void focusedNodeChanged(Node*) const;
 
-    Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, const NavigationAction&) const;
-    void show() const;
+    void show(NavigationPolicy = NavigationPolicyIgnore) const;
 
     bool canRunModal() const;
     bool canRunModalNow() const;
diff --git a/Source/core/page/ChromeClient.h b/Source/core/page/ChromeClient.h
index 5af7ac2..0d91580 100644
--- a/Source/core/page/ChromeClient.h
+++ b/Source/core/page/ChromeClient.h
@@ -25,6 +25,7 @@
 #include "core/accessibility/AXObjectCache.h"
 #include "core/inspector/ConsoleAPITypes.h"
 #include "core/loader/FrameLoader.h"
+#include "core/loader/NavigationPolicy.h"
 #include "core/page/ConsoleTypes.h"
 #include "core/page/FocusDirection.h"
 #include "core/platform/Cursor.h"
@@ -105,8 +106,8 @@
     // created Page has its show method called.
     // The FrameLoadRequest parameter is only for ChromeClient to check if the
     // request could be fulfilled. The ChromeClient should not load the request.
-    virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, const NavigationAction&) = 0;
-    virtual void show() = 0;
+    virtual Page* createWindow(Frame*, const FrameLoadRequest&, const WindowFeatures&, const NavigationAction&, NavigationPolicy = NavigationPolicyIgnore) = 0;
+    virtual void show(NavigationPolicy) = 0;
 
     virtual bool canRunModal() = 0;
     virtual void runModal() = 0;
diff --git a/Source/core/page/Console.cpp b/Source/core/page/Console.cpp
index b1aa59b..bd34162 100644
--- a/Source/core/page/Console.cpp
+++ b/Source/core/page/Console.cpp
@@ -29,7 +29,6 @@
 #include "config.h"
 #include "core/page/Console.h"
 
-#include <stdio.h>
 #include "bindings/v8/ScriptCallStackFactory.h"
 #include "bindings/v8/ScriptProfiler.h"
 #include "core/inspector/ConsoleAPITypes.h"
@@ -43,9 +42,8 @@
 #include "core/page/Frame.h"
 #include "core/page/MemoryInfo.h"
 #include "core/page/Page.h"
-#include <wtf/text/CString.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/UnusedParam.h>
+#include "wtf/text/CString.h"
+#include "wtf/text/WTFString.h"
 
 #include "core/platform/chromium/TraceEvent.h"
 
@@ -221,7 +219,7 @@
 
 void Console::groupEnd()
 {
-    InspectorInstrumentation::addMessageToConsole(page(), ConsoleAPIMessageSource, EndGroupMessageType, LogMessageLevel, String(), String(), 0);
+    InspectorInstrumentation::addMessageToConsole(page(), ConsoleAPIMessageSource, EndGroupMessageType, LogMessageLevel, String(), String(), 0, 0);
 }
 
 PassRefPtr<MemoryInfo> Console::memory() const
diff --git a/Source/core/page/Console.idl b/Source/core/page/Console.idl
index e536e49..f675e8e 100644
--- a/Source/core/page/Console.idl
+++ b/Source/core/page/Console.idl
@@ -30,17 +30,17 @@
     NoInterfaceObject
 ] interface Console {
 
-    [CallWith=ScriptArguments|ScriptState] void debug();
-    [CallWith=ScriptArguments|ScriptState] void error();
-    [CallWith=ScriptArguments|ScriptState] void info();
-    [CallWith=ScriptArguments|ScriptState] void log();
-    [CallWith=ScriptArguments|ScriptState] void warn();
-    [CallWith=ScriptArguments|ScriptState] void dir();
-    [CallWith=ScriptArguments|ScriptState] void dirxml();
-    [CallWith=ScriptArguments|ScriptState] void table();
-    [CallWith=ScriptArguments|ScriptState] void trace();
-    [CallWith=ScriptArguments|ScriptState, ImplementedAs=assertCondition] void assert([Default=Undefined] optional boolean condition);
-    [CallWith=ScriptArguments|ScriptState] void count();
+    [CallWith=ScriptArguments&ScriptState] void debug();
+    [CallWith=ScriptArguments&ScriptState] void error();
+    [CallWith=ScriptArguments&ScriptState] void info();
+    [CallWith=ScriptArguments&ScriptState] void log();
+    [CallWith=ScriptArguments&ScriptState] void warn();
+    [CallWith=ScriptArguments&ScriptState] void dir();
+    [CallWith=ScriptArguments&ScriptState] void dirxml();
+    [CallWith=ScriptArguments&ScriptState] void table();
+    [CallWith=ScriptArguments&ScriptState] void trace();
+    [CallWith=ScriptArguments&ScriptState, ImplementedAs=assertCondition] void assert([Default=Undefined] optional boolean condition);
+    [CallWith=ScriptArguments&ScriptState] void count();
     [CallWith=ScriptArguments] void markTimeline();
 
     [CallWith=ScriptState] void profile([Default=NullString] optional DOMString title);
@@ -49,10 +49,10 @@
     void time([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString title);
     [CallWith=ScriptState] void timeEnd([TreatNullAs=NullString, TreatUndefinedAs=NullString] DOMString title);
     [CallWith=ScriptArguments] void timeStamp();
-    [CallWith=ScriptArguments|ScriptState] void group();
-    [CallWith=ScriptArguments|ScriptState] void groupCollapsed();
+    [CallWith=ScriptArguments&ScriptState] void group();
+    [CallWith=ScriptArguments&ScriptState] void groupCollapsed();
     void groupEnd();
-    [CallWith=ScriptArguments|ScriptState] void clear();
+    [CallWith=ScriptArguments&ScriptState] void clear();
 
     readonly attribute MemoryInfo memory;
 };
diff --git a/Source/core/page/ContentSecurityPolicy.cpp b/Source/core/page/ContentSecurityPolicy.cpp
index ecc8582..aeed3de 100644
--- a/Source/core/page/ContentSecurityPolicy.cpp
+++ b/Source/core/page/ContentSecurityPolicy.cpp
@@ -33,22 +33,18 @@
 #include "core/dom/DOMStringList.h"
 #include "core/dom/Document.h"
 #include "core/dom/SecurityPolicyViolationEvent.h"
-#include "core/html/FormDataList.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include "core/inspector/InspectorValues.h"
 #include "core/inspector/ScriptCallStack.h"
 #include "core/loader/PingLoader.h"
-#include "core/page/Console.h"
 #include "core/page/Frame.h"
-#include "core/page/PageConsole.h"
 #include "core/page/UseCounter.h"
+#include "core/platform/JSONValues.h"
 #include "core/platform/network/FormData.h"
 #include "weborigin/KURL.h"
 #include "weborigin/KnownPorts.h"
 #include "weborigin/SchemeRegistry.h"
 #include "weborigin/SecurityOrigin.h"
 #include "wtf/HashSet.h"
-#include "wtf/text/TextEncoding.h"
 #include "wtf/text/TextPosition.h"
 #include "wtf/text/WTFString.h"
 
@@ -200,8 +196,8 @@
 
 static bool isSourceListNone(const String& value)
 {
-    const UChar* begin = value.characters();
-    const UChar* end = value.characters() + value.length();
+    const UChar* begin = value.bloatedCharacters();
+    const UChar* end = value.bloatedCharacters() + value.length();
     skipWhile<isASCIISpace>(begin, end);
 
     const UChar* position = begin;
@@ -352,7 +348,7 @@
     // We represent 'none' as an empty m_list.
     if (isSourceListNone(value))
         return;
-    parse(value.characters(), value.characters() + value.length());
+    parse(value.bloatedCharacters(), value.bloatedCharacters() + value.length());
 }
 
 bool CSPSourceList::matches(const KURL& url)
@@ -537,7 +533,7 @@
 {
     DEFINE_STATIC_LOCAL(const String, noncePrefix, (ASCIILiteral("'nonce-")));
 
-    if (!equalIgnoringCase(noncePrefix.characters(), begin, noncePrefix.length()))
+    if (!equalIgnoringCase(noncePrefix.bloatedCharacters(), begin, noncePrefix.length()))
         return true;
 
     const UChar* position = begin + noncePrefix.length();
@@ -731,7 +727,7 @@
 private:
     void parse(const String& value)
     {
-        const UChar* begin = value.characters();
+        const UChar* begin = value.bloatedCharacters();
         const UChar* position = begin;
         const UChar* end = begin + value.length();
 
@@ -1202,7 +1198,7 @@
     if (policy.isEmpty())
         return;
 
-    const UChar* position = policy.characters();
+    const UChar* position = policy.bloatedCharacters();
     const UChar* end = position + policy.length();
 
     while (position < end) {
@@ -1281,7 +1277,7 @@
         m_policy->reportDuplicateDirective(name);
         return;
     }
-    const UChar* position = value.characters();
+    const UChar* position = value.bloatedCharacters();
     const UChar* end = position + value.length();
 
     while (position < end) {
@@ -1335,7 +1331,7 @@
         return;
     }
 
-    const UChar* position = value.characters();
+    const UChar* position = value.bloatedCharacters();
     const UChar* end = position + value.length();
 
     skipWhile<isASCIISpace>(position, end);
@@ -1438,7 +1434,7 @@
     // RFC2616, section 4.2 specifies that headers appearing multiple times can
     // be combined with a comma. Walk the header string, and parse each comma
     // separated chunk as a separate header.
-    const UChar* begin = header.characters();
+    const UChar* begin = header.bloatedCharacters();
     const UChar* position = begin;
     const UChar* end = begin + header.length();
     while (position < end) {
@@ -1734,7 +1730,7 @@
     // sent explicitly. As for which directive was violated, that's pretty
     // harmless information.
 
-    RefPtr<InspectorObject> cspReport = InspectorObject::create();
+    RefPtr<JSONObject> cspReport = JSONObject::create();
     cspReport->setString("document-uri", violationData.documentURI);
     cspReport->setString("referrer", violationData.referrer);
     cspReport->setString("violated-directive", violationData.violatedDirective);
@@ -1748,7 +1744,7 @@
         cspReport->setNumber("column-number", violationData.columnNumber);
     }
 
-    RefPtr<InspectorObject> reportObject = InspectorObject::create();
+    RefPtr<JSONObject> reportObject = JSONObject::create();
     reportObject->setObject("csp-report", cspReport.release());
 
     RefPtr<FormData> report = FormData::create(reportObject->toJSONString().utf8());
@@ -1806,7 +1802,7 @@
 
 void ContentSecurityPolicy::reportInvalidReflectedXSS(const String& invalidValue) const
 {
-    logToConsole("The 'reflected-xss' Content Security Policy directive has the invalid value \"" + invalidValue + "\". Value values are \"allow\", \"filter\", and \"block\".");
+    logToConsole("The 'reflected-xss' Content Security Policy directive has the invalid value \"" + invalidValue + "\". Valid values are \"allow\", \"filter\", and \"block\".");
 }
 
 void ContentSecurityPolicy::reportInvalidDirectiveValueCharacter(const String& directiveName, const String& value) const
diff --git a/Source/core/page/ContentSecurityPolicy.h b/Source/core/page/ContentSecurityPolicy.h
index 0dc62f8..35760a7 100644
--- a/Source/core/page/ContentSecurityPolicy.h
+++ b/Source/core/page/ContentSecurityPolicy.h
@@ -27,11 +27,10 @@
 #define ContentSecurityPolicy_h
 
 #include "bindings/v8/ScriptState.h"
-#include <wtf/PassOwnPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/text/TextPosition.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Vector.h>
+#include "wtf/PassOwnPtr.h"
+#include "wtf/Vector.h"
+#include "wtf/text/TextPosition.h"
+#include "wtf/text/WTFString.h"
 
 namespace WTF {
 class OrdinalNumber;
diff --git a/Source/core/page/ContextMenuController.cpp b/Source/core/page/ContextMenuController.cpp
index e781685..49e2a58 100644
--- a/Source/core/page/ContextMenuController.cpp
+++ b/Source/core/page/ContextMenuController.cpp
@@ -96,11 +96,11 @@
     if (!event->isMouseEvent())
         return nullptr;
 
-    MouseEvent* mouseEvent = static_cast<MouseEvent*>(event);
+    MouseEvent* mouseEvent = toMouseEvent(event);
     HitTestResult result(mouseEvent->absoluteLocation());
 
     if (Frame* frame = event->target()->toNode()->document()->frame())
-        result = frame->eventHandler()->hitTestResultAtPoint(mouseEvent->absoluteLocation());
+        result = frame->eventHandler()->hitTestResultAtPoint(mouseEvent->absoluteLocation(), HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
 
     if (!result.innerNonSharedNode())
         return nullptr;
diff --git a/Source/core/page/DOMSecurityPolicy.cpp b/Source/core/page/DOMSecurityPolicy.cpp
index 344d9ef..8056f70 100644
--- a/Source/core/page/DOMSecurityPolicy.cpp
+++ b/Source/core/page/DOMSecurityPolicy.cpp
@@ -26,7 +26,7 @@
 #include "config.h"
 #include "core/page/DOMSecurityPolicy.h"
 
-#include "core/dom/ContextDestructionObserver.h"
+#include "core/dom/ContextLifecycleObserver.h"
 #include "core/dom/DOMStringList.h"
 #include "core/dom/ScriptExecutionContext.h"
 #include "core/page/ContentSecurityPolicy.h"
@@ -80,7 +80,7 @@
 } // namespace
 
 DOMSecurityPolicy::DOMSecurityPolicy(ScriptExecutionContext* context)
-    : ContextDestructionObserver(context)
+    : ContextLifecycleObserver(context)
 {
     ScriptWrappable::init(this);
 }
diff --git a/Source/core/page/DOMSecurityPolicy.h b/Source/core/page/DOMSecurityPolicy.h
index 3cbe0da..6cb8a80 100644
--- a/Source/core/page/DOMSecurityPolicy.h
+++ b/Source/core/page/DOMSecurityPolicy.h
@@ -27,11 +27,9 @@
 #define DOMSecurityPolicy_h
 
 #include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/ContextDestructionObserver.h"
-#include <wtf/PassOwnPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/Vector.h>
+#include "core/dom/ContextLifecycleObserver.h"
+#include "wtf/RefCounted.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -39,7 +37,7 @@
 class DOMStringList;
 class Frame;
 
-class DOMSecurityPolicy : public RefCounted<DOMSecurityPolicy>, public ScriptWrappable, public ContextDestructionObserver {
+class DOMSecurityPolicy : public RefCounted<DOMSecurityPolicy>, public ScriptWrappable, public ContextLifecycleObserver {
 public:
     static PassRefPtr<DOMSecurityPolicy> create(ScriptExecutionContext* context)
     {
diff --git a/Source/core/page/DOMTimer.cpp b/Source/core/page/DOMTimer.cpp
index a8b7d04..e049d4b 100644
--- a/Source/core/page/DOMTimer.cpp
+++ b/Source/core/page/DOMTimer.cpp
@@ -31,9 +31,7 @@
 #include "core/dom/ScriptExecutionContext.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/inspector/InspectorInstrumentation.h"
-#include <wtf/CurrentTime.h>
-#include <wtf/HashSet.h>
-#include <wtf/StdLibExtras.h>
+#include "wtf/CurrentTime.h"
 
 using namespace std;
 
diff --git a/Source/core/page/DOMWindow.cpp b/Source/core/page/DOMWindow.cpp
index 65c7619..fe2afe1 100644
--- a/Source/core/page/DOMWindow.cpp
+++ b/Source/core/page/DOMWindow.cpp
@@ -27,14 +27,12 @@
 #include "config.h"
 #include "core/page/DOMWindow.h"
 
-#include <wtf/CurrentTime.h>
-#include <wtf/MainThread.h>
-#include <wtf/MathExtras.h>
-#include <wtf/text/Base64.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/MainThread.h"
+#include "wtf/MathExtras.h"
+#include "wtf/text/Base64.h"
+#include "wtf/text/WTFString.h"
 #include <algorithm>
 #include "RuntimeEnabledFeatures.h"
-#include "bindings/v8/ScheduledAction.h"
 #include "bindings/v8/ScriptCallStackFactory.h"
 #include "bindings/v8/ScriptController.h"
 #include "bindings/v8/SerializedScriptValue.h"
@@ -227,79 +225,11 @@
     return frame == page->mainFrame();
 }
 
-bool DOMWindow::dispatchAllPendingBeforeUnloadEvents()
-{
-    DOMWindowSet& set = windowsWithBeforeUnloadEventListeners();
-    if (set.isEmpty())
-        return true;
-
-    static bool alreadyDispatched = false;
-    ASSERT(!alreadyDispatched);
-    if (alreadyDispatched)
-        return true;
-
-    Vector<RefPtr<DOMWindow> > windows;
-    DOMWindowSet::iterator end = set.end();
-    for (DOMWindowSet::iterator it = set.begin(); it != end; ++it)
-        windows.append(it->key);
-
-    size_t size = windows.size();
-    for (size_t i = 0; i < size; ++i) {
-        DOMWindow* window = windows[i].get();
-        if (!set.contains(window))
-            continue;
-
-        Frame* frame = window->frame();
-        if (!frame)
-            continue;
-
-        if (!frame->loader()->shouldClose())
-            return false;
-    }
-
-    enableSuddenTermination();
-
-    alreadyDispatched = true;
-
-    return true;
-}
-
 unsigned DOMWindow::pendingUnloadEventListeners() const
 {
     return windowsWithUnloadEventListeners().count(const_cast<DOMWindow*>(this));
 }
 
-void DOMWindow::dispatchAllPendingUnloadEvents()
-{
-    DOMWindowSet& set = windowsWithUnloadEventListeners();
-    if (set.isEmpty())
-        return;
-
-    static bool alreadyDispatched = false;
-    ASSERT(!alreadyDispatched);
-    if (alreadyDispatched)
-        return;
-
-    Vector<RefPtr<DOMWindow> > windows;
-    DOMWindowSet::iterator end = set.end();
-    for (DOMWindowSet::iterator it = set.begin(); it != end; ++it)
-        windows.append(it->key);
-
-    size_t size = windows.size();
-    for (size_t i = 0; i < size; ++i) {
-        DOMWindow* window = windows[i].get();
-        if (!set.contains(window))
-            continue;
-
-        window->dispatchEvent(PageTransitionEvent::create(eventNames().pagehideEvent, false), window->document());
-        window->dispatchEvent(Event::create(eventNames().unloadEvent, false, false), window->document());
-    }
-
-    enableSuddenTermination();
-
-    alreadyDispatched = true;
-}
-
 // This function:
 // 1) Validates the pending changes are not changing any value to NaN; in that case keep original value.
 // 2) Constrains the window rect to the minimum window size and no bigger than the float rect's dimensions.
@@ -404,18 +334,18 @@
 
     m_document = document;
 
-    if (m_document) {
-        m_document->setDOMWindow(this);
-        if (!m_document->attached())
-            m_document->attach();
-        m_document->updateViewportArguments();
-    }
+    if (!m_document)
+        return;
+
+    m_document->setDOMWindow(this);
+    if (!m_document->attached())
+        m_document->attach();
 
     if (!m_frame)
         return;
 
-    if (m_document)
-        m_frame->script()->updateDocument();
+    m_frame->script()->updateDocument();
+    m_document->updateViewportArguments();
 
     if (m_frame->page() && m_frame->view()) {
         if (ScrollingCoordinator* scrollingCoordinator = m_frame->page()->scrollingCoordinator()) {
@@ -429,7 +359,7 @@
 
     if (m_frame->page() && m_frame->page()->mainFrame() == m_frame) {
         m_frame->page()->mainFrame()->notifyChromeClientWheelEventHandlerCountChanged();
-        if (m_document && m_document->hasTouchEventHandlers())
+        if (m_document->hasTouchEventHandlers())
             m_frame->page()->chrome().client()->needTouchEvents(true);
     }
 }
@@ -726,7 +656,7 @@
     if (!page)
         return 0;
 
-    RefPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
+    OwnPtr<StorageArea> storageArea = page->sessionStorage()->storageArea(document->securityOrigin());
     if (!storageArea->canAccessStorage(m_frame)) {
         ec = SECURITY_ERR;
         return 0;
@@ -765,7 +695,7 @@
     if (!page->settings()->localStorageEnabled())
         return 0;
 
-    RefPtr<StorageArea> storageArea = page->group().localStorage()->storageArea(document->securityOrigin());
+    OwnPtr<StorageArea> storageArea = StorageNamespace::localStorageArea(document->securityOrigin());
     if (!storageArea->canAccessStorage(m_frame)) {
         ec = SECURITY_ERR;
         return 0;
diff --git a/Source/core/page/DOMWindow.h b/Source/core/page/DOMWindow.h
index db31601..7f74875 100644
--- a/Source/core/page/DOMWindow.h
+++ b/Source/core/page/DOMWindow.h
@@ -107,9 +107,6 @@
 
         unsigned pendingUnloadEventListeners() const;
 
-        static bool dispatchAllPendingBeforeUnloadEvents();
-        static void dispatchAllPendingUnloadEvents();
-
         static FloatRect adjustWindowRect(Page*, const FloatRect& pendingChanges);
 
         bool allowPopUp(); // Call on first window, not target window.
diff --git a/Source/core/page/DragClient.h b/Source/core/page/DragClient.h
index d3e4d7f..c8d1b2b 100644
--- a/Source/core/page/DragClient.h
+++ b/Source/core/page/DragClient.h
@@ -28,22 +28,22 @@
 #define DragClient_h
 
 #include "core/page/DragActions.h"
-#include "core/platform/DragImage.h"
-#include "core/platform/graphics/IntPoint.h"
 
 namespace WebCore {
-    
-    class Clipboard;
-    class DragData;
-    class Frame;
-    
-    class DragClient {
-    public:
-        virtual DragDestinationAction actionMaskForDrag(DragData*) = 0;
-        virtual void startDrag(DragImageRef dragImage, const IntPoint& dragImageOrigin, const IntPoint& eventPos, Clipboard*, Frame*, bool linkDrag = false) = 0;
-        virtual ~DragClient() { }
-    };
-    
+
+class Clipboard;
+class DragData;
+class DragImage;
+class Frame;
+class IntPoint;
+
+class DragClient {
+public:
+    virtual DragDestinationAction actionMaskForDrag(DragData*) = 0;
+    virtual void startDrag(DragImage*, const IntPoint& dragImageOrigin, const IntPoint& eventPos, Clipboard*, Frame*, bool linkDrag = false) = 0;
+    virtual ~DragClient() { }
+};
+
 }
 
 #endif // !DragClient_h
diff --git a/Source/core/page/DragController.cpp b/Source/core/page/DragController.cpp
index a09c851..11065d2 100644
--- a/Source/core/page/DragController.cpp
+++ b/Source/core/page/DragController.cpp
@@ -27,8 +27,6 @@
 #include "config.h"
 #include "core/page/DragController.h"
 
-#include <wtf/CurrentTime.h>
-#include <wtf/RefPtr.h>
 #include "HTMLNames.h"
 #include "core/dom/Clipboard.h"
 #include "core/dom/ClipboardAccessPolicy.h"
@@ -63,6 +61,7 @@
 #include "core/page/Page.h"
 #include "core/page/Settings.h"
 #include "core/platform/DragData.h"
+#include "core/platform/DragImage.h"
 #include "core/platform/graphics/FloatRect.h"
 #include "core/platform/graphics/Image.h"
 #include "core/platform/graphics/ImageOrientation.h"
@@ -73,6 +72,10 @@
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
 #include "weborigin/SecurityOrigin.h"
+#include "wtf/CurrentTime.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/RefPtr.h"
 
 #if OS(WINDOWS)
 #include <windows.h>
@@ -80,12 +83,12 @@
 
 namespace WebCore {
 
-const int DragController::LinkDragBorderInset = 2;
-const int DragController::MaxOriginalImageArea = 1500 * 1500;
 const int DragController::DragIconRightInset = 7;
 const int DragController::DragIconBottomInset = 3;
 
-const float DragController::DragImageAlpha = 0.75f;
+static const int MaxOriginalImageArea = 1500 * 1500;
+static const int LinkDragBorderInset = 2;
+static const float DragImageAlpha = 0.75f;
 
 static PlatformMouseEvent createMouseEvent(DragData* dragData)
 {
@@ -538,7 +541,7 @@
     if (!m_page->mainFrame()->contentRenderer())
         return false;
 
-    result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point, HitTestRequest::ReadOnly | HitTestRequest::Active);
+    result = m_page->mainFrame()->eventHandler()->hitTestResultAtPoint(point);
 
     if (!result.innerNonSharedNode())
         return false;
@@ -684,7 +687,52 @@
     clipboard->declareAndWriteDragImage(node, !linkURL.isEmpty() ? linkURL : imageURL, label, source);
 }
 
-static IntPoint dragLocForDHTMLDrag(const IntPoint& mouseDraggedPoint, const IntPoint& dragOrigin, const IntPoint& dragImageOffset, bool isLinkImage)
+bool DragController::populateDragClipboard(Frame* src, const DragState& state, const IntPoint& dragOrigin)
+{
+    ASSERT(src);
+
+    if (!src->view() || !src->contentRenderer())
+        return false;
+
+    HitTestResult hitTestResult = src->eventHandler()->hitTestResultAtPoint(dragOrigin, HitTestRequest::ReadOnly | HitTestRequest::Active);
+    // FIXME: Can this even happen? I guess it's possible, but should verify
+    // with a layout test.
+    if (!state.m_dragSrc->contains(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.
+        return false;
+    }
+    const KURL& linkURL = hitTestResult.absoluteLinkURL();
+    const KURL& imageURL = hitTestResult.absoluteImageURL();
+
+    Clipboard* clipboard = state.m_dragClipboard.get();
+
+    Node* node = state.m_dragSrc.get();
+
+    if (state.m_dragType == DragSourceActionSelection) {
+        if (enclosingTextFormControl(src->selection()->start())) {
+            clipboard->writePlainText(src->editor()->selectedTextForClipboard());
+        } else {
+            RefPtr<Range> selectionRange = src->selection()->toNormalizedRange();
+            ASSERT(selectionRange);
+
+            clipboard->writeRange(selectionRange.get(), src);
+        }
+    } else if ((m_dragSourceAction & DragSourceActionImage)
+        && !imageURL.isEmpty() && node && node->isElementNode()) {
+        Element* element = toElement(node);
+        prepareClipboardForImageDrag(src, clipboard, element, linkURL, imageURL, hitTestResult.altDisplayString());
+    } else if ((m_dragSourceAction & DragSourceActionLink) && !linkURL.isEmpty()) {
+        // Simplify whitespace so the title put on the clipboard resembles what the user sees
+        // on the web page. This includes replacing newlines with spaces.
+        clipboard->writeURL(linkURL, hitTestResult.textContent().simplifyWhiteSpace(), src);
+    }
+    // FIXME: For DHTML/draggable element drags, write element markup to clipboard.
+    return true;
+}
+
+static IntPoint dragLocationForDHTMLDrag(const IntPoint& mouseDraggedPoint, const IntPoint& dragOrigin, const IntPoint& dragImageOffset, bool isLinkImage)
 {
     // dragImageOffset is the cursor position relative to the lower-left corner of the image.
     const int yOffset = -dragImageOffset.y();
@@ -695,9 +743,9 @@
     return IntPoint(dragOrigin.x() - dragImageOffset.x(), dragOrigin.y() + yOffset);
 }
 
-static IntPoint dragLocForSelectionDrag(Frame* src)
+static IntPoint dragLocationForSelectionDrag(Frame* sourceFrame)
 {
-    IntRect draggingRect = enclosingIntRect(src->selection()->bounds());
+    IntRect draggingRect = enclosingIntRect(sourceFrame->selection()->bounds());
     int xpos = draggingRect.maxX();
     xpos = draggingRect.x() < xpos ? draggingRect.x() : xpos;
     int ypos = draggingRect.maxY();
@@ -705,6 +753,58 @@
     return IntPoint(xpos, ypos);
 }
 
+static const IntSize& maxDragImageSize()
+{
+#if OS(DARWIN)
+    // Match Safari's drag image size.
+    static const IntSize maxDragImageSize(400, 400);
+#else
+    static const IntSize maxDragImageSize(200, 200);
+#endif
+    return maxDragImageSize;
+}
+
+static PassOwnPtr<DragImage> dragImageForImage(Element* element, Image* image, const IntPoint& dragOrigin, const IntRect& imageRect, IntPoint& dragLocation)
+{
+    OwnPtr<DragImage> dragImage;
+    IntPoint origin;
+
+    if (image->size().height() * image->size().width() <= MaxOriginalImageArea
+        && (dragImage = DragImage::create(image, element->renderer() ? element->renderer()->shouldRespectImageOrientation() : DoNotRespectImageOrientation))) {
+        IntSize originalSize = imageRect.size();
+        origin = imageRect.location();
+
+        dragImage->fitToMaxSize(imageRect.size(), maxDragImageSize());
+        dragImage->dissolveToFraction(DragImageAlpha);
+        IntSize newSize = dragImage->size();
+
+        // Properly orient the drag image and orient it differently if it's smaller than the original
+        float scale = newSize.width() / (float)originalSize.width();
+        float dx = origin.x() - dragOrigin.x();
+        dx *= scale;
+        origin.setX((int)(dx + 0.5));
+        float dy = origin.y() - dragOrigin.y();
+        dy *= scale;
+        origin.setY((int)(dy + 0.5));
+    }
+
+    dragLocation = dragOrigin + origin;
+    return dragImage.release();
+}
+
+static PassOwnPtr<DragImage> dragImageForLink(const KURL& linkURL, const String& linkText, float deviceScaleFactor, const IntPoint& mouseDraggedPoint, IntPoint& dragLoc)
+{
+    FontDescription fontDescription;
+    RenderTheme::defaultTheme()->systemFont(WebCore::CSSValueNone, fontDescription);
+    OwnPtr<DragImage> dragImage = DragImage::create(linkURL, linkText, fontDescription, deviceScaleFactor);
+
+    IntSize size = dragImage ? dragImage->size() : IntSize();
+    IntPoint dragImageOffset(-size.width() / 2, -LinkDragBorderInset);
+    dragLoc = IntPoint(mouseDraggedPoint.x() + dragImageOffset.x(), mouseDraggedPoint.y() + dragImageOffset.y());
+
+    return dragImage.release();
+}
+
 bool DragController::startDrag(Frame* src, const DragState& state, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin)
 {
     ASSERT(src);
@@ -712,27 +812,26 @@
     if (!src->view() || !src->contentRenderer())
         return false;
 
-    HitTestResult hitTestResult = src->eventHandler()->hitTestResultAtPoint(dragOrigin, HitTestRequest::ReadOnly | HitTestRequest::Active);
+    HitTestResult hitTestResult = src->eventHandler()->hitTestResultAtPoint(dragOrigin);
     if (!state.m_dragSrc->contains(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.
         return false;
-    KURL linkURL = hitTestResult.absoluteLinkURL();
-    KURL imageURL = hitTestResult.absoluteImageURL();
+    const KURL& linkURL = hitTestResult.absoluteLinkURL();
+    const KURL& imageURL = hitTestResult.absoluteImageURL();
 
     IntPoint mouseDraggedPoint = src->view()->windowToContents(dragEvent.position());
 
-    m_draggingImageURL = KURL();
     m_sourceDragOperation = srcOp;
 
-    DragImageRef dragImage = 0;
-    IntPoint dragLoc(0, 0);
-    IntPoint dragImageOffset(0, 0);
+    OwnPtr<DragImage> dragImage;
+    IntPoint dragLocation;
+    IntPoint dragOffset;
 
     Clipboard* clipboard = state.m_dragClipboard.get();
     if (state.m_dragType == DragSourceActionDHTML)
-        dragImage = clipboard->createDragImage(dragImageOffset);
+        dragImage = clipboard->createDragImage(dragOffset);
     if (state.m_dragType == DragSourceActionSelection || !imageURL.isEmpty() || !linkURL.isEmpty())
         // Selection, image, and link drags receive a default set of allowed drag operations that
         // follows from:
@@ -742,57 +841,33 @@
     // We allow DHTML/JS to set the drag image, even if its a link, image or text we're dragging.
     // This is in the spirit of the IE API, which allows overriding of pasteboard data and DragOp.
     if (dragImage) {
-        dragLoc = dragLocForDHTMLDrag(mouseDraggedPoint, dragOrigin, dragImageOffset, !linkURL.isEmpty());
-        m_dragOffset = dragImageOffset;
+        dragLocation = dragLocationForDHTMLDrag(mouseDraggedPoint, dragOrigin, dragOffset, !linkURL.isEmpty());
     }
 
-    bool startedDrag = true; // optimism - we almost always manage to start the drag
-
     Node* node = state.m_dragSrc.get();
 
-    Image* image = node->isElementNode() ? getImage(toElement(node)) : 0;
     if (state.m_dragType == DragSourceActionSelection) {
-        if (!clipboard->hasData()) {
-            if (enclosingTextFormControl(src->selection()->start()))
-                clipboard->writePlainText(src->editor()->selectedTextForClipboard());
-            else {
-                RefPtr<Range> selectionRange = src->selection()->toNormalizedRange();
-                ASSERT(selectionRange);
-
-                clipboard->writeRange(selectionRange.get(), src);
-            }
-        }
         if (!dragImage) {
-            dragImage = createDragImageForSelection(src->dragImageForSelection(), DragImageAlpha);
-            dragLoc = dragLocForSelectionDrag(src);
-            m_dragOffset = IntPoint(dragOrigin.x() - dragLoc.x(), dragOrigin.y() - dragLoc.y());
+            dragImage = src->dragImageForSelection();
+            if (dragImage)
+                dragImage->dissolveToFraction(DragImageAlpha);
+            dragLocation = dragLocationForSelectionDrag(src);
         }
-        doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
-    } else if (!imageURL.isEmpty() && node && node->isElementNode() && image && !image->isNull()
-               && (m_dragSourceAction & DragSourceActionImage)) {
+        doSystemDrag(dragImage.get(), dragLocation, dragOrigin, clipboard, src, false);
+    } else if ((m_dragSourceAction & DragSourceActionImage)
+        && !imageURL.isEmpty() && node && node->isElementNode()) {
+        Element* element = toElement(node);
+        Image* image = getImage(element);
+        if (!image || image->isNull())
+            return false;
         // We shouldn't be starting a drag for an image that can't provide an extension.
         // This is an early detection for problems encountered later upon drop.
         ASSERT(!image->filenameExtension().isEmpty());
-        Element* element = toElement(node);
-        if (!clipboard->hasData()) {
-            m_draggingImageURL = imageURL;
-            prepareClipboardForImageDrag(src, clipboard, element, linkURL, imageURL, hitTestResult.altDisplayString());
-        }
-
         if (!dragImage) {
-            IntRect imageRect = hitTestResult.imageRect();
-            imageRect.setLocation(m_page->mainFrame()->view()->rootViewToContents(src->view()->contentsToRootView(imageRect.location())));
-            doImageDrag(element, dragOrigin, hitTestResult.imageRect(), clipboard, src, m_dragOffset);
-        } else
-            // DHTML defined drag image
-            doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
-
-    } else if (!linkURL.isEmpty() && (m_dragSourceAction & DragSourceActionLink)) {
-        if (!clipboard->hasData())
-            // Simplify whitespace so the title put on the clipboard resembles what the user sees
-            // on the web page. This includes replacing newlines with spaces.
-            clipboard->writeURL(linkURL, hitTestResult.textContent().simplifyWhiteSpace(), src);
-
+            dragImage = dragImageForImage(element, image, dragOrigin, hitTestResult.imageRect(), dragLocation);
+        }
+        doSystemDrag(dragImage.get(), dragLocation, dragOrigin, clipboard, src, false);
+    } else if ((m_dragSourceAction & DragSourceActionLink) && !linkURL.isEmpty()) {
         if (src->selection()->isCaret() && src->selection()->isContentEditable()) {
             // a user can initiate a drag on a link without having any text
             // selected.  In this case, we should expand the selection to
@@ -804,77 +879,33 @@
         }
 
         if (!dragImage) {
-            FontDescription fontDescription;
-            RenderTheme::defaultTheme()->systemFont(WebCore::CSSValueNone, fontDescription);
-            float deviceScaleFactor = src->page() ? src->page()->deviceScaleFactor() : 1;
-            dragImage = createDragImageForLink(linkURL, hitTestResult.textContent(), fontDescription, deviceScaleFactor);
-            IntSize size = dragImageSize(dragImage);
-            m_dragOffset = IntPoint(-size.width() / 2, -LinkDragBorderInset);
-            dragLoc = IntPoint(mouseDraggedPoint.x() + m_dragOffset.x(), mouseDraggedPoint.y() + m_dragOffset.y());
+            ASSERT(src->page());
+            float deviceScaleFactor = src->page()->deviceScaleFactor();
+            dragImage = dragImageForLink(linkURL, hitTestResult.textContent(), deviceScaleFactor, mouseDraggedPoint, dragLocation);
         }
-        doSystemDrag(dragImage, dragLoc, mouseDraggedPoint, clipboard, src, true);
+        doSystemDrag(dragImage.get(), dragLocation, mouseDraggedPoint, clipboard, src, true);
     } else if (state.m_dragType == DragSourceActionDHTML) {
-        if (dragImage) {
-            ASSERT(m_dragSourceAction & DragSourceActionDHTML);
-            doSystemDrag(dragImage, dragLoc, dragOrigin, clipboard, src, false);
-        } else {
-            startedDrag = false;
-        }
+        if (!dragImage)
+            return false;
+        ASSERT(m_dragSourceAction & DragSourceActionDHTML);
+        doSystemDrag(dragImage.get(), dragLocation, dragOrigin, clipboard, src, false);
     } else {
         // draggableNode() determined an image or link node was draggable, but it turns out the
         // image or link had no URL, so there is nothing to drag.
-        startedDrag = false;
+        return false;
     }
 
-    if (dragImage)
-        deleteDragImage(dragImage);
-    return startedDrag;
+    return true;
 }
 
-void DragController::doImageDrag(Element* element, const IntPoint& dragOrigin, const IntRect& rect, Clipboard* clipboard, Frame* frame, IntPoint& dragImageOffset)
-{
-    IntPoint mouseDownPoint = dragOrigin;
-    DragImageRef dragImage;
-    IntPoint origin;
-
-    Image* image = getImage(element);
-    if (image && image->size().height() * image->size().width() <= MaxOriginalImageArea
-        && (dragImage = createDragImageFromImage(image, element->renderer() ? element->renderer()->shouldRespectImageOrientation() : DoNotRespectImageOrientation))) {
-        IntSize originalSize = rect.size();
-        origin = rect.location();
-
-        dragImage = fitDragImageToMaxSize(dragImage, rect.size(), maxDragImageSize());
-        dragImage = dissolveDragImageToFraction(dragImage, DragImageAlpha);
-        IntSize newSize = dragImageSize(dragImage);
-
-        // Properly orient the drag image and orient it differently if it's smaller than the original
-        float scale = newSize.width() / (float)originalSize.width();
-        float dx = origin.x() - mouseDownPoint.x();
-        dx *= scale;
-        origin.setX((int)(dx + 0.5));
-        float dy = origin.y() - mouseDownPoint.y();
-        dy *= scale;
-        origin.setY((int)(dy + 0.5));
-    } else {
-        dragImage = createDragImageIconForCachedImage(getCachedImage(element));
-        if (dragImage)
-            origin = IntPoint(DragIconRightInset - dragImageSize(dragImage).width(), DragIconBottomInset);
-    }
-
-    dragImageOffset = mouseDownPoint + origin;
-    doSystemDrag(dragImage, dragImageOffset, dragOrigin, clipboard, frame, false);
-
-    deleteDragImage(dragImage);
-}
-
-void DragController::doSystemDrag(DragImageRef image, const IntPoint& dragLoc, const IntPoint& eventPos, Clipboard* clipboard, Frame* frame, bool forLink)
+void DragController::doSystemDrag(DragImage* image, const IntPoint& dragLocation, const IntPoint& eventPos, Clipboard* clipboard, Frame* frame, bool forLink)
 {
     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
     RefPtr<Frame> frameProtector = m_page->mainFrame();
     RefPtr<FrameView> viewProtector = frameProtector->view();
-    m_client->startDrag(image, viewProtector->rootViewToContents(frame->view()->contentsToRootView(dragLoc)),
+    m_client->startDrag(image, viewProtector->rootViewToContents(frame->view()->contentsToRootView(dragLocation)),
         viewProtector->rootViewToContents(frame->view()->contentsToRootView(eventPos)), clipboard, frameProtector.get(), forLink);
     // DragClient::startDrag can cause our Page to dispear, deallocating |this|.
     if (!frameProtector->page())
@@ -918,17 +949,6 @@
 #endif
 }
 
-const IntSize& DragController::maxDragImageSize()
-{
-#if OS(DARWIN)
-    // Match Safari's drag image size.
-    static const IntSize maxDragImageSize(400, 400);
-#else
-    static const IntSize maxDragImageSize(200, 200);
-#endif
-    return maxDragImageSize;
-}
-
 void DragController::cleanupAfterSystemDrag()
 {
 }
diff --git a/Source/core/page/DragController.h b/Source/core/page/DragController.h
index e3132ac..553ccaa 100644
--- a/Source/core/page/DragController.h
+++ b/Source/core/page/DragController.h
@@ -27,9 +27,9 @@
 #define DragController_h
 
 #include "core/page/DragActions.h"
-#include "core/platform/DragImage.h"
 #include "core/platform/graphics/IntPoint.h"
 #include "weborigin/KURL.h"
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
@@ -37,6 +37,7 @@
     class Document;
     class DragClient;
     class DragData;
+    class DragImage;
     struct DragSession;
     struct DragState;
     class Element;
@@ -49,7 +50,7 @@
     class Page;
     class PlatformMouseEvent;
     class Range;
-    
+
     class DragController {
         WTF_MAKE_NONCOPYABLE(DragController); WTF_MAKE_FAST_ALLOCATED;
     public:
@@ -69,9 +70,6 @@
         void setDidInitiateDrag(bool initiated) { m_didInitiateDrag = initiated; } 
         bool didInitiateDrag() const { return m_didInitiateDrag; }
         DragOperation sourceDragOperation() const { return m_sourceDragOperation; }
-        const KURL& draggingImageURL() const { return m_draggingImageURL; }
-        void setDragOffset(const IntPoint& offset) { m_dragOffset = offset; }
-        const IntPoint& dragOffset() const { return m_dragOffset; }
         DragSourceAction dragSourceAction() const { return m_dragSourceAction; }
 
         Document* documentUnderMouse() const { return m_documentUnderMouse.get(); }
@@ -83,14 +81,11 @@
         
         void placeDragCaret(const IntPoint&);
         
+        bool populateDragClipboard(Frame* src, const DragState&, const IntPoint& dragOrigin);
         bool startDrag(Frame* src, const DragState&, DragOperation srcOp, const PlatformMouseEvent& dragEvent, const IntPoint& dragOrigin);
-        static const IntSize& maxDragImageSize();
         
-        static const int LinkDragBorderInset;
-        static const int MaxOriginalImageArea;
         static const int DragIconRightInset;
         static const int DragIconBottomInset;        
-        static const float DragImageAlpha;
 
     private:
         DragController(Page*, DragClient*);
@@ -110,9 +105,9 @@
         void mouseMovedIntoDocument(Document*);
 
         IntRect selectionDraggingRect(Frame*);
-        bool doDrag(Frame* src, Clipboard* clipboard, DragImageRef dragImage, const KURL& linkURL, const KURL& imageURL, Node* node, IntPoint& dragLoc, IntPoint& dragImageOffset);
+        bool doDrag(Frame* src, Clipboard*, DragImage*, const KURL& linkURL, const KURL& imageURL, Node*, IntPoint& dragLoc, IntPoint& dragImageOffset);
         void doImageDrag(Element*, const IntPoint&, const IntRect&, Clipboard*, Frame*, IntPoint&);
-        void doSystemDrag(DragImageRef, const IntPoint&, const IntPoint&, Clipboard*, Frame*, bool forLink);
+        void doSystemDrag(DragImage*, const IntPoint&, const IntPoint&, Clipboard*, Frame*, bool forLink);
         void cleanupAfterSystemDrag();
 
         Page* m_page;
@@ -127,8 +122,6 @@
         DragSourceAction m_dragSourceAction;
         bool m_didInitiateDrag;
         DragOperation m_sourceDragOperation; // Set in startDrag when a drag starts from a mouse down within WebKit
-        IntPoint m_dragOffset;
-        KURL m_draggingImageURL;
     };
 
 }
diff --git a/Source/core/page/EventHandler.cpp b/Source/core/page/EventHandler.cpp
index e78a8c8..1f176f1 100644
--- a/Source/core/page/EventHandler.cpp
+++ b/Source/core/page/EventHandler.cpp
@@ -429,14 +429,15 @@
 
     if (innerNode && innerNode->renderer()) {
         VisiblePosition pos(innerNode->renderer()->positionForPoint(result.localPoint()));
+        Position start = pos.deepEquivalent();
+        Position end = pos.deepEquivalent();
         if (pos.isNotNull()) {
-            RefPtr<Range> range = makeRange(pos, pos);
             Vector<DocumentMarker*> markers = innerNode->document()->markers()->markersInRange(
-                range.get(), DocumentMarker::Spelling | DocumentMarker::Grammar);
+                makeRange(pos, pos).get(), DocumentMarker::Spelling | DocumentMarker::Grammar);
             if (markers.size() == 1) {
-                range->setStart(innerNode, markers[0]->startOffset());
-                range->setEnd(innerNode, markers[0]->endOffset());
-                newSelection = VisibleSelection(range.get());
+                start.moveToOffset(markers[0]->startOffset());
+                end.moveToOffset(markers[0]->endOffset());
+                newSelection = VisibleSelection(start, end);
             }
         }
 
@@ -2079,7 +2080,7 @@
         // if the page already set it (e.g., by canceling default behavior).
         if (Page* page = m_frame->page()) {
             if (node && node->isMouseFocusable()) {
-                if (!page->focusController()->setFocusedNode(node, m_frame))
+                if (!page->focusController()->setFocusedNode(node, m_frame, FocusDirectionMouse))
                     swallowEvent = true;
             } else if (!node || !node->focused()) {
                 if (!page->focusController()->setFocusedNode(0, m_frame))
@@ -2405,7 +2406,7 @@
 #endif
     if (shouldLongPressSelectWord) {
         IntPoint hitTestPoint = m_frame->view()->windowToContents(gestureEvent.position());
-        HitTestResult result = hitTestResultAtPoint(hitTestPoint, HitTestRequest::ReadOnly | HitTestRequest::Active);
+        HitTestResult result = hitTestResultAtPoint(hitTestPoint);
         Node* innerNode = result.targetNode();
         if (!result.isLiveLink() && innerNode && (innerNode->isContentEditable() || innerNode->isTextNode())) {
             selectClosestWordFromHitTestResult(result, DontAppendTrailingWhitespace);
@@ -3278,6 +3279,12 @@
             }
         } 
         
+        Page* page = m_frame->page();
+        DragController* dragController = page ? page->dragController() : 0;
+        if (!dragController || !dragController->populateDragClipboard(m_frame, dragState(), m_mouseDownPos)) {
+            m_mouseDownMayStartDrag = false;
+            goto cleanupDrag;
+        }
         m_mouseDownMayStartDrag = dispatchDragSrcEvent(eventNames().dragstartEvent, m_mouseDown)
             && !m_frame->selection()->isInPasswordField();
         
@@ -3330,7 +3337,7 @@
 {
     // Platforms should differentiate real commands like selectAll from text input in disguise (like insertNewline),
     // and avoid dispatching text input events from keydown default handlers.
-    ASSERT(!underlyingEvent || !underlyingEvent->isKeyboardEvent() || static_cast<KeyboardEvent*>(underlyingEvent)->type() == eventNames().keypressEvent);
+    ASSERT(!underlyingEvent || !underlyingEvent->isKeyboardEvent() || toKeyboardEvent(underlyingEvent)->type() == eventNames().keypressEvent);
 
     if (!m_frame)
         return false;
diff --git a/Source/core/page/EventHandler.h b/Source/core/page/EventHandler.h
index c86d37d..bfec93f 100644
--- a/Source/core/page/EventHandler.h
+++ b/Source/core/page/EventHandler.h
@@ -33,15 +33,13 @@
 #include "core/page/FocusDirection.h"
 #include "core/platform/Cursor.h"
 #include "core/platform/PlatformMouseEvent.h"
-#include "core/platform/PlatformWheelEvent.h"
 #include "core/platform/ScrollTypes.h"
 #include "core/platform/Timer.h"
 #include "core/platform/graphics/LayoutPoint.h"
 #include "core/rendering/HitTestRequest.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/RefPtr.h>
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
@@ -111,7 +109,7 @@
     void dispatchFakeMouseMoveEventSoonInQuad(const FloatQuad&);
 
     HitTestResult hitTestResultAtPoint(const LayoutPoint&,
-        HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent,
+        HitTestRequest::HitTestRequestType hitType = HitTestRequest::ReadOnly | HitTestRequest::Active,
         const LayoutSize& padding = LayoutSize());
 
     bool mousePressed() const { return m_mousePressed; }
diff --git a/Source/core/page/EventSource.idl b/Source/core/page/EventSource.idl
index b50a876..490161e 100644
--- a/Source/core/page/EventSource.idl
+++ b/Source/core/page/EventSource.idl
@@ -30,7 +30,7 @@
  */
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     ActiveDOMObject,
     Constructor(DOMString url, optional Dictionary eventSourceInit),
     ConstructorCallWith=ScriptExecutionContext,
diff --git a/Source/core/page/FocusDirection.h b/Source/core/page/FocusDirection.h
index 0645a6f..4dcb6b8 100644
--- a/Source/core/page/FocusDirection.h
+++ b/Source/core/page/FocusDirection.h
@@ -34,7 +34,8 @@
         FocusDirectionUp,
         FocusDirectionDown,
         FocusDirectionLeft,
-        FocusDirectionRight
+        FocusDirectionRight,
+        FocusDirectionMouse
     };
 }
 
diff --git a/Source/core/page/Frame.cpp b/Source/core/page/Frame.cpp
index 6245cac..ddc44b6 100644
--- a/Source/core/page/Frame.cpp
+++ b/Source/core/page/Frame.cpp
@@ -31,69 +31,37 @@
 #include "core/page/Frame.h"
 
 #include "bindings/v8/ScriptController.h"
-#include "bindings/v8/ScriptSourceCode.h"
-#include "bindings/v8/ScriptValue.h"
-#include "bindings/v8/npruntime_impl.h"
-#include "core/css/CSSComputedStyleDeclaration.h"
-#include "core/css/StylePropertySet.h"
 #include "core/dom/DocumentType.h"
 #include "core/dom/Event.h"
-#include "core/dom/EventNames.h"
-#include "core/dom/NodeList.h"
-#include "core/dom/NodeTraversal.h"
-#include "core/dom/UserTypingGestureIndicator.h"
-#include "core/editing/ApplyStyleCommand.h"
 #include "core/editing/Editor.h"
 #include "core/editing/FrameSelection.h"
-#include "core/editing/TextIterator.h"
-#include "core/editing/VisibleUnits.h"
 #include "core/editing/htmlediting.h"
 #include "core/editing/markup.h"
-#include "core/html/HTMLDocument.h"
-#include "core/html/HTMLFormControlElement.h"
-#include "core/html/HTMLFormElement.h"
 #include "core/html/HTMLFrameElementBase.h"
-#include "core/html/HTMLTableCellElement.h"
-#include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
-#include "core/loader/TextResourceDecoder.h"
-#include "core/loader/cache/CachedCSSStyleSheet.h"
 #include "core/loader/cache/CachedResourceLoader.h"
 #include "core/page/Chrome.h"
 #include "core/page/ChromeClient.h"
 #include "core/page/DOMWindow.h"
-#include "core/page/EditorClient.h"
 #include "core/page/EventHandler.h"
 #include "core/page/FocusController.h"
 #include "core/page/FrameDestructionObserver.h"
 #include "core/page/FrameView.h"
-#include "core/page/Navigator.h"
 #include "core/page/Page.h"
-#include "core/page/PageGroup.h"
-#include "RuntimeEnabledFeatures.h"
-#include "core/page/Settings.h"
-#include "core/page/UserContentURLPattern.h"
 #include "core/page/animation/AnimationController.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
 #include "core/platform/DragImage.h"
-#include "core/platform/Logging.h"
-#include "core/platform/graphics/FloatQuad.h"
 #include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/GraphicsLayer.h"
 #include "core/platform/graphics/ImageBuffer.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/RenderLayerCompositor.h"
 #include "core/rendering/RenderPart.h"
-#include "core/rendering/RenderTableCell.h"
-#include "core/rendering/RenderTextControl.h"
-#include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
 #include "core/svg/SVGDocument.h"
-#include "core/svg/SVGDocumentExtensions.h"
-#include <wtf/PassOwnPtr.h>
-#include <wtf/RefCountedLeakCounter.h>
-#include <wtf/StdLibExtras.h>
+#include "wtf/PassOwnPtr.h"
+#include "wtf/RefCountedLeakCounter.h"
+#include "wtf/StdLibExtras.h"
 
 using namespace std;
 
@@ -433,7 +401,7 @@
 
 VisiblePosition Frame::visiblePositionForPoint(const IntPoint& framePoint)
 {
-    HitTestResult result = eventHandler()->hitTestResultAtPoint(framePoint, HitTestRequest::ReadOnly | HitTestRequest::Active);
+    HitTestResult result = eventHandler()->hitTestResultAtPoint(framePoint);
     Node* node = result.innerNonSharedNode();
     if (!node)
         return VisiblePosition();
@@ -455,7 +423,7 @@
     HitTestResult result = HitTestResult(pt);
 
     if (contentRenderer())
-        result = eventHandler()->hitTestResultAtPoint(pt);
+        result = eventHandler()->hitTestResultAtPoint(pt, HitTestRequest::ReadOnly | HitTestRequest::Active | HitTestRequest::DisallowShadowContent);
     return result.innerNode() ? result.innerNode()->document() : 0;
 }
 
@@ -658,10 +626,10 @@
     Color backgroundColor;
 };
 
-DragImageRef Frame::nodeImage(Node* node)
+PassOwnPtr<DragImage> Frame::nodeImage(Node* node)
 {
     if (!node->renderer())
-        return 0;
+        return nullptr;
 
     const ScopedFramePaintingState state(this, node);
 
@@ -675,7 +643,7 @@
     // Document::updateLayout may have blown away the original RenderObject.
     RenderObject* renderer = node->renderer();
     if (!renderer)
-      return 0;
+        return nullptr;
 
     LayoutRect topLevelRect;
     IntRect paintingRect = pixelSnappedIntRect(renderer->paintingRootRect(topLevelRect));
@@ -688,20 +656,20 @@
 
     OwnPtr<ImageBuffer> buffer(ImageBuffer::create(paintingRect.size(), deviceScaleFactor));
     if (!buffer)
-        return 0;
+        return nullptr;
     buffer->context()->translate(-paintingRect.x(), -paintingRect.y());
     buffer->context()->clip(FloatRect(0, 0, paintingRect.maxX(), paintingRect.maxY()));
 
     m_view->paintContents(buffer->context(), paintingRect);
 
     RefPtr<Image> image = buffer->copyImage();
-    return createDragImageFromImage(image.get(), renderer->shouldRespectImageOrientation());
+    return DragImage::create(image.get(), renderer->shouldRespectImageOrientation());
 }
 
-DragImageRef Frame::dragImageForSelection()
+PassOwnPtr<DragImage> Frame::dragImageForSelection()
 {
     if (!selection()->isRange())
-        return 0;
+        return nullptr;
 
     const ScopedFramePaintingState state(this, 0);
     m_view->setPaintBehavior(PaintBehaviorSelectionOnly | PaintBehaviorFlattenCompositingLayers);
@@ -717,14 +685,14 @@
 
     OwnPtr<ImageBuffer> buffer(ImageBuffer::create(paintingRect.size(), deviceScaleFactor));
     if (!buffer)
-        return 0;
+        return nullptr;
     buffer->context()->translate(-paintingRect.x(), -paintingRect.y());
     buffer->context()->clip(FloatRect(0, 0, paintingRect.maxX(), paintingRect.maxY()));
 
     m_view->paintContents(buffer->context(), paintingRect);
 
     RefPtr<Image> image = buffer->copyImage();
-    return createDragImageFromImage(image.get());
+    return DragImage::create(image.get());
 }
 
 } // namespace WebCore
diff --git a/Source/core/page/Frame.h b/Source/core/page/Frame.h
index 1794d23..26192df 100644
--- a/Source/core/page/Frame.h
+++ b/Source/core/page/Frame.h
@@ -33,9 +33,9 @@
 #include "core/page/AdjustViewSizeOrNot.h"
 #include "core/page/FrameTree.h"
 #include "core/platform/ScrollTypes.h"
-#include "core/platform/chromium/DragImageRef.h"
 #include "core/platform/graphics/IntSize.h"
-#include <wtf/RefCounted.h>
+#include "wtf/Forward.h"
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
@@ -43,6 +43,7 @@
     class Color;
     class DOMWindow;
     class Document;
+    class DragImage;
     class Editor;
     class Element;
     class EventHandler;
@@ -147,8 +148,8 @@
 
         String displayStringModifiedByEncoding(const String&) const;
 
-        DragImageRef nodeImage(Node*);
-        DragImageRef dragImageForSelection();
+        PassOwnPtr<DragImage> nodeImage(Node*);
+        PassOwnPtr<DragImage> dragImageForSelection();
 
         VisiblePosition visiblePositionForPoint(const IntPoint& framePoint);
         Document* documentAtPoint(const IntPoint& windowPoint);
diff --git a/Source/core/page/FrameTree.cpp b/Source/core/page/FrameTree.cpp
index d2878cd..f9e06a6 100644
--- a/Source/core/page/FrameTree.cpp
+++ b/Source/core/page/FrameTree.cpp
@@ -21,16 +21,14 @@
 #include "config.h"
 #include "core/page/FrameTree.h"
 
-#include <stdarg.h>
 #include "core/dom/Document.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
 #include "core/page/PageGroup.h"
-#include <wtf/StringExtras.h>
-#include <wtf/text/CString.h>
-#include <wtf/text/StringBuilder.h>
-#include <wtf/Vector.h>
+#include "wtf/Vector.h"
+#include "wtf/text/CString.h"
+#include "wtf/text/StringBuilder.h"
 
 using std::swap;
 
diff --git a/Source/core/page/FrameView.cpp b/Source/core/page/FrameView.cpp
index 754677d..a8c3719 100644
--- a/Source/core/page/FrameView.cpp
+++ b/Source/core/page/FrameView.cpp
@@ -36,13 +36,8 @@
 #include "core/dom/DocumentMarkerController.h"
 #include "core/dom/OverflowEvent.h"
 #include "core/editing/FrameSelection.h"
-#include "core/history/BackForwardController.h"
-#include "core/html/HTMLDocument.h"
 #include "core/html/HTMLFrameElement.h"
-#include "core/html/HTMLFrameSetElement.h"
 #include "core/html/HTMLPlugInImageElement.h"
-#include "core/inspector/InspectorClient.h"
-#include "core/inspector/InspectorController.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/FrameLoader.h"
 #include "core/loader/FrameLoaderClient.h"
@@ -65,8 +60,6 @@
 #include "core/platform/text/TextStream.h"
 #include "core/rendering/RenderArena.h"
 #include "core/rendering/RenderEmbeddedObject.h"
-#include "core/rendering/RenderFullScreen.h"
-#include "core/rendering/RenderIFrame.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderLayerBacking.h"
 #include "core/rendering/RenderLayerCompositor.h"
@@ -82,9 +75,8 @@
 #include "core/svg/SVGDocument.h"
 #include "core/svg/SVGSVGElement.h"
 
-#include <wtf/CurrentTime.h>
-#include <wtf/TemporaryChange.h>
-#include <wtf/UnusedParam.h>
+#include "wtf/CurrentTime.h"
+#include "wtf/TemporaryChange.h"
 
 #include "core/platform/chromium/TraceEvent.h"
 
@@ -152,7 +144,7 @@
 
     // paged-y always corresponds to TopToBottomPaginated or BottomToTopPaginated. If the WritingMode
     // is horizontal, then the direction of the horizontality dictates the choice. If the WritingMode
-    // is vertical, then we use TextDirection to choose between those options. 
+    // is vertical, then we use TextDirection to choose between those options.
     if (writingMode == TopToBottomWritingMode || (!isHorizontalWritingMode && textDirection == RTL))
         return Pagination::TopToBottomPaginated;
     return Pagination::BottomToTopPaginated;
@@ -225,7 +217,7 @@
         m_postLayoutTasksTimer.stop();
         m_actionScheduler->clear();
     }
-    
+
     removeFromAXObjectCache();
     resetScrollbars();
 
@@ -235,7 +227,7 @@
 
     setHasHorizontalScrollbar(false); // Remove native scrollbars now before we lose the connection to the HostWindow.
     setHasVerticalScrollbar(false);
-    
+
     ASSERT(!m_scrollCorner);
     ASSERT(m_actionScheduler->isEmpty());
 
@@ -342,7 +334,7 @@
             setMarginHeight(marginHeight);
     }
 }
-    
+
 void FrameView::prepareForDetach()
 {
     detachCustomScrollbars();
@@ -395,7 +387,7 @@
 void FrameView::clear()
 {
     setCanBlitOnScroll(true);
-    
+
     reset();
 
     if (m_frame) {
@@ -509,17 +501,17 @@
     Element* body = doc ? doc->body() : 0;
     if (body && body->renderer() && body->renderer()->style()->hasPseudoStyle(SCROLLBAR))
         return RenderScrollbar::createCustomScrollbar(this, orientation, body);
-    
+
     // If the <body> didn't have a custom style, then the root element might.
     Element* docElement = doc ? doc->documentElement() : 0;
     if (docElement && docElement->renderer() && docElement->renderer()->style()->hasPseudoStyle(SCROLLBAR))
         return RenderScrollbar::createCustomScrollbar(this, orientation, docElement);
-        
+
     // If we have an owning iframe/frame element, then it can set the custom scrollbar also.
     RenderPart* frameRenderer = m_frame->ownerRenderer();
     if (frameRenderer && frameRenderer->style()->hasPseudoStyle(SCROLLBAR))
         return RenderScrollbar::createCustomScrollbar(this, orientation, 0, m_frame.get());
-    
+
     // Nobody set a custom style, so we just use a native scrollbar.
     return ScrollView::createScrollbar(orientation);
 }
@@ -533,7 +525,7 @@
 
     ScrollView::setContentsSize(size);
     ScrollView::contentsResized();
-    
+
     Page* page = frame() ? frame()->page() : 0;
     if (!page)
         return;
@@ -543,7 +535,7 @@
     page->chrome().contentsSizeChanged(frame(), size); // Notify only.
 
     m_deferSetNeedsLayouts--;
-    
+
     if (!m_deferSetNeedsLayouts)
         m_setNeedsLayoutWasDeferred = false; // FIXME: Find a way to make the deferred layout actually happen.
 }
@@ -559,7 +551,7 @@
     const IntRect rect = renderView->documentRect();
     const IntSize& size = rect.size();
     ScrollView::setScrollOrigin(IntPoint(-rect.x(), -rect.y()), !m_frame->document()->printing(), size == contentsSize());
-    
+
     setContentsSize(size);
 }
 
@@ -595,7 +587,7 @@
             // Don't set it at all.
             ;
     }
-    
+
      switch (overflowY) {
         case OHIDDEN:
             vMode = ScrollbarAlwaysOff;
@@ -651,8 +643,8 @@
         hMode = ScrollbarAlwaysOff;
         vMode = ScrollbarAlwaysOff;
         return;
-    }  
-    
+    }
+
     if (m_canHaveScrollbars || strategy == RulesFromWebContentOnly) {
         hMode = ScrollbarAuto;
         // Seamless documents begin with heights of 0; we special case that here
@@ -664,7 +656,7 @@
         hMode = ScrollbarAlwaysOff;
         vMode = ScrollbarAlwaysOff;
     }
-    
+
     if (!m_layoutRoot) {
         Document* document = m_frame->document();
         Node* documentElement = document->documentElement();
@@ -682,7 +674,7 @@
             }
         } else if (rootRenderer)
             applyOverflowToViewport(rootRenderer, hMode, vMode);
-    }    
+    }
 }
 
 void FrameView::updateCompositingLayersAfterStyleChange()
@@ -808,7 +800,7 @@
 
     return false;
 }
-    
+
 bool FrameView::isSoftwareRenderable() const
 {
     RenderView* renderView = this->renderView();
@@ -876,6 +868,7 @@
         return;
 
     TRACE_EVENT0("webkit", "FrameView::layout");
+    TraceEvent::SamplingState0Scope("Blink\0Blink-Layout");
 
     // Protect the view from being deleted during layout (in recalcStyle)
     RefPtr<FrameView> protector(this);
@@ -893,7 +886,7 @@
         m_size.setWidth(layoutWidth());
         return;
     }
-    
+
     // we shouldn't enter layout() while painting
     ASSERT(!isPainting());
     if (isPainting())
@@ -936,7 +929,7 @@
 
         subtree = m_layoutRoot;
 
-        // If there is only one ref to this view left, then its going to be destroyed as soon as we exit, 
+        // 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;
@@ -972,13 +965,13 @@
 #ifdef INSTRUMENT_LAYOUT_SCHEDULING
             if (m_firstLayout && !m_frame->ownerElement())
                 printf("Elapsed time before first layout: %d\n", document->elapsedTime());
-#endif        
+#endif
         }
 
         autoSizeIfEnabled();
 
         ScrollbarMode hMode;
-        ScrollbarMode vMode;    
+        ScrollbarMode vMode;
         calculateScrollbarModesForLayout(hMode, vMode);
 
         m_doFullRepaint = !subtree && (m_firstLayout || toRenderView(root)->printing());
@@ -994,7 +987,7 @@
 
                     m_firstLayout = false;
                     m_firstLayoutCallbackPending = true;
-                    m_lastViewportSize = visibleContentRect(IncludeScrollbars).size();
+                    m_lastViewportSize = layoutSize(IncludeScrollbars);
                     m_lastZoomFactor = root->style()->zoom();
 
                     // Set the initial vMode to AlwaysOn if we're auto.
@@ -1046,8 +1039,10 @@
             root->layout();
 
             bool autosized = document->textAutosizer()->processSubtree(root);
-            if (autosized && root->needsLayout())
+            if (autosized && root->needsLayout()) {
+                TRACE_EVENT0("webkit", "2nd layout due to Text Autosizing");
                 root->layout();
+            }
 
             endDeferredRepaints();
             m_inLayout = false;
@@ -1203,12 +1198,12 @@
     m_widgetUpdateSet->remove(object);
 }
 
-void FrameView::setMediaType(const String& mediaType)
+void FrameView::setMediaType(const AtomicString& mediaType)
 {
     m_mediaType = mediaType;
 }
 
-String FrameView::mediaType() const
+AtomicString FrameView::mediaType() const
 {
     // See if we have an override type.
     String overrideType;
@@ -1227,7 +1222,7 @@
     } else {
         if (!m_mediaTypeWhenNotPrinting.isNull())
             setMediaType(m_mediaTypeWhenNotPrinting);
-        m_mediaTypeWhenNotPrinting = String();
+        m_mediaTypeWhenNotPrinting = nullAtom;
     }
 }
 
@@ -1379,7 +1374,7 @@
 
         if (renderer->isComposited())
             continue;
-    
+
         // Fixed items should always have layers.
         ASSERT(renderer->hasLayer());
         RenderLayer* layer = toRenderBoxModelObject(renderer)->layer();
@@ -1391,7 +1386,7 @@
         }
 
         if (layer->hasAncestorWithFilterOutsets()) {
-            // If the fixed layer has a blur/drop-shadow filter applied on at least one of its parents, we cannot 
+            // If the fixed layer has a blur/drop-shadow filter applied on at least one of its parents, we cannot
             // scroll using the fast path, otherwise the outsets of the filter will be moved around the page.
             return false;
         }
@@ -1528,7 +1523,7 @@
                 return true;
         }
     }
-  
+
     // Implement the rule that "" and "top" both mean top of page as in other browsers.
     if (!anchorNode && !(name.isEmpty() || equalIgnoringCase(name, "top")))
         return false;
@@ -1579,7 +1574,8 @@
     if (newScrollPosition == scrollPosition())
         return;
 
-    if (Page* page = m_frame->page())
+    Page* page = m_frame->page();
+    if (page && RuntimeEnabledFeatures::programmaticScrollNotificationsEnabled())
         page->chrome().client()->didProgrammaticallyScroll(m_frame.get(), newScrollPosition);
 
     if (requestScrollPositionUpdate(newScrollPosition))
@@ -1716,7 +1712,7 @@
 
         return;
     }
-    
+
     if (!shouldUpdate())
         return;
 
@@ -1778,7 +1774,7 @@
         startDeferredRepaintTimer(delay);
         return;
     }
-    
+
     doDeferredRepaints();
 }
 
@@ -1829,7 +1825,7 @@
     }
     m_repaintRects.clear();
     m_repaintCount = 0;
-    
+
     updateDeferredRepaintDelayAfterRepaint();
 }
 
@@ -1876,7 +1872,7 @@
     double timeSinceLastPaint = currentTime() - m_lastPaintTime;
     return max(0., m_deferredRepaintDelay - timeSinceLastPaint);
 }
-    
+
 void FrameView::deferredRepaintTimerFired(Timer<FrameView>*)
 {
     doDeferredRepaints();
@@ -2032,7 +2028,7 @@
     if (!m_frame->document()->ownerElement())
         printf("Layout timer unscheduled at %d\n", m_frame->document()->elapsedTime());
 #endif
-    
+
     m_layoutTimer.stop();
     m_delayedLayout = false;
 }
@@ -2189,7 +2185,7 @@
 {
     if (m_nestedLayoutCount > 1 || !m_widgetUpdateSet || m_widgetUpdateSet->isEmpty())
         return true;
-    
+
     size_t size = m_widgetUpdateSet->size();
 
     Vector<RenderObject*> objects;
@@ -2220,7 +2216,7 @@
             embeddedObject->deref(protectedArena.get());
         }
     }
-    
+
     return m_widgetUpdateSet->isEmpty();
 }
 
@@ -2273,8 +2269,7 @@
     }
 
     m_frame->loader()->didLayout(milestonesAchieved);
-    if (RuntimeEnabledFeatures::fontLoadEventsEnabled())
-        m_frame->document()->fontloader()->didLayout();
+    m_frame->document()->fontloader()->didLayout();
 
     RenderView* renderView = this->renderView();
     if (renderView)
@@ -2303,8 +2298,7 @@
     // Refetch render view since it can be destroyed by updateWidget() call above.
     renderView = this->renderView();
     if (renderView && !renderView->printing()) {
-        IntSize currentSize;
-        currentSize = visibleContentRect(IncludeScrollbars).size();
+        IntSize currentSize = layoutSize(IncludeScrollbars);
         float currentZoomFactor = renderView->style()->zoom();
         bool resized = !m_firstLayout && (currentSize != m_lastViewportSize || currentZoomFactor != m_lastZoomFactor);
         m_lastViewportSize = currentSize;
@@ -2423,26 +2417,26 @@
 {
     if (!m_viewportRenderer)
         return;
-    
+
     if (m_overflowStatusDirty) {
         m_horizontalOverflow = horizontalOverflow;
         m_verticalOverflow = verticalOverflow;
         m_overflowStatusDirty = false;
         return;
     }
-    
+
     bool horizontalOverflowChanged = (m_horizontalOverflow != horizontalOverflow);
     bool verticalOverflowChanged = (m_verticalOverflow != verticalOverflow);
-    
+
     if (horizontalOverflowChanged || verticalOverflowChanged) {
         m_horizontalOverflow = horizontalOverflow;
         m_verticalOverflow = verticalOverflow;
-        
+
         m_actionScheduler->scheduleEvent(OverflowEvent::create(horizontalOverflowChanged, horizontalOverflow,
             verticalOverflowChanged, verticalOverflow),
             m_viewportRenderer->node());
     }
-    
+
 }
 
 const Pagination& FrameView::pagination() const
@@ -2507,7 +2501,7 @@
         clipRect = pixelSnappedIntRect(enclosingLayer->childrenClipRect());
     else
         clipRect = pixelSnappedIntRect(enclosingLayer->selfClipRect());
-    clipRect = contentsToWindow(clipRect); 
+    clipRect = contentsToWindow(clipRect);
     return intersection(clipRect, windowClipRect());
 }
 
@@ -2719,7 +2713,7 @@
             if (RenderObject* renderer = body->renderer())
                 cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), renderer->style());
         }
-        
+
         if (!cornerStyle) {
             // If the <body> didn't have a custom style, then the root element might.
             if (Element* docElement = doc->documentElement()) {
@@ -2727,7 +2721,7 @@
                     cornerStyle = renderer->getUncachedPseudoStyle(PseudoStyleRequest(SCROLLBAR_CORNER), renderer->style());
             }
         }
-        
+
         if (!cornerStyle) {
             // If we have an owning iframe/frame element, then it can set the custom scrollbar also.
             if (RenderPart* renderer = m_frame->ownerRenderer())
@@ -2854,7 +2848,7 @@
     // We do a "fake" paint, and when the theme gets a paint call, it can then do an invalidate.
     // This is only done if the theme supports control tinting. It's up to the theme and platform
     // to define when controls get the tint and to call this function when that changes.
-    
+
     // Optimize the common case where we bring a window to the front while it's still empty.
     if (!m_frame || m_frame->document()->url().isEmpty())
         return;
@@ -2932,12 +2926,12 @@
     FontCachePurgePreventer fontCachePurgePreventer;
 
     PaintBehavior oldPaintBehavior = m_paintBehavior;
-    
+
     if (FrameView* parentView = parentFrameView()) {
         if (parentView->paintBehavior() & PaintBehaviorFlattenCompositingLayers)
             m_paintBehavior |= PaintBehaviorFlattenCompositingLayers;
     }
-    
+
     if (m_paintBehavior == PaintBehaviorNormal)
         document->markers()->invalidateRenderedRectsForMarkersInRect(rect);
 
@@ -3147,7 +3141,7 @@
 IntRect FrameView::convertToRenderer(const RenderObject* renderer, const IntRect& viewRect) const
 {
     IntRect rect = viewRect;
-    
+
     // Convert from FrameView coords into page ("absolute") coordinates.
     rect.moveBy(scrollPosition());
 
@@ -3185,17 +3179,17 @@
             RenderPart* renderer = m_frame->ownerRenderer();
             if (!renderer)
                 return localRect;
-                
+
             IntRect rect(localRect);
             // Add borders and padding??
             rect.move(renderer->borderLeft() + renderer->paddingLeft(),
                       renderer->borderTop() + renderer->paddingTop());
             return parentView->convertFromRenderer(renderer, rect);
         }
-        
+
         return Widget::convertToContainingView(localRect);
     }
-    
+
     return localRect;
 }
 
@@ -3216,10 +3210,10 @@
                       -renderer->borderTop() - renderer->paddingTop());
             return rect;
         }
-        
+
         return Widget::convertFromContainingView(parentRect);
     }
-    
+
     return parentRect;
 }
 
@@ -3233,7 +3227,7 @@
             RenderPart* renderer = m_frame->ownerRenderer();
             if (!renderer)
                 return localPoint;
-                
+
             IntPoint point(localPoint);
 
             // Add borders and padding
@@ -3241,10 +3235,10 @@
                        renderer->borderTop() + renderer->paddingTop());
             return parentView->convertFromRenderer(renderer, point);
         }
-        
+
         return Widget::convertToContainingView(localPoint);
     }
-    
+
     return localPoint;
 }
 
@@ -3265,10 +3259,10 @@
                        -renderer->borderTop() - renderer->paddingTop());
             return point;
         }
-        
+
         return Widget::convertFromContainingView(parentPoint);
     }
-    
+
     return parentPoint;
 }
 
@@ -3422,5 +3416,5 @@
         return frame()->document()->existingAXObjectCache();
     return 0;
 }
-    
+
 } // namespace WebCore
diff --git a/Source/core/page/FrameView.h b/Source/core/page/FrameView.h
index e21dd89..ac3c160 100644
--- a/Source/core/page/FrameView.h
+++ b/Source/core/page/FrameView.h
@@ -67,7 +67,7 @@
     virtual ~FrameView();
 
     virtual HostWindow* hostWindow() const;
-    
+
     virtual void invalidateRect(const IntRect&);
     virtual void setFrameRect(const IntRect&);
 
@@ -138,7 +138,7 @@
 
     bool isTransparent() const;
     void setTransparent(bool isTransparent);
-    
+
     // True if the FrameView is not transparent, and the base background color is opaque.
     bool hasOpaqueBackground() const;
 
@@ -151,7 +151,7 @@
     bool shouldUpdate() const;
 
     void adjustViewSize();
-    
+
     virtual IntRect windowClipRect(bool clipToContents = true) const;
     IntRect windowClipRectForFrameOwner(const HTMLFrameOwnerElement*, bool clipToLayerContents) const;
 
@@ -169,11 +169,11 @@
     void setScrollPositionNonProgrammatically(const IntPoint&);
 
     // This is different than visibleContentRect() in that it ignores negative (or overly positive)
-    // offsets from rubber-banding, and it takes zooming into account. 
+    // offsets from rubber-banding, and it takes zooming into account.
     LayoutRect viewportConstrainedVisibleContentRect() const;
 
-    String mediaType() const;
-    void setMediaType(const String&);
+    AtomicString mediaType() const;
+    void setMediaType(const AtomicString&);
     void adjustMediaTypeForPrinting(bool printing);
 
     void setCannotBlitToWindow();
@@ -238,7 +238,7 @@
     Color documentBackgroundColor() const;
 
     static double currentPaintTimeStamp() { return sCurrentPaintTimeStamp; } // returns 0 if not painting
-    
+
     void updateLayoutAndStyleIfNeededRecursive();
 
     void incrementVisuallyNonEmptyCharacterCount(unsigned);
@@ -290,7 +290,7 @@
     void setAnimatorsAreActive();
 
     RenderBox* embeddedContentBox() const;
-    
+
     void setTracksRepaints(bool);
     bool isTrackingRepaints() const { return m_isTrackingRepaints; }
     void resetTrackedRepaints();
@@ -427,18 +427,18 @@
 
     virtual AXObjectCache* axObjectCache() const;
     void removeFromAXObjectCache();
-    
+
     static double sCurrentPaintTimeStamp; // used for detecting decoded resource thrash in the cache
 
     LayoutSize m_size;
     LayoutSize m_margins;
-    
+
     typedef HashSet<RenderObject*> RenderObjectSet;
     OwnPtr<RenderObjectSet> m_widgetUpdateSet;
     RefPtr<Frame> m_frame;
 
     bool m_doFullRepaint;
-    
+
     bool m_canHaveScrollbars;
     bool m_cannotBlitToWindow;
     bool m_isOverlapped;
@@ -450,7 +450,7 @@
     Timer<FrameView> m_layoutTimer;
     bool m_delayedLayout;
     RenderObject* m_layoutRoot;
-    
+
     bool m_layoutSchedulingEnabled;
     bool m_inLayout;
     bool m_doingPreLayoutStyleUpdate;
@@ -466,14 +466,14 @@
     IntSize m_lastViewportSize;
     float m_lastZoomFactor;
 
-    String m_mediaType;
-    String m_mediaTypeWhenNotPrinting;
+    AtomicString m_mediaType;
+    AtomicString m_mediaTypeWhenNotPrinting;
 
     OwnPtr<FrameActionScheduler> m_actionScheduler;
 
     bool m_overflowStatusDirty;
     bool m_horizontalOverflow;
-    bool m_verticalOverflow;    
+    bool m_verticalOverflow;
     RenderObject* m_viewportRenderer;
 
     Pagination m_pagination;
diff --git a/Source/core/page/GroupSettings.cpp b/Source/core/page/GroupSettings.cpp
deleted file mode 100644
index b87a12b..0000000
--- a/Source/core/page/GroupSettings.cpp
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/page/GroupSettings.h"
-
-namespace WebCore {
-
-GroupSettings::GroupSettings()
-    : m_localStorageQuotaBytes(5 * 1024 * 1024) // Suggested by the HTML5 spec.
-    , m_indexedDBQuotaBytes(5 * 1024 * 1024)
-{
-}
-
-void GroupSettings::setLocalStorageQuotaBytes(unsigned quota)
-{
-    m_localStorageQuotaBytes = quota;
-}
-
-void GroupSettings::setIndexedDBDatabasePath(const String& path)
-{
-    m_indexedDBDatabasePath = path;
-}
-
-void GroupSettings::setIndexedDBQuotaBytes(int64_t quota)
-{
-    m_indexedDBQuotaBytes = quota;
-}
-
-
-} // namespace WebCore
diff --git a/Source/core/page/GroupSettings.h b/Source/core/page/GroupSettings.h
deleted file mode 100644
index 603d06a..0000000
--- a/Source/core/page/GroupSettings.h
+++ /dev/null
@@ -1,63 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
- 
-#ifndef GroupSettings_h
-#define GroupSettings_h
-
-#include <wtf/PassOwnPtr.h>
-#include <wtf/text/WTFString.h>
-
-namespace WebCore {
-
-class PageGroup;
-
-class GroupSettings {
-    WTF_MAKE_NONCOPYABLE(GroupSettings); WTF_MAKE_FAST_ALLOCATED;
-public:
-    static PassOwnPtr<GroupSettings> create()
-    {
-        return adoptPtr(new GroupSettings());
-    }
-
-    void setLocalStorageQuotaBytes(unsigned);
-    unsigned localStorageQuotaBytes() const { return m_localStorageQuotaBytes; }
-
-    void setIndexedDBQuotaBytes(int64_t);
-    int64_t indexedDBQuotaBytes() const { return m_indexedDBQuotaBytes; }
-
-    void setIndexedDBDatabasePath(const String&);
-    const String& indexedDBDatabasePath() const { return m_indexedDBDatabasePath; }
-
-private:
-    GroupSettings();
-
-    unsigned m_localStorageQuotaBytes;
-    String m_indexedDBDatabasePath;
-    int64_t m_indexedDBQuotaBytes;
-};
-
-} // namespace WebCore
-
-#endif // GroupSettings_h
diff --git a/Source/core/page/Location.idl b/Source/core/page/Location.idl
index 96b211a..c4d6693 100644
--- a/Source/core/page/Location.idl
+++ b/Source/core/page/Location.idl
@@ -29,20 +29,20 @@
 [
     CheckSecurity
 ] interface Location {
-    [SetterCallWith=ActiveWindow|FirstWindow, DoNotCheckSecurityOnSetter, Unforgeable] attribute DOMString href;
+    [SetterCallWith=ActiveWindow&FirstWindow, DoNotCheckSecurityOnSetter, Unforgeable] attribute DOMString href;
 
-    [CallWith=ActiveWindow|FirstWindow, DoNotCheckSecurity, Unforgeable, ReadOnly, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds] void assign([Default=Undefined] optional DOMString url);
-    [CallWith=ActiveWindow|FirstWindow, DoNotCheckSecurity, Unforgeable, ReadOnly, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds] void replace([Default=Undefined] optional DOMString url);
+    [CallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity, Unforgeable, ReadOnly, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds] void assign([Default=Undefined] optional DOMString url);
+    [CallWith=ActiveWindow&FirstWindow, DoNotCheckSecurity, Unforgeable, ReadOnly, PerWorldBindings, ActivityLog=AccessForIsolatedWorlds] void replace([Default=Undefined] optional DOMString url);
     [CallWith=ActiveWindow, DoNotCheckSecurity, Unforgeable, ReadOnly] void reload();
 
     // URI decomposition attributes
-    [SetterCallWith=ActiveWindow|FirstWindow, SetterRaisesException] attribute DOMString protocol;
-    [SetterCallWith=ActiveWindow|FirstWindow] attribute DOMString host;
-    [SetterCallWith=ActiveWindow|FirstWindow] attribute DOMString hostname;
-    [SetterCallWith=ActiveWindow|FirstWindow] attribute DOMString port;
-    [SetterCallWith=ActiveWindow|FirstWindow] attribute DOMString pathname;
-    [SetterCallWith=ActiveWindow|FirstWindow] attribute DOMString search;
-    [SetterCallWith=ActiveWindow|FirstWindow] attribute DOMString hash;
+    [SetterCallWith=ActiveWindow&FirstWindow, SetterRaisesException] attribute DOMString protocol;
+    [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString host;
+    [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString hostname;
+    [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString port;
+    [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString pathname;
+    [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString search;
+    [SetterCallWith=ActiveWindow&FirstWindow] attribute DOMString hash;
 
     readonly attribute DOMString origin;
 
diff --git a/Source/core/page/Navigator.cpp b/Source/core/page/Navigator.cpp
index 4c6df2c..9d6aca8 100644
--- a/Source/core/page/Navigator.cpp
+++ b/Source/core/page/Navigator.cpp
@@ -23,8 +23,6 @@
 #include "config.h"
 #include "core/page/Navigator.h"
 
-#include <wtf/HashSet.h>
-#include <wtf/StdLibExtras.h>
 #include "bindings/v8/ScriptController.h"
 #include "core/dom/Document.h"
 #include "core/loader/CookieJar.h"
diff --git a/Source/core/page/Navigator.h b/Source/core/page/Navigator.h
index 01b042c..0d279bd 100644
--- a/Source/core/page/Navigator.h
+++ b/Source/core/page/Navigator.h
@@ -24,11 +24,10 @@
 #include "core/page/DOMWindowProperty.h"
 #include "core/page/NavigatorBase.h"
 #include "core/platform/Supplementable.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
+#include "wtf/Forward.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/page/Page.cpp b/Source/core/page/Page.cpp
index 06702ae..31a8fa1 100644
--- a/Source/core/page/Page.cpp
+++ b/Source/core/page/Page.cpp
@@ -20,66 +20,45 @@
 #include "config.h"
 #include "core/page/Page.h"
 
-#include "bindings/v8/ScriptController.h"
 #include "core/dom/ClientRectList.h"
 #include "core/dom/DocumentMarkerController.h"
 #include "core/dom/DocumentStyleSheetCollection.h"
 #include "core/dom/Event.h"
 #include "core/dom/EventNames.h"
-#include "core/dom/ExceptionCode.h"
-#include "core/dom/ExceptionCodePlaceholder.h"
 #include "core/dom/VisitedLinkState.h"
 #include "core/dom/WebCoreMemoryInstrumentation.h"
 #include "core/editing/Editor.h"
 #include "core/history/BackForwardController.h"
 #include "core/history/HistoryItem.h"
-#include "core/html/HTMLElement.h"
-#include "core/html/VoidCallback.h"
 #include "core/inspector/InspectorController.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/FrameLoader.h"
-#include "core/loader/FrameLoaderClient.h"
 #include "core/loader/ProgressTracker.h"
-#include "core/loader/TextResourceDecoder.h"
 #include "core/page/AutoscrollController.h"
 #include "core/page/Chrome.h"
-#include "core/page/ChromeClient.h"
-#include "core/page/ContextMenuClient.h"
 #include "core/page/ContextMenuController.h"
 #include "core/page/DOMTimer.h"
-#include "core/page/DOMWindow.h"
 #include "core/page/DragController.h"
-#include "core/page/EditorClient.h"
 #include "core/page/FocusController.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameTree.h"
 #include "core/page/FrameView.h"
-#include "core/page/Navigator.h"
 #include "core/page/PageConsole.h"
 #include "core/page/PageGroup.h"
 #include "core/page/PointerLockController.h"
-#include "RuntimeEnabledFeatures.h"
 #include "core/page/Settings.h"
-#include "core/page/animation/AnimationController.h"
 #include "core/page/scrolling/ScrollingCoordinator.h"
-#include "core/platform/FileSystem.h"
-#include "core/platform/Logging.h"
-#include "core/platform/SharedBuffer.h"
-#include "core/platform/Widget.h"
 #include "core/platform/network/NetworkStateNotifier.h"
 #include "core/plugins/PluginData.h"
 #include "core/rendering/RenderArena.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
-#include "core/rendering/RenderWidget.h"
-#include "core/storage/StorageArea.h"
 #include "core/storage/StorageNamespace.h"
-#include "weborigin/SchemeRegistry.h"
 #include "wtf/HashMap.h"
+#include "wtf/MemoryInstrumentationHashSet.h"
 #include "wtf/RefCountedLeakCounter.h"
 #include "wtf/StdLibExtras.h"
 #include "wtf/text/Base64.h"
-#include "wtf/text/StringHash.h"
 
 namespace WebCore {
 
@@ -610,19 +589,11 @@
 
 StorageNamespace* Page::sessionStorage(bool optionalCreate)
 {
-    if (!m_sessionStorage && optionalCreate) {
-        // FIXME: the quota value here is not needed or used in blink, crbug/230987
-        const unsigned int kBogusQuota = UINT_MAX;
-        m_sessionStorage = StorageNamespace::sessionStorageNamespace(this, kBogusQuota);
-    }
+    if (!m_sessionStorage && optionalCreate)
+        m_sessionStorage = StorageNamespace::sessionStorageNamespace(this);
     return m_sessionStorage.get();
 }
 
-void Page::setSessionStorage(PassRefPtr<StorageNamespace> newStorage)
-{
-    m_sessionStorage = newStorage;
-}
-
 void Page::setTimerAlignmentInterval(double interval)
 {
     if (interval == m_timerAlignmentInterval)
diff --git a/Source/core/page/Page.h b/Source/core/page/Page.h
index 9e14026..e857963 100644
--- a/Source/core/page/Page.h
+++ b/Source/core/page/Page.h
@@ -25,16 +25,14 @@
 #include "core/page/LayoutMilestones.h"
 #include "core/page/PageVisibilityState.h"
 #include "core/page/UseCounter.h"
-#include "core/platform/PlatformScreen.h"
 #include "core/platform/Supplementable.h"
 #include "core/platform/graphics/LayoutRect.h"
 #include "core/platform/graphics/Region.h"
 #include "core/rendering/Pagination.h"
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/Forward.h"
+#include "wtf/HashSet.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/text/WTFString.h"
 
 #if OS(SOLARIS)
 #include <sys/time.h> // For time_t structure.
@@ -228,7 +226,6 @@
     static void visitedStateChanged(PageGroup*, LinkHash visitedHash);
 
     StorageNamespace* sessionStorage(bool optionalCreate = true);
-    void setSessionStorage(PassRefPtr<StorageNamespace>);
 
     // Don't allow more than a certain number of frames in a page.
     // This seems like a reasonable upper bound, and otherwise mutually
@@ -326,7 +323,7 @@
 
     RefPtr<PageGroup> m_group;
 
-    RefPtr<StorageNamespace> m_sessionStorage;
+    OwnPtr<StorageNamespace> m_sessionStorage;
 
     double m_timerAlignmentInterval;
 
diff --git a/Source/core/page/PageConsole.cpp b/Source/core/page/PageConsole.cpp
index 1592b92..07bbb25 100644
--- a/Source/core/page/PageConsole.cpp
+++ b/Source/core/page/PageConsole.cpp
@@ -29,7 +29,6 @@
 #include "config.h"
 #include "core/page/PageConsole.h"
 
-#include <stdio.h>
 #include "core/dom/Document.h"
 #include "core/dom/ScriptableDocumentParser.h"
 #include "core/inspector/ConsoleAPITypes.h"
@@ -39,9 +38,7 @@
 #include "core/page/ChromeClient.h"
 #include "core/page/ConsoleTypes.h"
 #include "core/page/Page.h"
-#include <wtf/text/CString.h>
-#include <wtf/text/WTFString.h>
-#include <wtf/UnusedParam.h>
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
@@ -69,15 +66,15 @@
         if (!parser->isWaitingForScripts() && !parser->isExecutingScript())
             line = parser->lineNumber().oneBasedInt();
     }
-    addMessage(source, level, message, url, line, 0, 0, requestIdentifier);
+    addMessage(source, level, message, url, line, 0, 0, 0, requestIdentifier);
 }
 
 void PageConsole::addMessage(MessageSource source, MessageLevel level, const String& message, PassRefPtr<ScriptCallStack> callStack)
 {
-    addMessage(source, level, message, String(), 0, callStack, 0);
+    addMessage(source, level, message, String(), 0, 0, callStack, 0);
 }
 
-void PageConsole::addMessage(MessageSource source, MessageLevel level, const String& message, const String& url, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state, unsigned long requestIdentifier)
+void PageConsole::addMessage(MessageSource source, MessageLevel level, const String& message, const String& url, unsigned lineNumber, unsigned columnNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state, unsigned long requestIdentifier)
 {
     if (muteCount && source != ConsoleAPIMessageSource)
         return;
@@ -89,7 +86,7 @@
     if (callStack)
         InspectorInstrumentation::addMessageToConsole(page, source, LogMessageType, level, message, callStack, requestIdentifier);
     else
-        InspectorInstrumentation::addMessageToConsole(page, source, LogMessageType, level, message, url, lineNumber, state, requestIdentifier);
+        InspectorInstrumentation::addMessageToConsole(page, source, LogMessageType, level, message, url, lineNumber, columnNumber, state, requestIdentifier);
 
     if (source == CSSMessageSource)
         return;
diff --git a/Source/core/page/PageConsole.h b/Source/core/page/PageConsole.h
index cc82a2b..622ecf1 100644
--- a/Source/core/page/PageConsole.h
+++ b/Source/core/page/PageConsole.h
@@ -32,9 +32,8 @@
 #include "bindings/v8/ScriptState.h"
 #include "core/inspector/ScriptCallStack.h"
 #include "core/page/ConsoleTypes.h"
-#include <wtf/BitVector.h>
-#include <wtf/Forward.h>
-#include <wtf/PassOwnPtr.h>
+#include "wtf/Forward.h"
+#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
@@ -48,7 +47,7 @@
     static PassOwnPtr<PageConsole> create(Page* page) { return adoptPtr(new PageConsole(page)); }
     virtual ~PageConsole();
 
-    void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> = 0, ScriptState* = 0, unsigned long requestIdentifier = 0);
+    void addMessage(MessageSource, MessageLevel, const String& message, const String& sourceURL, unsigned lineNumber, unsigned columnNumber = 0, PassRefPtr<ScriptCallStack> = 0, ScriptState* = 0, unsigned long requestIdentifier = 0);
     void addMessage(MessageSource, MessageLevel, const String& message, PassRefPtr<ScriptCallStack>);
     void addMessage(MessageSource, MessageLevel, const String& message, unsigned long requestIdentifier = 0, Document* = 0);
 
diff --git a/Source/core/page/PageGroup.cpp b/Source/core/page/PageGroup.cpp
index 645a54f..af42733 100644
--- a/Source/core/page/PageGroup.cpp
+++ b/Source/core/page/PageGroup.cpp
@@ -29,14 +29,11 @@
 #include "core/dom/Document.h"
 #include "core/dom/DocumentStyleSheetCollection.h"
 #include "core/page/Frame.h"
-#include "core/page/GroupSettings.h"
 #include "core/page/Page.h"
-#include "core/storage/StorageNamespace.h"
 
 namespace WebCore {
 
 PageGroup::PageGroup()
-    : m_groupSettings(GroupSettings::create())
 {
 }
 
@@ -71,16 +68,6 @@
     m_pages.remove(page);
 }
 
-StorageNamespace* PageGroup::localStorage()
-{
-    if (!m_localStorage) {
-        unsigned quota = m_groupSettings->localStorageQuotaBytes();
-        m_localStorage = StorageNamespace::localStorageNamespace(quota);
-    }
-
-    return m_localStorage.get();
-}
-
 void PageGroup::addUserStyleSheet(const String& source, const KURL& url,
                                   const Vector<String>& whitelist, const Vector<String>& blacklist,
                                   UserContentInjectedFrames injectedFrames,
diff --git a/Source/core/page/PageGroup.h b/Source/core/page/PageGroup.h
index eee9fc3..f884581 100644
--- a/Source/core/page/PageGroup.h
+++ b/Source/core/page/PageGroup.h
@@ -28,19 +28,16 @@
 
 #include "core/page/UserStyleSheet.h"
 #include "core/platform/Supplementable.h"
-#include <wtf/HashSet.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/text/StringHash.h>
+#include "wtf/HashSet.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
     class KURL;
-    class GroupSettings;
     class Page;
     class SecurityOrigin;
-    class StorageNamespace;
 
     class PageGroup : public Supplementable<PageGroup>, public RefCounted<PageGroup> {
         WTF_MAKE_NONCOPYABLE(PageGroup); WTF_MAKE_FAST_ALLOCATED;
@@ -56,9 +53,6 @@
         void addPage(Page*);
         void removePage(Page*);
 
-        StorageNamespace* localStorage();
-        bool hasLocalStorage() { return m_localStorage; }
-
         void addUserStyleSheet(const String& source, const KURL&,
                                const Vector<String>& whitelist, const Vector<String>& blacklist,
                                UserContentInjectedFrames,
@@ -69,17 +63,13 @@
 
         const UserStyleSheetVector& userStyleSheets() const { return m_userStyleSheets; }
 
-        GroupSettings* groupSettings() const { return m_groupSettings.get(); }
-
     private:
         PageGroup();
 
         void invalidatedInjectedStyleSheetCacheInAllFrames();
 
         HashSet<Page*> m_pages;
-        RefPtr<StorageNamespace> m_localStorage;
         UserStyleSheetVector m_userStyleSheets;
-        OwnPtr<GroupSettings> m_groupSettings;
     };
 
 } // namespace WebCore
diff --git a/Source/core/page/PageSerializer.cpp b/Source/core/page/PageSerializer.cpp
index 6593e3e..f5a46cc 100644
--- a/Source/core/page/PageSerializer.cpp
+++ b/Source/core/page/PageSerializer.cpp
@@ -204,7 +204,7 @@
         return;
     }
     String text = accumulator.serializeNodes(document->documentElement(), IncludeNode);
-    CString frameHTML = textEncoding.encode(text.characters(), text.length(), WTF::EntitiesForUnencodables);
+    CString frameHTML = textEncoding.encode(text, WTF::EntitiesForUnencodables);
     m_resources->append(SerializedResource(url, document->suggestedMIMEType(), SharedBuffer::create(frameHTML.data(), frameHTML.length())));
     m_resourceURLs.add(url);
 
@@ -216,7 +216,7 @@
         Element* element = toElement(node);
         // We have to process in-line style as it might contain some resources (typically background images).
         if (element->isStyledElement())
-            retrieveResourcesForProperties(static_cast<StyledElement*>(element)->inlineStyle(), document);
+            retrieveResourcesForProperties(element->inlineStyle(), document);
 
         if (element->hasTagName(HTMLNames::imgTag)) {
             HTMLImageElement* imageElement = toHTMLImageElement(element);
@@ -231,7 +231,7 @@
                 ASSERT(m_resourceURLs.contains(url));
             }
         } else if (element->hasTagName(HTMLNames::styleTag)) {
-            HTMLStyleElement* styleElement = static_cast<HTMLStyleElement*>(element);
+            HTMLStyleElement* styleElement = toHTMLStyleElement(element);
             if (CSSStyleSheet* sheet = styleElement->sheet())
                 serializeCSSStyleSheet(sheet, KURL());
         }
@@ -272,7 +272,7 @@
         WTF::TextEncoding textEncoding(styleSheet->contents()->charset());
         ASSERT(textEncoding.isValid());
         String textString = cssText.toString();
-        CString text = textEncoding.encode(textString.characters(), textString.length(), WTF::EntitiesForUnencodables);
+        CString text = textEncoding.encode(textString, WTF::EntitiesForUnencodables);
         m_resources->append(SerializedResource(url, String("text/css"), SharedBuffer::create(text.data(), text.length())));
         m_resourceURLs.add(url);
     }
diff --git a/Source/core/page/PageSerializer.h b/Source/core/page/PageSerializer.h
index 56bd2da..5913c84 100644
--- a/Source/core/page/PageSerializer.h
+++ b/Source/core/page/PageSerializer.h
@@ -31,7 +31,6 @@
 #ifndef PageSerializer_h
 #define PageSerializer_h
 
-#include "core/platform/SharedBuffer.h"
 #include "weborigin/KURL.h"
 #include "weborigin/KURLHash.h"
 #include "wtf/HashMap.h"
diff --git a/Source/core/page/PerformanceResourceTiming.h b/Source/core/page/PerformanceResourceTiming.h
index 4a7848a..9f05fbe 100644
--- a/Source/core/page/PerformanceResourceTiming.h
+++ b/Source/core/page/PerformanceResourceTiming.h
@@ -33,9 +33,8 @@
 #define PerformanceResourceTiming_h
 
 #include "core/page/PerformanceEntry.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/page/PerformanceTiming.cpp b/Source/core/page/PerformanceTiming.cpp
index 28436a6..81214c3 100644
--- a/Source/core/page/PerformanceTiming.cpp
+++ b/Source/core/page/PerformanceTiming.cpp
@@ -39,7 +39,6 @@
 #include "core/page/Frame.h"
 #include "core/platform/network/ResourceLoadTiming.h"
 #include "core/platform/network/ResourceResponse.h"
-#include <wtf/CurrentTime.h>
 
 namespace WebCore {
 
diff --git a/Source/core/page/PerformanceUserTiming.cpp b/Source/core/page/PerformanceUserTiming.cpp
index 8c2fd46..794eef3 100644
--- a/Source/core/page/PerformanceUserTiming.cpp
+++ b/Source/core/page/PerformanceUserTiming.cpp
@@ -29,8 +29,7 @@
 #include "core/page/Performance.h"
 #include "core/page/PerformanceMark.h"
 #include "core/page/PerformanceMeasure.h"
-#include <wtf/dtoa/utils.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/page/PerformanceUserTiming.h b/Source/core/page/PerformanceUserTiming.h
index 525499e..9caf169 100644
--- a/Source/core/page/PerformanceUserTiming.h
+++ b/Source/core/page/PerformanceUserTiming.h
@@ -27,13 +27,12 @@
 #define PerformanceUserTiming_h
 
 #include "core/dom/ExceptionCode.h"
-#include "core/page/Performance.h"
 #include "core/page/PerformanceTiming.h"
-#include <wtf/HashMap.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/text/StringHash.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/HashMap.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/text/StringHash.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/page/RuntimeCSSEnabled.cpp b/Source/core/page/RuntimeCSSEnabled.cpp
index fe5c52a..5d38e76 100644
--- a/Source/core/page/RuntimeCSSEnabled.cpp
+++ b/Source/core/page/RuntimeCSSEnabled.cpp
@@ -72,12 +72,12 @@
     CSSPropertyID cssGridLayoutProperties[] = {
         CSSPropertyGridAutoColumns,
         CSSPropertyGridAutoRows,
-        CSSPropertyGridColumns,
-        CSSPropertyGridRows,
-        CSSPropertyGridStart,
-        CSSPropertyGridEnd,
-        CSSPropertyGridBefore,
-        CSSPropertyGridAfter,
+        CSSPropertyGridDefinitionColumns,
+        CSSPropertyGridDefinitionRows,
+        CSSPropertyGridColumnStart,
+        CSSPropertyGridColumnEnd,
+        CSSPropertyGridRowStart,
+        CSSPropertyGridRowEnd,
         CSSPropertyGridColumn,
         CSSPropertyGridRow,
         CSSPropertyGridArea,
diff --git a/Source/core/page/RuntimeEnabledFeatures.in b/Source/core/page/RuntimeEnabledFeatures.in
index b378baa..6ebf974 100644
--- a/Source/core/page/RuntimeEnabledFeatures.in
+++ b/Source/core/page/RuntimeEnabledFeatures.in
@@ -1,3 +1,5 @@
+// http://dev.chromium.org/blink/runtime-enabled-features 
+//
 // This list is used to generate RuntimeEnabledFeatures.h/cpp which contains
 // a class that stores static enablers for all experimental features.
 //
@@ -13,6 +15,7 @@
 // condition=ENABLE_NAME is used for wrapping features in compile-time
 // #if ENABLE(FEATURE) guards.  These are deprecated and should all be removed.
 
+AnimatedWebP status=experimental
 ApplicationCache status=stable
 AuthorShadowDOMForAnyElement
 CanvasPath status=test
@@ -46,6 +49,7 @@
 HighResolutionTimeInWorkers status=experimental
 IMEAPI status=test
 IndexedDB status=stable
+InputModeAttribute status=test
 InputTypeColor status=stable
 InputTypeWeek status=stable
 JavaScriptI18NAPI status=stable
@@ -60,6 +64,8 @@
 PagePopup status=stable
 ParseSVGAsHTML
 PeerConnection depends_on=MediaStream, status=stable
+ProgrammaticScrollNotifications status=test
+Promise status=test
 Quota status=stable
 RequestAutocomplete status=test
 ScriptedSpeech status=stable
@@ -68,6 +74,7 @@
 SharedWorker custom
 SpeechInput status=stable
 SpeechSynthesis status=experimental
+Stream status=experimental
 StyleScoped status=experimental
 Touch status=stable
 Vibration status=test
@@ -77,5 +84,4 @@
 WebGLDraftExtensions status=experimental
 WebMIDI status=test
 WebKitMediaSource status=stable
-WebPInAcceptHeader
 WOFF2 status=experimental
diff --git a/Source/core/page/Screen.cpp b/Source/core/page/Screen.cpp
index cac5441..795f2fb 100644
--- a/Source/core/page/Screen.cpp
+++ b/Source/core/page/Screen.cpp
@@ -33,9 +33,7 @@
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/Frame.h"
 #include "core/page/FrameView.h"
-#include "core/page/Settings.h"
 #include "core/platform/PlatformScreen.h"
-#include "core/platform/Widget.h"
 #include "core/platform/graphics/FloatRect.h"
 
 namespace WebCore {
diff --git a/Source/core/page/Settings.cpp b/Source/core/page/Settings.cpp
index dc52fb3..67fa2f6 100644
--- a/Source/core/page/Settings.cpp
+++ b/Source/core/page/Settings.cpp
@@ -28,9 +28,6 @@
 
 #include <limits>
 #include "core/dom/Document.h"
-#include "core/history/BackForwardController.h"
-#include "core/history/HistoryItem.h"
-#include "core/html/HTMLMediaElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/loader/cache/CachedResourceLoader.h"
 #include "core/page/Chrome.h"
@@ -38,9 +35,7 @@
 #include "core/page/FrameTree.h"
 #include "core/page/FrameView.h"
 #include "core/page/Page.h"
-#include "core/platform/network/ResourceHandle.h"
 #include "core/rendering/TextAutosizer.h"
-#include "modules/webdatabase/Database.h"
 
 using namespace std;
 
diff --git a/Source/core/page/Settings.h b/Source/core/page/Settings.h
index a1ab84c..e0fbbef 100644
--- a/Source/core/page/Settings.h
+++ b/Source/core/page/Settings.h
@@ -36,7 +36,6 @@
 #include "wtf/HashMap.h"
 #include "wtf/text/AtomicString.h"
 #include "wtf/text/AtomicStringHash.h"
-#include "wtf/unicode/Unicode.h"
 
 namespace WebCore {
 
@@ -156,6 +155,11 @@
     void setOpenGLMultisamplingEnabled(bool flag);
     bool openGLMultisamplingEnabled();
 
+    // FIXME: This is a temporary flag and should be removed once accelerated
+    // overflow scroll is ready (crbug.com/254111).
+    void setCompositorDrivenAcceleratedScrollingEnabled(bool enabled) { m_compositorDrivenAcceleratedScrollingEnabled = enabled; }
+    bool isCompositorDrivenAcceleratedScrollingEnabled() const { return m_compositorDrivenAcceleratedScrollingEnabled; }
+
 private:
     explicit Settings(Page*);
 
@@ -191,6 +195,10 @@
     bool m_touchEventEmulationEnabled : 1;
     bool m_openGLMultisamplingEnabled : 1;
 
+    // FIXME: This is a temporary flag and should be removed once accelerated
+    // overflow scroll is ready (crbug.com/254111).
+    bool m_compositorDrivenAcceleratedScrollingEnabled : 1;
+
     Timer<Settings> m_setImageLoadingSettingsTimer;
     void imageLoadingSettingsTimerFired(Timer<Settings>*);
 
diff --git a/Source/core/page/Settings.in b/Source/core/page/Settings.in
index 6033967..5533c3c 100644
--- a/Source/core/page/Settings.in
+++ b/Source/core/page/Settings.in
@@ -65,6 +65,7 @@
 acceleratedCompositingForPluginsEnabled initial=true
 acceleratedCompositingForCanvasEnabled initial=true
 acceleratedCompositingForAnimationEnabled initial=true
+acceleratedCompositingForFiltersEnabled initial=false
 acceleratedCompositingForFixedPositionEnabled initial=false
 acceleratedCompositingForOverflowScrollEnabled initial=false
 acceleratedCompositingForTransitionEnabled initial=false
diff --git a/Source/core/page/SpeechInputEvent.h b/Source/core/page/SpeechInputEvent.h
index 7d6bd0c..8166c0c 100644
--- a/Source/core/page/SpeechInputEvent.h
+++ b/Source/core/page/SpeechInputEvent.h
@@ -31,9 +31,7 @@
 #include "core/dom/Event.h"
 #include "core/page/SpeechInputResultList.h"
 
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/Vector.h>
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
diff --git a/Source/core/page/SpeechInputResultList.h b/Source/core/page/SpeechInputResultList.h
index ef4377e..eef6ca3 100644
--- a/Source/core/page/SpeechInputResultList.h
+++ b/Source/core/page/SpeechInputResultList.h
@@ -32,7 +32,6 @@
 #include "core/page/SpeechInputResult.h"
 #include "wtf/PassRefPtr.h"
 #include "wtf/RefCounted.h"
-#include "wtf/Vector.h"
 
 namespace WebCore {
 
diff --git a/Source/core/page/TouchAdjustment.cpp b/Source/core/page/TouchAdjustment.cpp
index 527e6d4..321f1f0 100644
--- a/Source/core/page/TouchAdjustment.cpp
+++ b/Source/core/page/TouchAdjustment.cpp
@@ -156,7 +156,7 @@
     if (textRenderer->frame()->editor()->behavior().shouldSelectOnContextualMenuClick()) {
         // Make subtargets out of every word.
         String textValue = textNode->data();
-        TextBreakIterator* wordIterator = wordBreakIterator(textValue.characters(), textValue.length());
+        TextBreakIterator* wordIterator = wordBreakIterator(textValue.bloatedCharacters(), textValue.length());
         int lastOffset = textBreakFirst(wordIterator);
         if (lastOffset == -1)
             return;
diff --git a/Source/core/page/UseCounter.cpp b/Source/core/page/UseCounter.cpp
index 245e2fc..6001182 100644
--- a/Source/core/page/UseCounter.cpp
+++ b/Source/core/page/UseCounter.cpp
@@ -1,3 +1,4 @@
+
 /*
  * Copyright (C) 2012 Google, Inc. All rights reserved.
  *
@@ -282,24 +283,24 @@
 #if defined(ENABLE_CSS_FILTERS) && ENABLE_CSS_FILTERS
     case CSSPropertyWebkitFilter: return 229;
 #endif
-    case CSSPropertyWebkitAlignContent: return 230;
-    case CSSPropertyWebkitAlignItems: return 231;
-    case CSSPropertyWebkitAlignSelf: return 232;
-    case CSSPropertyWebkitFlex: return 233;
-    case CSSPropertyWebkitFlexBasis: return 234;
-    case CSSPropertyWebkitFlexDirection: return 235;
-    case CSSPropertyWebkitFlexFlow: return 236;
-    case CSSPropertyWebkitFlexGrow: return 237;
-    case CSSPropertyWebkitFlexShrink: return 238;
-    case CSSPropertyWebkitFlexWrap: return 239;
-    case CSSPropertyWebkitJustifyContent: return 240;
+    case CSSPropertyAlignContent: return 230;
+    case CSSPropertyAlignItems: return 231;
+    case CSSPropertyAlignSelf: return 232;
+    case CSSPropertyFlex: return 233;
+    case CSSPropertyFlexBasis: return 234;
+    case CSSPropertyFlexDirection: return 235;
+    case CSSPropertyFlexFlow: return 236;
+    case CSSPropertyFlexGrow: return 237;
+    case CSSPropertyFlexShrink: return 238;
+    case CSSPropertyFlexWrap: return 239;
+    case CSSPropertyJustifyContent: return 240;
     case CSSPropertyWebkitFontSizeDelta: return 241;
-    case CSSPropertyGridColumns: return 242;
-    case CSSPropertyGridRows: return 243;
-    case CSSPropertyGridStart: return 244;
-    case CSSPropertyGridEnd: return 245;
-    case CSSPropertyGridBefore: return 246;
-    case CSSPropertyGridAfter: return 247;
+    case CSSPropertyGridDefinitionColumns: return 242;
+    case CSSPropertyGridDefinitionRows: return 243;
+    case CSSPropertyGridColumnStart: return 244;
+    case CSSPropertyGridColumnEnd: return 245;
+    case CSSPropertyGridRowStart: return 246;
+    case CSSPropertyGridRowEnd: return 247;
     case CSSPropertyGridColumn: return 248;
     case CSSPropertyGridRow: return 249;
     case CSSPropertyGridAutoFlow: return 250;
@@ -355,7 +356,7 @@
     case CSSPropertyWebkitMinLogicalWidth: return 300;
     case CSSPropertyWebkitMinLogicalHeight: return 301;
     // WebkitNbspMode has been deleted, was return 302;
-    case CSSPropertyWebkitOrder: return 303;
+    case CSSPropertyOrder: return 303;
     case CSSPropertyWebkitPaddingAfter: return 304;
     case CSSPropertyWebkitPaddingBefore: return 305;
     case CSSPropertyWebkitPaddingEnd: return 306;
diff --git a/Source/core/page/UseCounter.h b/Source/core/page/UseCounter.h
index 5f814d3..8aa08a7 100644
--- a/Source/core/page/UseCounter.h
+++ b/Source/core/page/UseCounter.h
@@ -142,6 +142,7 @@
         SVGSwitchElement,
         PrefixedDocumentRegister,
         HTMLShadowElementOlderShadowRoot,
+        DocumentAll,
         // Add new features immediately above this line. Don't change assigned numbers of each items.
         NumberOfFeatures, // This enum value must be last.
     };
diff --git a/Source/core/page/Window.idl b/Source/core/page/Window.idl
index 46b983c..d468230 100644
--- a/Source/core/page/Window.idl
+++ b/Source/core/page/Window.idl
@@ -149,12 +149,10 @@
     [EnabledAtRuntime, PerWorldBindings, ActivityLog=GetterForIsolatedWorlds, GetterRaisesException] readonly attribute Storage sessionStorage;
     [EnabledAtRuntime, PerWorldBindings, ActivityLog=GetterForIsolatedWorlds, GetterRaisesException] readonly attribute Storage localStorage;
 
-#if defined(ENABLE_ORIENTATION_EVENTS) && ENABLE_ORIENTATION_EVENTS
     // This is the interface orientation in degrees. Some examples are:
     //  0 is straight up; -90 is when the device is rotated 90 clockwise;
     //  90 is when rotated counter clockwise.
-    readonly attribute long orientation;
-#endif
+    [Conditional=ORIENTATION_EVENTS] readonly attribute long orientation;
 
     [Replaceable] readonly attribute Console console;
 
@@ -163,12 +161,6 @@
 
     [Replaceable] readonly attribute Performance performance;
 
-    // Timers
-    [Custom] long setTimeout(any handler, [Default=Undefined] optional long timeout);
-    void clearTimeout([Default=Undefined] optional long handle);
-    [Custom] long setInterval(any handler, [Default=Undefined] optional long timeout);
-    void clearInterval([Default=Undefined] optional long handle);
-
     [MeasureAs=UnprefixedRequestAnimationFrame] long requestAnimationFrame(RequestAnimationFrameCallback callback);
     void cancelAnimationFrame(long id);
     [MeasureAs=PrefixedRequestAnimationFrame] long webkitRequestAnimationFrame(RequestAnimationFrameCallback callback);
@@ -260,9 +252,7 @@
     attribute EventListener onwebkitanimationstart;
     attribute EventListener onwebkittransitionend;
     attribute EventListener ontransitionend;
-#if defined(ENABLE_ORIENTATION_EVENTS) && ENABLE_ORIENTATION_EVENTS
-    attribute EventListener onorientationchange;
-#endif
+    [Conditional=ORIENTATION_EVENTS] attribute EventListener onorientationchange;
     [EnabledAtRuntime=touch] attribute EventListener ontouchstart;
     [EnabledAtRuntime=touch] attribute EventListener ontouchmove;
     [EnabledAtRuntime=touch] attribute EventListener ontouchend;
@@ -318,3 +308,5 @@
     [Custom, NotEnumerable] getter Window (DOMString name);
 };
 
+Window implements WindowTimers;
+
diff --git a/Source/core/page/WindowFocusAllowedIndicator.h b/Source/core/page/WindowFocusAllowedIndicator.h
index 86598d7..2e0052b 100644
--- a/Source/core/page/WindowFocusAllowedIndicator.h
+++ b/Source/core/page/WindowFocusAllowedIndicator.h
@@ -26,8 +26,7 @@
 #ifndef WindowFocusAllowedIndicator_h
 #define WindowFocusAllowedIndicator_h
 
-#include <wtf/Noncopyable.h>
-#include <wtf/RefPtr.h>
+#include "wtf/Noncopyable.h"
 
 namespace WebCore {
 
diff --git a/Source/core/editing/EditorDeleteAction.h b/Source/core/page/WindowTimers.idl
similarity index 69%
rename from Source/core/editing/EditorDeleteAction.h
rename to Source/core/page/WindowTimers.idl
index 00bf683..97d5d42 100644
--- a/Source/core/editing/EditorDeleteAction.h
+++ b/Source/core/page/WindowTimers.idl
@@ -1,5 +1,7 @@
 /*
- * Copyright (C) 2006 Apple Computer, Inc.  All rights reserved.
+ * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -20,21 +22,15 @@
  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
- 
-#ifndef EditorDeleteAction_h
-#define EditorDeleteAction_h
 
-namespace WebCore {
-
-enum EditorDeleteAction {
-    deleteSelectionAction,
-    deleteKeyAction,
-    forwardDeleteKeyAction
+[
+    NoInterfaceObject
+] interface WindowTimers {
+    [Custom] long setTimeout(any handler, [Default=Undefined] optional long timeout);
+    void clearTimeout([Default=Undefined] optional long handle);
+    [Custom] long setInterval(any handler, [Default=Undefined] optional long timeout);
+    void clearInterval([Default=Undefined] optional long handle);
 };
 
-} // namespace
-
-#endif
-
diff --git a/Source/core/page/WorkerNavigator.h b/Source/core/page/WorkerNavigator.h
index 20d9b8e..2152785 100644
--- a/Source/core/page/WorkerNavigator.h
+++ b/Source/core/page/WorkerNavigator.h
@@ -29,10 +29,9 @@
 #include "bindings/v8/ScriptWrappable.h"
 #include "core/page/NavigatorBase.h"
 #include "core/platform/Supplementable.h"
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/page/animation/AnimationBase.cpp b/Source/core/page/animation/AnimationBase.cpp
index 94c3120..881c4e7 100644
--- a/Source/core/page/animation/AnimationBase.cpp
+++ b/Source/core/page/animation/AnimationBase.cpp
@@ -29,18 +29,11 @@
 #include "config.h"
 #include "core/page/animation/AnimationBase.h"
 
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/dom/Document.h"
-#include "core/dom/EventNames.h"
 #include "core/page/animation/AnimationControllerPrivate.h"
-#include "core/page/animation/CSSPropertyAnimation.h"
 #include "core/page/animation/CompositeAnimation.h"
-#include "core/platform/FloatConversion.h"
 #include "core/platform/animation/AnimationUtilities.h"
 #include "core/platform/animation/TimingFunction.h"
 #include "core/rendering/RenderBox.h"
-#include "core/rendering/style/RenderStyle.h"
-#include "wtf/CurrentTime.h"
 #include <algorithm>
 
 using namespace std;
diff --git a/Source/core/page/animation/AnimationBase.h b/Source/core/page/animation/AnimationBase.h
index 763cee5..e0487e6 100644
--- a/Source/core/page/animation/AnimationBase.h
+++ b/Source/core/page/animation/AnimationBase.h
@@ -32,10 +32,7 @@
 #include "CSSPropertyNames.h"
 #include "core/platform/animation/CSSAnimationData.h"
 #include "core/rendering/style/RenderStyleConstants.h"
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-#include <wtf/RefCounted.h>
-#include <wtf/text/AtomicString.h>
+#include "wtf/RefCounted.h"
 
 namespace WebCore {
 
diff --git a/Source/core/page/animation/AnimationController.cpp b/Source/core/page/animation/AnimationController.cpp
index b41f8b9..a68827b 100644
--- a/Source/core/page/animation/AnimationController.cpp
+++ b/Source/core/page/animation/AnimationController.cpp
@@ -40,8 +40,7 @@
 #include "core/page/animation/CSSPropertyAnimation.h"
 #include "core/page/animation/CompositeAnimation.h"
 #include "core/rendering/RenderView.h"
-#include <wtf/CurrentTime.h>
-#include <wtf/UnusedParam.h>
+#include "wtf/CurrentTime.h"
 
 namespace WebCore {
 
diff --git a/Source/core/page/animation/CSSPropertyAnimation.cpp b/Source/core/page/animation/CSSPropertyAnimation.cpp
index cebadfc..06022ab 100644
--- a/Source/core/page/animation/CSSPropertyAnimation.cpp
+++ b/Source/core/page/animation/CSSPropertyAnimation.cpp
@@ -44,8 +44,7 @@
 #include "core/rendering/style/RenderStyle.h"
 #include "core/rendering/style/StyleCachedImage.h"
 #include "core/rendering/style/StyleGeneratedImage.h"
-#include <wtf/Noncopyable.h>
-#include <wtf/RefCounted.h>
+#include "wtf/Noncopyable.h"
 
 namespace WebCore {
 
@@ -137,10 +136,10 @@
     return ShapeClipPathOperation::create(toShape->blend(fromShape, progress));
 }
 
-static inline PassRefPtr<ExclusionShapeValue> blendFunc(const AnimationBase*, ExclusionShapeValue* from, ExclusionShapeValue* to, double progress)
+static inline PassRefPtr<ShapeValue> blendFunc(const AnimationBase*, ShapeValue* from, ShapeValue* to, double progress)
 {
     // FIXME Bug 102723: Shape-inside should be able to animate a value of 'outside-shape' when shape-outside is set to a BasicShape
-    if (from->type() != ExclusionShapeValue::Shape || to->type() != ExclusionShapeValue::Shape)
+    if (from->type() != ShapeValue::Shape || to->type() != ShapeValue::Shape)
         return to;
 
     const BasicShape* fromShape = from->shape();
@@ -149,7 +148,7 @@
     if (!fromShape->canBlend(toShape))
         return to;
 
-    return ExclusionShapeValue::createShapeValue(toShape->blend(fromShape, progress));
+    return ShapeValue::createShapeValue(toShape->blend(fromShape, progress));
 }
 
 static inline PassRefPtr<FilterOperation> blendFunc(const AnimationBase* anim, FilterOperation* fromOp, FilterOperation* toOp, double progress, bool blendToPassthrough = false)
@@ -397,10 +396,10 @@
     }
 };
 
-class PropertyWrapperExclusionShape : public RefCountedPropertyWrapper<ExclusionShapeValue> {
+class PropertyWrapperShape : public RefCountedPropertyWrapper<ShapeValue> {
 public:
-    PropertyWrapperExclusionShape(CSSPropertyID prop, ExclusionShapeValue* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<ExclusionShapeValue>))
-        : RefCountedPropertyWrapper<ExclusionShapeValue>(prop, getter, setter)
+    PropertyWrapperShape(CSSPropertyID prop, ShapeValue* (RenderStyle::*getter)() const, void (RenderStyle::*setter)(PassRefPtr<ShapeValue>))
+        : RefCountedPropertyWrapper<ShapeValue>(prop, getter, setter)
     {
     }
 };
@@ -911,7 +910,8 @@
 
 class PropertyWrapperFlex : public AnimationPropertyWrapperBase {
 public:
-    PropertyWrapperFlex() : AnimationPropertyWrapperBase(CSSPropertyWebkitFlex)
+    PropertyWrapperFlex()
+        : AnimationPropertyWrapperBase(CSSPropertyFlex)
     {
     }
 
@@ -1133,7 +1133,7 @@
 
     gPropertyWrappers->append(new PropertyWrapperClipPath(CSSPropertyWebkitClipPath, &RenderStyle::clipPath, &RenderStyle::setClipPath));
 
-    gPropertyWrappers->append(new PropertyWrapperExclusionShape(CSSPropertyWebkitShapeInside, &RenderStyle::shapeInside, &RenderStyle::setShapeInside));
+    gPropertyWrappers->append(new PropertyWrapperShape(CSSPropertyWebkitShapeInside, &RenderStyle::shapeInside, &RenderStyle::setShapeInside));
 
     gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyWebkitColumnRuleColor, MaybeInvalidColor, &RenderStyle::columnRuleColor, &RenderStyle::setColumnRuleColor, &RenderStyle::visitedLinkColumnRuleColor, &RenderStyle::setVisitedLinkColumnRuleColor));
     gPropertyWrappers->append(new PropertyWrapperVisitedAffectedColor(CSSPropertyWebkitTextStrokeColor, MaybeInvalidColor, &RenderStyle::textStrokeColor, &RenderStyle::setTextStrokeColor, &RenderStyle::visitedLinkTextStrokeColor, &RenderStyle::setVisitedLinkTextStrokeColor));
diff --git a/Source/core/page/animation/CSSPropertyAnimation.h b/Source/core/page/animation/CSSPropertyAnimation.h
index 29a503d..45709ab 100644
--- a/Source/core/page/animation/CSSPropertyAnimation.h
+++ b/Source/core/page/animation/CSSPropertyAnimation.h
@@ -30,8 +30,6 @@
 #define CSSPropertyAnimation_h
 
 #include "CSSPropertyNames.h"
-#include "core/rendering/style/RenderStyleConstants.h"
-#include <wtf/HashSet.h>
 
 namespace WebCore {
 
diff --git a/Source/core/page/animation/CompositeAnimation.h b/Source/core/page/animation/CompositeAnimation.h
index 6d05bef..2d3d142 100644
--- a/Source/core/page/animation/CompositeAnimation.h
+++ b/Source/core/page/animation/CompositeAnimation.h
@@ -31,9 +31,7 @@
 
 #include "core/page/animation/ImplicitAnimation.h"
 #include "core/page/animation/KeyframeAnimation.h"
-#include <wtf/HashMap.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/text/AtomicString.h>
+#include "wtf/HashMap.h"
 
 namespace WebCore {
 
diff --git a/Source/core/page/animation/ImplicitAnimation.cpp b/Source/core/page/animation/ImplicitAnimation.cpp
index 091f205..8d07fca 100644
--- a/Source/core/page/animation/ImplicitAnimation.cpp
+++ b/Source/core/page/animation/ImplicitAnimation.cpp
@@ -35,7 +35,6 @@
 #include "core/page/animation/ImplicitAnimation.h"
 #include "core/page/animation/KeyframeAnimation.h"
 #include "core/rendering/RenderBoxModelObject.h"
-#include <wtf/UnusedParam.h>
 
 namespace WebCore {
 
diff --git a/Source/core/page/animation/KeyframeAnimation.cpp b/Source/core/page/animation/KeyframeAnimation.cpp
index 4c4e587..220bac1 100644
--- a/Source/core/page/animation/KeyframeAnimation.cpp
+++ b/Source/core/page/animation/KeyframeAnimation.cpp
@@ -37,7 +37,6 @@
 #include "core/page/animation/CompositeAnimation.h"
 #include "core/rendering/RenderBoxModelObject.h"
 #include "core/rendering/style/RenderStyle.h"
-#include <wtf/UnusedParam.h>
 
 using namespace std;
 
diff --git a/Source/core/page/scrolling/ScrollingCoordinator.cpp b/Source/core/page/scrolling/ScrollingCoordinator.cpp
index 9afb665..cd9e31f 100644
--- a/Source/core/page/scrolling/ScrollingCoordinator.cpp
+++ b/Source/core/page/scrolling/ScrollingCoordinator.cpp
@@ -46,7 +46,6 @@
 #include "public/platform/Platform.h"
 #include "public/platform/WebCompositorSupport.h"
 #include "public/platform/WebLayerPositionConstraint.h"
-#include "public/platform/WebScrollbar.h"
 #include "public/platform/WebScrollbarLayer.h"
 #include "public/platform/WebScrollbarThemeGeometry.h"
 #include "public/platform/WebScrollbarThemePainter.h"
diff --git a/Source/core/page/scrolling/ScrollingCoordinator.h b/Source/core/page/scrolling/ScrollingCoordinator.h
index 5ff33d6..925583b 100644
--- a/Source/core/page/scrolling/ScrollingCoordinator.h
+++ b/Source/core/page/scrolling/ScrollingCoordinator.h
@@ -29,7 +29,6 @@
 #include "core/platform/PlatformWheelEvent.h"
 #include "core/platform/ScrollTypes.h"
 #include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/LayoutRect.h"
 #include "core/rendering/RenderObject.h"
 
 namespace WebKit {
diff --git a/Source/core/platform/DateComponents.cpp b/Source/core/platform/DateComponents.cpp
index e04d340..0d7c616 100644
--- a/Source/core/platform/DateComponents.cpp
+++ b/Source/core/platform/DateComponents.cpp
@@ -98,10 +98,10 @@
     return day == Thursday || (day == Wednesday && isLeapYear(m_year)) ? maximumWeekNumber : maximumWeekNumber - 1;
 }
 
-static unsigned countDigits(const UChar* src, unsigned length, unsigned start)
+static unsigned countDigits(const String& src, unsigned start)
 {
     unsigned index = start;
-    for (; index < length; ++index) {
+    for (; index < src.length(); ++index) {
         if (!isASCIIDigit(src[index]))
             break;
     }
@@ -109,19 +109,19 @@
 }
 
 // Very strict integer parser. Do not allow leading or trailing whitespace unlike charactersToIntStrict().
-static bool toInt(const UChar* src, unsigned length, unsigned parseStart, unsigned parseLength, int& out)
+static bool toInt(const String& src, unsigned parseStart, unsigned parseLength, int& out)
 {
-    if (parseStart + parseLength > length || parseLength <= 0)
+    if (parseStart + parseLength > src.length() || parseLength <= 0)
         return false;
     int value = 0;
-    const UChar* current = src + parseStart;
-    const UChar* end = current + parseLength;
+    unsigned current = parseStart;
+    unsigned end = current + parseLength;
 
     // We don't need to handle negative numbers for ISO 8601.
     for (; current < end; ++current) {
-        if (!isASCIIDigit(*current))
+        if (!isASCIIDigit(src[current]))
             return false;
-        int digit = *current - '0';
+        int digit = src[current] - '0';
         if (value > (INT_MAX - digit) / 10) // Check for overflow.
             return false;
         value = value * 10 + digit;
@@ -130,14 +130,14 @@
     return true;
 }
 
-bool DateComponents::parseYear(const UChar* src, unsigned length, unsigned start, unsigned& end)
+bool DateComponents::parseYear(const String& src, unsigned start, unsigned& end)
 {
-    unsigned digitsLength = countDigits(src, length, start);
+    unsigned digitsLength = countDigits(src, start);
     // Needs at least 4 digits according to the standard.
     if (digitsLength < 4)
         return false;
     int year;
-    if (!toInt(src, length, start, digitsLength, year))
+    if (!toInt(src, start, digitsLength, year))
         return false;
     if (year < minimumYear() || year > maximumYear())
         return false;
@@ -285,9 +285,9 @@
 }
 
 // Parses a timezone part, and adjust year, month, monthDay, hour, minute, second, millisecond.
-bool DateComponents::parseTimeZone(const UChar* src, unsigned length, unsigned start, unsigned& end)
+bool DateComponents::parseTimeZone(const String& src, unsigned start, unsigned& end)
 {
-    if (start >= length)
+    if (start >= src.length())
         return false;
     unsigned index = start;
     if (src[index] == 'Z') {
@@ -306,15 +306,15 @@
 
     int hour;
     int minute;
-    if (!toInt(src, length, index, 2, hour) || hour < 0 || hour > 23)
+    if (!toInt(src, index, 2, hour) || hour < 0 || hour > 23)
         return false;
     index += 2;
 
-    if (index >= length || src[index] != ':')
+    if (index >= src.length() || src[index] != ':')
         return false;
     ++index;
 
-    if (!toInt(src, length, index, 2, minute) || minute < 0 || minute > 59)
+    if (!toInt(src, index, 2, minute) || minute < 0 || minute > 59)
         return false;
     index += 2;
 
@@ -330,18 +330,17 @@
     return true;
 }
 
-bool DateComponents::parseMonth(const UChar* src, unsigned length, unsigned start, unsigned& end)
+bool DateComponents::parseMonth(const String& src, unsigned start, unsigned& end)
 {
-    ASSERT(src);
     unsigned index;
-    if (!parseYear(src, length, start, index))
+    if (!parseYear(src, start, index))
         return false;
-    if (index >= length || src[index] != '-')
+    if (index >= src.length() || src[index] != '-')
         return false;
     ++index;
 
     int month;
-    if (!toInt(src, length, index, 2, month) || month < 1 || month > 12)
+    if (!toInt(src, index, 2, month) || month < 1 || month > 12)
         return false;
     --month;
     if (!withinHTMLDateLimits(m_year, month))
@@ -352,21 +351,20 @@
     return true;
 }
 
-bool DateComponents::parseDate(const UChar* src, unsigned length, unsigned start, unsigned& end)
+bool DateComponents::parseDate(const String& src, unsigned start, unsigned& end)
 {
-    ASSERT(src);
     unsigned index;
-    if (!parseMonth(src, length, start, index))
+    if (!parseMonth(src, start, index))
         return false;
     // '-' and 2-digits are needed.
-    if (index + 2 >= length)
+    if (index + 2 >= src.length())
         return false;
     if (src[index] != '-')
         return false;
     ++index;
 
     int day;
-    if (!toInt(src, length, index, 2, day) || day < 1 || day > maxDayOfMonth(m_year, m_month))
+    if (!toInt(src, index, 2, day) || day < 1 || day > maxDayOfMonth(m_year, m_month))
         return false;
     if (!withinHTMLDateLimits(m_year, m_month, day))
         return false;
@@ -376,15 +374,14 @@
     return true;
 }
 
-bool DateComponents::parseWeek(const UChar* src, unsigned length, unsigned start, unsigned& end)
+bool DateComponents::parseWeek(const String& src, unsigned start, unsigned& end)
 {
-    ASSERT(src);
     unsigned index;
-    if (!parseYear(src, length, start, index))
+    if (!parseYear(src, start, index))
         return false;
 
     // 4 characters ('-' 'W' digit digit) are needed.
-    if (index + 3 >= length)
+    if (index + 3 >= src.length())
         return false;
     if (src[index] != '-')
         return false;
@@ -394,7 +391,7 @@
     ++index;
 
     int week;
-    if (!toInt(src, length, index, 2, week) || week < minimumWeekNumber || week > maxWeekNumberInYear())
+    if (!toInt(src, index, 2, week) || week < minimumWeekNumber || week > maxWeekNumberInYear())
         return false;
     if (m_year == maximumYear() && week > maximumWeekInMaximumYear)
         return false;
@@ -404,21 +401,20 @@
     return true;
 }
 
-bool DateComponents::parseTime(const UChar* src, unsigned length, unsigned start, unsigned& end)
+bool DateComponents::parseTime(const String& src, unsigned start, unsigned& end)
 {
-    ASSERT(src);
     int hour;
-    if (!toInt(src, length, start, 2, hour) || hour < 0 || hour > 23)
+    if (!toInt(src, start, 2, hour) || hour < 0 || hour > 23)
         return false;
     unsigned index = start + 2;
-    if (index >= length)
+    if (index >= src.length())
         return false;
     if (src[index] != ':')
         return false;
     ++index;
 
     int minute;
-    if (!toInt(src, length, index, 2, minute) || minute < 0 || minute > 59)
+    if (!toInt(src, index, 2, minute) || minute < 0 || minute > 59)
         return false;
     index += 2;
 
@@ -426,24 +422,25 @@
     int millisecond = 0;
     // Optional second part.
     // Do not return with false because the part is optional.
-    if (index + 2 < length && src[index] == ':') {
-        if (toInt(src, length, index + 1, 2, second) && second >= 0 && second <= 59) {
+    if (index + 2 < src.length() && src[index] == ':') {
+        if (toInt(src, index + 1, 2, second) && second >= 0 && second <= 59) {
             index += 3;
 
             // Optional fractional second part.
-            if (index < length && src[index] == '.') {
-                unsigned digitsLength = countDigits(src, length, index + 1);
+            if (index < src.length() && src[index] == '.') {
+                unsigned digitsLength = countDigits(src, index + 1);
                 if (digitsLength >  0) {
                     ++index;
                     bool ok;
                     if (digitsLength == 1) {
-                        ok = toInt(src, length, index, 1, millisecond);
+                        ok = toInt(src, index, 1, millisecond);
                         millisecond *= 100;
                     } else if (digitsLength == 2) {
-                        ok = toInt(src, length, index, 2, millisecond);
+                        ok = toInt(src, index, 2, millisecond);
                         millisecond *= 10;
-                    } else // digitsLength >= 3
-                        ok = toInt(src, length, index, 3, millisecond);
+                    } else { // digitsLength >= 3
+                        ok = toInt(src, index, 3, millisecond);
+                    }
                     ASSERT_UNUSED(ok, ok);
                     index += digitsLength;
                 }
@@ -459,18 +456,17 @@
     return true;
 }
 
-bool DateComponents::parseDateTimeLocal(const UChar* src, unsigned length, unsigned start, unsigned& end)
+bool DateComponents::parseDateTimeLocal(const String& src, unsigned start, unsigned& end)
 {
-    ASSERT(src);
     unsigned index;
-    if (!parseDate(src, length, start, index))
+    if (!parseDate(src, start, index))
         return false;
-    if (index >= length)
+    if (index >= src.length())
         return false;
     if (src[index] != 'T')
         return false;
     ++index;
-    if (!parseTime(src, length, index, end))
+    if (!parseTime(src, index, end))
         return false;
     if (!withinHTMLDateLimits(m_year, m_month, m_monthDay, m_hour, m_minute, m_second, m_millisecond))
         return false;
@@ -478,20 +474,19 @@
     return true;
 }
 
-bool DateComponents::parseDateTime(const UChar* src, unsigned length, unsigned start, unsigned& end)
+bool DateComponents::parseDateTime(const String& src, unsigned start, unsigned& end)
 {
-    ASSERT(src);
     unsigned index;
-    if (!parseDate(src, length, start, index))
+    if (!parseDate(src, start, index))
         return false;
-    if (index >= length)
+    if (index >= src.length())
         return false;
     if (src[index] != 'T')
         return false;
     ++index;
-    if (!parseTime(src, length, index, index))
+    if (!parseTime(src, index, index))
         return false;
-    if (!parseTimeZone(src, length, index, end))
+    if (!parseTimeZone(src, index, end))
         return false;
     if (!withinHTMLDateLimits(m_year, m_month, m_monthDay, m_hour, m_minute, m_second, m_millisecond))
         return false;
diff --git a/Source/core/platform/DateComponents.h b/Source/core/platform/DateComponents.h
index b7f6950..2a2c5b7 100644
--- a/Source/core/platform/DateComponents.h
+++ b/Source/core/platform/DateComponents.h
@@ -102,17 +102,17 @@
     // failures, and the trailing extra characters don't cause parse failures.
 
     // Sets year and month.
-    bool parseMonth(const UChar* src, unsigned length, unsigned start, unsigned& end);
+    bool parseMonth(const String&, unsigned start, unsigned& end);
     // Sets year, month and monthDay.
-    bool parseDate(const UChar* src, unsigned length, unsigned start, unsigned& end);
+    bool parseDate(const String&, unsigned start, unsigned& end);
     // Sets year and week.
-    bool parseWeek(const UChar* src, unsigned length, unsigned start, unsigned& end);
+    bool parseWeek(const String&, unsigned start, unsigned& end);
     // Sets hour, minute, second and millisecond.
-    bool parseTime(const UChar* src, unsigned length, unsigned start, unsigned& end);
+    bool parseTime(const String&, unsigned start, unsigned& end);
     // Sets year, month, monthDay, hour, minute, second and millisecond.
-    bool parseDateTimeLocal(const UChar* src, unsigned length, unsigned start, unsigned& end);
+    bool parseDateTimeLocal(const String&, unsigned start, unsigned& end);
     // Sets year, month, monthDay, hour, minute, second and millisecond, and adjusts timezone.
-    bool parseDateTime(const UChar* src, unsigned length, unsigned start, unsigned& end);
+    bool parseDateTime(const String&, unsigned start, unsigned& end);
 
     // The following setMillisecondsSinceEpochFor*() functions take
     // the number of milliseconds since 1970-01-01 00:00:00.000 UTC as
@@ -172,10 +172,10 @@
     // Returns the maximum week number in this DateComponents's year.
     // The result is either of 52 and 53.
     int maxWeekNumberInYear() const;
-    bool parseYear(const UChar* src, unsigned length, unsigned start, unsigned& end);
+    bool parseYear(const String&, unsigned start, unsigned& end);
     bool addDay(int);
     bool addMinute(int);
-    bool parseTimeZone(const UChar* src, unsigned length, unsigned start, unsigned& end);
+    bool parseTimeZone(const String&, unsigned start, unsigned& end);
     // Helper for millisecondsSinceEpoch().
     double millisecondsSinceEpochForTime() const;
     // Helpers for setMillisecondsSinceEpochFor*().
diff --git a/Source/core/platform/DragImage.cpp b/Source/core/platform/DragImage.cpp
index 4d34435..4beef95 100644
--- a/Source/core/platform/DragImage.cpp
+++ b/Source/core/platform/DragImage.cpp
@@ -26,18 +26,35 @@
 #include "config.h"
 #include "core/platform/DragImage.h"
 
+#include "core/platform/graphics/BitmapImage.h"
+#include "core/platform/graphics/Color.h"
+#include "core/platform/graphics/FloatPoint.h"
+#include "core/platform/graphics/FloatRect.h"
 #include "core/platform/graphics/Font.h"
 #include "core/platform/graphics/FontCache.h"
 #include "core/platform/graphics/FontDescription.h"
-#include "core/platform/graphics/FontSelector.h"
+#include "core/platform/graphics/FontMetrics.h"
 #include "core/platform/graphics/GraphicsContext.h"
+#include "core/platform/graphics/Image.h"
 #include "core/platform/graphics/ImageBuffer.h"
+#include "core/platform/graphics/IntPoint.h"
+#include "core/platform/graphics/IntSize.h"
 #include "core/platform/graphics/StringTruncator.h"
 #include "core/platform/graphics/TextRun.h"
+#include "core/platform/graphics/skia/NativeImageSkia.h"
+#include "core/platform/graphics/transforms/AffineTransform.h"
+#include "skia/ext/image_operations.h"
+#include "third_party/skia/include/core/SkCanvas.h"
+#include "third_party/skia/include/core/SkMatrix.h"
 #include "weborigin/KURL.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/text/WTFString.h"
+
+#include <algorithm>
 
 namespace WebCore {
-    
+
 const float kDragLabelBorderX = 4;
 // Keep border_y in synch with DragController::LinkDragBorderInset.
 const float kDragLabelBorderY = 2;
@@ -51,11 +68,52 @@
 const float kDragLinkLabelFontSize = 11;
 const float kDragLinkUrlFontSize = 10;
 
+PassOwnPtr<DragImage> DragImage::create(Image* image, RespectImageOrientationEnum shouldRespectImageOrientation)
+{
+    if (!image)
+        return nullptr;
+
+    RefPtr<NativeImageSkia> bitmap = image->nativeImageForCurrentFrame();
+    if (!bitmap)
+        return nullptr;
+
+    if (image->isBitmapImage()) {
+        ImageOrientation orientation = DefaultImageOrientation;
+        BitmapImage* bitmapImage = static_cast<BitmapImage*>(image);
+        IntSize sizeRespectingOrientation = bitmapImage->sizeRespectingOrientation();
+
+        if (shouldRespectImageOrientation == RespectImageOrientation)
+            orientation = bitmapImage->currentFrameOrientation();
+
+        if (orientation != DefaultImageOrientation) {
+            FloatRect destRect(FloatPoint(), sizeRespectingOrientation);
+            if (orientation.usesWidthAsHeight())
+                destRect = destRect.transposedRect();
+
+            SkBitmap skBitmap;
+            skBitmap.setConfig(
+                SkBitmap::kARGB_8888_Config, sizeRespectingOrientation.width(), sizeRespectingOrientation.height());
+            if (!skBitmap.allocPixels())
+                return nullptr;
+
+            SkCanvas canvas(skBitmap);
+            canvas.concat(orientation.transformFromDefault(sizeRespectingOrientation));
+            canvas.drawBitmapRect(bitmap->bitmap(), 0, destRect);
+
+            return adoptPtr(new DragImage(skBitmap, bitmap->resolutionScale()));
+        }
+    }
+
+    SkBitmap skBitmap;
+    if (!bitmap->bitmap().copyTo(&skBitmap, SkBitmap::kARGB_8888_Config))
+        return nullptr;
+    return adoptPtr(new DragImage(skBitmap, bitmap->resolutionScale()));
+}
+
 static Font deriveDragLabelFont(int size, FontWeight fontWeight, const FontDescription& systemFont)
 {
     FontDescription description = systemFont;
     description.setWeight(fontWeight);
-
     description.setSpecifiedSize(size);
     description.setComputedSize(size);
     Font result(description, 0, 0);
@@ -63,46 +121,7 @@
     return result;
 }
 
-DragImageRef fitDragImageToMaxSize(DragImageRef image, const IntSize& srcSize, const IntSize& size)
-{
-    float heightResizeRatio = 0.0f;
-    float widthResizeRatio = 0.0f;
-    float resizeRatio = -1.0f;
-    IntSize originalSize = dragImageSize(image);
-    
-    if (srcSize.width() > size.width()) {
-        widthResizeRatio = size.width() / (float)srcSize.width();
-        resizeRatio = widthResizeRatio;
-    }
-    
-    if (srcSize.height() > size.height()) {
-        heightResizeRatio = size.height() / (float)srcSize.height();
-        if ((resizeRatio < 0.0f) || (resizeRatio > heightResizeRatio))
-            resizeRatio = heightResizeRatio;
-    }
-    
-    if (srcSize == originalSize)
-        return resizeRatio > 0.0f ? scaleDragImage(image, FloatSize(resizeRatio, resizeRatio)) : image;
-    
-    // The image was scaled in the webpage so at minimum we must account for that scaling
-    float scalex = srcSize.width() / (float)originalSize.width();
-    float scaley = srcSize.height() / (float)originalSize.height();
-    if (resizeRatio > 0.0f) {
-        scalex *= resizeRatio;
-        scaley *= resizeRatio;
-    }
-    
-    return scaleDragImage(image, FloatSize(scalex, scaley));
-}
-    
-DragImageRef createDragImageForSelection(DragImageRef image, float dragImageAlpha)
-{
-    if (image)
-        image = dissolveDragImageToFraction(image, dragImageAlpha);
-    return image;
-}
-
-DragImageRef createDragImageForLink(const KURL& url, const String& inLabel, const FontDescription& systemFont, float deviceScaleFactor)
+PassOwnPtr<DragImage> DragImage::create(const KURL& url, const String& inLabel, const FontDescription& systemFont, float deviceScaleFactor)
 {
     const Font labelFont = deriveDragLabelFont(kDragLinkLabelFontSize, FontWeightBold, systemFont);
     const Font urlFont = deriveDragLabelFont(kDragLinkUrlFontSize, FontWeightNormal, systemFont);
@@ -149,7 +168,7 @@
     scaledImageSize.scale(deviceScaleFactor);
     OwnPtr<ImageBuffer> buffer(ImageBuffer::create(scaledImageSize, deviceScaleFactor));
     if (!buffer)
-        return 0;
+        return nullptr;
 
     const float DragLabelRadius = 5;
     const IntSize radii(DragLabelRadius, DragLabelRadius);
@@ -174,8 +193,77 @@
     buffer->context()->drawText(urlFont, TextRunPaintInfo(textRun), textPos);
 
     RefPtr<Image> image = buffer->copyImage();
-    return createDragImageFromImage(image.get());
+    return DragImage::create(image.get());
+}
+
+DragImage::DragImage(const SkBitmap& bitmap, float resolutionScale)
+    : m_bitmap(bitmap)
+    , m_resolutionScale(resolutionScale)
+{
+}
+
+DragImage::~DragImage()
+{
+}
+
+void DragImage::fitToMaxSize(const IntSize& srcSize, const IntSize& maxSize)
+{
+    float heightResizeRatio = 0.0f;
+    float widthResizeRatio = 0.0f;
+    float resizeRatio = -1.0f;
+    IntSize originalSize = size();
+
+    if (srcSize.width() > maxSize.width()) {
+        widthResizeRatio = maxSize.width() / static_cast<float>(srcSize.width());
+        resizeRatio = widthResizeRatio;
+    }
+
+    if (srcSize.height() > maxSize.height()) {
+        heightResizeRatio = maxSize.height() / static_cast<float>(srcSize.height());
+        if ((resizeRatio < 0.0f) || (resizeRatio > heightResizeRatio))
+            resizeRatio = heightResizeRatio;
+    }
+
+    if (srcSize == originalSize) {
+        if (resizeRatio > 0.0f)
+            scale(resizeRatio, resizeRatio);
+        return;
+    }
+
+    // The image was scaled in the webpage so at minimum we must account for that scaling
+    float scaleX = srcSize.width() / static_cast<float>(originalSize.width());
+    float scaleY = srcSize.height() / static_cast<float>(originalSize.height());
+    if (resizeRatio > 0.0f) {
+        scaleX *= resizeRatio;
+        scaleY *= resizeRatio;
+    }
+
+    scale(scaleX, scaleY);
+}
+
+void DragImage::scale(float scaleX, float scaleY)
+{
+    int imageWidth = scaleX * m_bitmap.width();
+    int imageHeight = scaleY * m_bitmap.height();
+    m_bitmap = skia::ImageOperations::Resize(
+        m_bitmap, skia::ImageOperations::RESIZE_LANCZOS3, imageWidth, imageHeight);
+}
+
+void DragImage::dissolveToFraction(float fraction)
+{
+    m_bitmap.setIsOpaque(false);
+    SkAutoLockPixels lock(m_bitmap);
+
+    for (int row = 0; row < m_bitmap.height(); ++row) {
+        for (int column = 0; column < m_bitmap.width(); ++column) {
+            uint32_t* pixel = m_bitmap.getAddr32(column, row);
+            *pixel = SkPreMultiplyARGB(
+                SkColorGetA(*pixel) * fraction,
+                SkColorGetR(*pixel),
+                SkColorGetG(*pixel),
+                SkColorGetB(*pixel));
+        }
+    }
 }
 
 } // namespace WebCore
-
diff --git a/Source/core/platform/DragImage.h b/Source/core/platform/DragImage.h
index 91586cb..129383d 100644
--- a/Source/core/platform/DragImage.h
+++ b/Source/core/platform/DragImage.h
@@ -20,42 +20,44 @@
  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
 #ifndef DragImage_h
 #define DragImage_h
 
-#include "core/platform/chromium/DragImageRef.h"
-#include "core/platform/graphics/FloatSize.h"
-#include "core/platform/graphics/FontRenderingMode.h"
 #include "core/platform/graphics/ImageOrientation.h"
 #include "core/platform/graphics/IntSize.h"
-#include <wtf/Forward.h>
+#include "third_party/skia/include/core/SkBitmap.h"
+#include "wtf/Forward.h"
 
 namespace WebCore {
-    
-    class CachedImage;
-    class FontDescription;
-    class Frame;
-    class Image;
-    class KURL;
-    class Range;
 
-    IntSize dragImageSize(DragImageRef);
-    
-    //These functions should be memory neutral, eg. if they return a newly allocated image, 
-    //they should release the input image.  As a corollary these methods don't guarantee
-    //the input image ref will still be valid after they have been called
-    DragImageRef fitDragImageToMaxSize(DragImageRef image, const IntSize& srcSize, const IntSize& size);
-    DragImageRef scaleDragImage(DragImageRef, FloatSize scale);
-    DragImageRef dissolveDragImageToFraction(DragImageRef image, float delta);
-    
-    DragImageRef createDragImageFromImage(Image*, RespectImageOrientationEnum = DoNotRespectImageOrientation);
-    DragImageRef createDragImageForSelection(DragImageRef, float dragImageAlpha);
-    DragImageRef createDragImageIconForCachedImage(CachedImage*);
-    DragImageRef createDragImageForLink(const KURL&, const String& label, const FontDescription&, float deviceScaleFactor);
-    void deleteDragImage(DragImageRef);
+class FontDescription;
+class Image;
+class KURL;
+
+class DragImage {
+public:
+    static PassOwnPtr<DragImage> create(Image*, RespectImageOrientationEnum = DoNotRespectImageOrientation);
+    static PassOwnPtr<DragImage> create(const KURL&, const String& label, const FontDescription& systemFont, float deviceScaleFactor);
+    ~DragImage();
+
+    const SkBitmap& bitmap() { return m_bitmap; }
+    float resolutionScale() const { return m_resolutionScale; }
+    IntSize size() const { return IntSize(m_bitmap.width(), m_bitmap.height()); }
+
+    void fitToMaxSize(const IntSize& srcSize, const IntSize& maxSize);
+    void scale(float scaleX, float scaleY);
+    void dissolveToFraction(float fraction);
+
+private:
+    DragImage(const SkBitmap&, float resolutionScale);
+
+    SkBitmap m_bitmap;
+    float m_resolutionScale;
+};
+
 }
 
-#endif //!DragImage_h
+#endif // DragImage_h
diff --git a/Source/core/platform/EventTracer.cpp b/Source/core/platform/EventTracer.cpp
index 6fa0ab9..f9be0da 100644
--- a/Source/core/platform/EventTracer.cpp
+++ b/Source/core/platform/EventTracer.cpp
@@ -32,18 +32,29 @@
 #include "core/platform/EventTracer.h"
 
 #include "public/platform/Platform.h"
+#include <stdio.h>
 
 namespace WebCore {
 
-TraceEventAPIAtomicWord* traceSamplingState0;
-TraceEventAPIAtomicWord* traceSamplingState1;
-TraceEventAPIAtomicWord* traceSamplingState2;
+// The dummy variable is needed to avoid a crash when someone updates the state variables
+// before EventTracer::initialize() is called.
+long dummyTraceSamplingState = 0;
+long* traceSamplingState0 = &dummyTraceSamplingState;
+long* traceSamplingState1 = &dummyTraceSamplingState;
+long* traceSamplingState2 = &dummyTraceSamplingState;
 
 void EventTracer::initialize()
 {
     traceSamplingState0 = WebKit::Platform::current()->getTraceSamplingState(0);
+    // FIXME: traceSamplingState0 can be 0 in split-dll build. http://crbug.com/237249
+    if (!traceSamplingState0)
+        traceSamplingState0 = &dummyTraceSamplingState;
     traceSamplingState1 = WebKit::Platform::current()->getTraceSamplingState(1);
+    if (!traceSamplingState1)
+        traceSamplingState1 = &dummyTraceSamplingState;
     traceSamplingState2 = WebKit::Platform::current()->getTraceSamplingState(2);
+    if (!traceSamplingState2)
+        traceSamplingState2 = &dummyTraceSamplingState;
 }
 
 const unsigned char* EventTracer::getTraceCategoryEnabledFlag(const char* categoryName)
diff --git a/Source/core/platform/EventTracer.h b/Source/core/platform/EventTracer.h
index 836e2e9..73df310 100644
--- a/Source/core/platform/EventTracer.h
+++ b/Source/core/platform/EventTracer.h
@@ -33,11 +33,10 @@
 
 namespace WebCore {
 
-typedef long int TraceEventAPIAtomicWord;
-
-extern TraceEventAPIAtomicWord* traceSamplingState0;
-extern TraceEventAPIAtomicWord* traceSamplingState1;
-extern TraceEventAPIAtomicWord* traceSamplingState2;
+// FIXME: Make these global variables thread-safe. Make a value update atomic.
+extern long* traceSamplingState0;
+extern long* traceSamplingState1;
+extern long* traceSamplingState2;
 
 class EventTracer {
 public:
diff --git a/Source/core/platform/JSONValues.cpp b/Source/core/platform/JSONValues.cpp
new file mode 100644
index 0000000..667bedd
--- /dev/null
+++ b/Source/core/platform/JSONValues.cpp
@@ -0,0 +1,386 @@
+/*
+ * Copyright (C) 2010 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/platform/JSONValues.h"
+
+#include "wtf/DecimalNumber.h"
+#include "wtf/dtoa.h"
+#include "wtf/text/StringBuilder.h"
+
+namespace WebCore {
+
+namespace {
+
+const char* const nullString = "null";
+const char* const trueString = "true";
+const char* const falseString = "false";
+
+inline bool escapeChar(UChar c, StringBuilder* dst)
+{
+    switch (c) {
+    case '\b': dst->append("\\b", 2); break;
+    case '\f': dst->append("\\f", 2); break;
+    case '\n': dst->append("\\n", 2); break;
+    case '\r': dst->append("\\r", 2); break;
+    case '\t': dst->append("\\t", 2); break;
+    case '\\': dst->append("\\\\", 2); break;
+    case '"': dst->append("\\\"", 2); break;
+    default:
+        return false;
+    }
+    return true;
+}
+
+inline void doubleQuoteString(const String& str, StringBuilder* dst)
+{
+    dst->append('"');
+    for (unsigned i = 0; i < str.length(); ++i) {
+        UChar c = str[i];
+        if (!escapeChar(c, dst)) {
+            if (c < 32 || c > 126 || c == '<' || c == '>') {
+                // 1. Escaping <, > to prevent script execution.
+                // 2. Technically, we could also pass through c > 126 as UTF8, but this
+                //    is also optional. It would also be a pain to implement here.
+                unsigned symbol = static_cast<unsigned>(c);
+                String symbolCode = String::format("\\u%04X", symbol);
+                dst->append(symbolCode);
+            } else {
+                dst->append(c);
+            }
+        }
+    }
+    dst->append('"');
+}
+
+} // anonymous namespace
+
+bool JSONValue::asBoolean(bool*) const
+{
+    return false;
+}
+
+bool JSONValue::asNumber(double*) const
+{
+    return false;
+}
+
+bool JSONValue::asNumber(long*) const
+{
+    return false;
+}
+
+bool JSONValue::asNumber(int*) const
+{
+    return false;
+}
+
+bool JSONValue::asNumber(unsigned long*) const
+{
+    return false;
+}
+
+bool JSONValue::asNumber(unsigned*) const
+{
+    return false;
+}
+
+bool JSONValue::asString(String*) const
+{
+    return false;
+}
+
+bool JSONValue::asValue(RefPtr<JSONValue>* output)
+{
+    *output = this;
+    return true;
+}
+
+bool JSONValue::asObject(RefPtr<JSONObject>*)
+{
+    return false;
+}
+
+bool JSONValue::asArray(RefPtr<JSONArray>*)
+{
+    return false;
+}
+
+PassRefPtr<JSONObject> JSONValue::asObject()
+{
+    return 0;
+}
+
+PassRefPtr<JSONArray> JSONValue::asArray()
+{
+    return 0;
+}
+
+String JSONValue::toJSONString() const
+{
+    StringBuilder result;
+    result.reserveCapacity(512);
+    writeJSON(&result);
+    return result.toString();
+}
+
+void JSONValue::writeJSON(StringBuilder* output) const
+{
+    ASSERT(m_type == TypeNull);
+    output->append(nullString, 4);
+}
+
+bool JSONBasicValue::asBoolean(bool* output) const
+{
+    if (type() != TypeBoolean)
+        return false;
+    *output = m_boolValue;
+    return true;
+}
+
+bool JSONBasicValue::asNumber(double* output) const
+{
+    if (type() != TypeNumber)
+        return false;
+    *output = m_doubleValue;
+    return true;
+}
+
+bool JSONBasicValue::asNumber(long* output) const
+{
+    if (type() != TypeNumber)
+        return false;
+    *output = static_cast<long>(m_doubleValue);
+    return true;
+}
+
+bool JSONBasicValue::asNumber(int* output) const
+{
+    if (type() != TypeNumber)
+        return false;
+    *output = static_cast<int>(m_doubleValue);
+    return true;
+}
+
+bool JSONBasicValue::asNumber(unsigned long* output) const
+{
+    if (type() != TypeNumber)
+        return false;
+    *output = static_cast<unsigned long>(m_doubleValue);
+    return true;
+}
+
+bool JSONBasicValue::asNumber(unsigned* output) const
+{
+    if (type() != TypeNumber)
+        return false;
+    *output = static_cast<unsigned>(m_doubleValue);
+    return true;
+}
+
+void JSONBasicValue::writeJSON(StringBuilder* output) const
+{
+    ASSERT(type() == TypeBoolean || type() == TypeNumber);
+    if (type() == TypeBoolean) {
+        if (m_boolValue)
+            output->append(trueString, 4);
+        else
+            output->append(falseString, 5);
+    } else if (type() == TypeNumber) {
+        NumberToLStringBuffer buffer;
+        if (!std::isfinite(m_doubleValue)) {
+            output->append(nullString, 4);
+            return;
+        }
+        DecimalNumber decimal = m_doubleValue;
+        unsigned length = 0;
+        if (decimal.bufferLengthForStringDecimal() > WTF::NumberToStringBufferLength) {
+            // Not enough room for decimal. Use exponential format.
+            if (decimal.bufferLengthForStringExponential() > WTF::NumberToStringBufferLength) {
+                // Fallback for an abnormal case if it's too little even for exponential.
+                output->append("NaN", 3);
+                return;
+            }
+            length = decimal.toStringExponential(buffer, WTF::NumberToStringBufferLength);
+        } else {
+            length = decimal.toStringDecimal(buffer, WTF::NumberToStringBufferLength);
+        }
+        output->append(buffer, length);
+    }
+}
+
+bool JSONString::asString(String* output) const
+{
+    *output = m_stringValue;
+    return true;
+}
+
+void JSONString::writeJSON(StringBuilder* output) const
+{
+    ASSERT(type() == TypeString);
+    doubleQuoteString(m_stringValue, output);
+}
+
+JSONObjectBase::~JSONObjectBase()
+{
+}
+
+bool JSONObjectBase::asObject(RefPtr<JSONObject>* output)
+{
+    COMPILE_ASSERT(sizeof(JSONObject) == sizeof(JSONObjectBase), cannot_cast);
+    *output = static_cast<JSONObject*>(this);
+    return true;
+}
+
+PassRefPtr<JSONObject> JSONObjectBase::asObject()
+{
+    return openAccessors();
+}
+
+JSONObject* JSONObjectBase::openAccessors()
+{
+    COMPILE_ASSERT(sizeof(JSONObject) == sizeof(JSONObjectBase), cannot_cast);
+    return static_cast<JSONObject*>(this);
+}
+
+bool JSONObjectBase::getBoolean(const String& name, bool* output) const
+{
+    RefPtr<JSONValue> value = get(name);
+    if (!value)
+        return false;
+    return value->asBoolean(output);
+}
+
+bool JSONObjectBase::getString(const String& name, String* output) const
+{
+    RefPtr<JSONValue> value = get(name);
+    if (!value)
+        return false;
+    return value->asString(output);
+}
+
+PassRefPtr<JSONObject> JSONObjectBase::getObject(const String& name) const
+{
+    RefPtr<JSONValue> value = get(name);
+    if (!value)
+        return 0;
+    return value->asObject();
+}
+
+PassRefPtr<JSONArray> JSONObjectBase::getArray(const String& name) const
+{
+    RefPtr<JSONValue> value = get(name);
+    if (!value)
+        return 0;
+    return value->asArray();
+}
+
+PassRefPtr<JSONValue> JSONObjectBase::get(const String& name) const
+{
+    Dictionary::const_iterator it = m_data.find(name);
+    if (it == m_data.end())
+        return 0;
+    return it->value;
+}
+
+void JSONObjectBase::remove(const String& name)
+{
+    m_data.remove(name);
+    for (size_t i = 0; i < m_order.size(); ++i) {
+        if (m_order[i] == name) {
+            m_order.remove(i);
+            break;
+        }
+    }
+}
+
+void JSONObjectBase::writeJSON(StringBuilder* output) const
+{
+    output->append('{');
+    for (size_t i = 0; i < m_order.size(); ++i) {
+        Dictionary::const_iterator it = m_data.find(m_order[i]);
+        ASSERT(it != m_data.end());
+        if (i)
+            output->append(',');
+        doubleQuoteString(it->key, output);
+        output->append(':');
+        it->value->writeJSON(output);
+    }
+    output->append('}');
+}
+
+JSONObjectBase::JSONObjectBase()
+    : JSONValue(TypeObject)
+    , m_data()
+    , m_order()
+{
+}
+
+JSONArrayBase::~JSONArrayBase()
+{
+}
+
+bool JSONArrayBase::asArray(RefPtr<JSONArray>* output)
+{
+    COMPILE_ASSERT(sizeof(JSONArrayBase) == sizeof(JSONArray), cannot_cast);
+    *output = static_cast<JSONArray*>(this);
+    return true;
+}
+
+PassRefPtr<JSONArray> JSONArrayBase::asArray()
+{
+    COMPILE_ASSERT(sizeof(JSONArrayBase) == sizeof(JSONArray), cannot_cast);
+    return static_cast<JSONArray*>(this);
+}
+
+void JSONArrayBase::writeJSON(StringBuilder* output) const
+{
+    output->append('[');
+    for (Vector<RefPtr<JSONValue> >::const_iterator it = m_data.begin(); it != m_data.end(); ++it) {
+        if (it != m_data.begin())
+            output->append(',');
+        (*it)->writeJSON(output);
+    }
+    output->append(']');
+}
+
+JSONArrayBase::JSONArrayBase()
+    : JSONValue(TypeArray)
+    , m_data()
+{
+}
+
+PassRefPtr<JSONValue> JSONArrayBase::get(size_t index)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(index < m_data.size());
+    return m_data[index];
+}
+
+} // namespace WebCore
diff --git a/Source/core/platform/JSONValues.h b/Source/core/platform/JSONValues.h
new file mode 100644
index 0000000..f1f3bf7
--- /dev/null
+++ b/Source/core/platform/JSONValues.h
@@ -0,0 +1,393 @@
+/*
+ * Copyright (C) 2009 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef JSONValues_h
+#define JSONValues_h
+
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/RefCounted.h"
+#include "wtf/Vector.h"
+#include "wtf/text/StringHash.h"
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class JSONArray;
+class JSONObject;
+
+class JSONValue : public RefCounted<JSONValue> {
+public:
+    static const int maxDepth = 1000;
+
+    JSONValue() : m_type(TypeNull) { }
+    virtual ~JSONValue() { }
+
+    static PassRefPtr<JSONValue> null()
+    {
+        return adoptRef(new JSONValue());
+    }
+
+    typedef enum {
+        TypeNull = 0,
+        TypeBoolean,
+        TypeNumber,
+        TypeString,
+        TypeObject,
+        TypeArray
+    } Type;
+
+    Type type() const { return m_type; }
+
+    bool isNull() const { return m_type == TypeNull; }
+
+    virtual bool asBoolean(bool* output) const;
+    virtual bool asNumber(double* output) const;
+    virtual bool asNumber(long* output) const;
+    virtual bool asNumber(int* output) const;
+    virtual bool asNumber(unsigned long* output) const;
+    virtual bool asNumber(unsigned* output) const;
+    virtual bool asString(String* output) const;
+    virtual bool asValue(RefPtr<JSONValue>* output);
+    virtual bool asObject(RefPtr<JSONObject>* output);
+    virtual bool asArray(RefPtr<JSONArray>* output);
+    virtual PassRefPtr<JSONObject> asObject();
+    virtual PassRefPtr<JSONArray> asArray();
+
+    String toJSONString() const;
+    virtual void writeJSON(StringBuilder* output) const;
+
+protected:
+    explicit JSONValue(Type type) : m_type(type) { }
+
+private:
+    Type m_type;
+};
+
+class JSONBasicValue : public JSONValue {
+public:
+
+    static PassRefPtr<JSONBasicValue> create(bool value)
+    {
+        return adoptRef(new JSONBasicValue(value));
+    }
+
+    static PassRefPtr<JSONBasicValue> create(int value)
+    {
+        return adoptRef(new JSONBasicValue(value));
+    }
+
+    static PassRefPtr<JSONBasicValue> create(double value)
+    {
+        return adoptRef(new JSONBasicValue(value));
+    }
+
+    virtual bool asBoolean(bool* output) const;
+    virtual bool asNumber(double* output) const;
+    virtual bool asNumber(long* output) const;
+    virtual bool asNumber(int* output) const;
+    virtual bool asNumber(unsigned long* output) const;
+    virtual bool asNumber(unsigned* output) const;
+
+    virtual void writeJSON(StringBuilder* output) const;
+
+private:
+    explicit JSONBasicValue(bool value) : JSONValue(TypeBoolean), m_boolValue(value) { }
+    explicit JSONBasicValue(int value) : JSONValue(TypeNumber), m_doubleValue((double)value) { }
+    explicit JSONBasicValue(double value) : JSONValue(TypeNumber), m_doubleValue(value) { }
+
+    union {
+        bool m_boolValue;
+        double m_doubleValue;
+    };
+};
+
+class JSONString : public JSONValue {
+public:
+    static PassRefPtr<JSONString> create(const String& value)
+    {
+        return adoptRef(new JSONString(value));
+    }
+
+    static PassRefPtr<JSONString> create(const char* value)
+    {
+        return adoptRef(new JSONString(value));
+    }
+
+    virtual bool asString(String* output) const;
+
+    virtual void writeJSON(StringBuilder* output) const;
+
+private:
+    explicit JSONString(const String& value) : JSONValue(TypeString), m_stringValue(value) { }
+    explicit JSONString(const char* value) : JSONValue(TypeString), m_stringValue(value) { }
+
+    String m_stringValue;
+};
+
+class JSONObjectBase : public JSONValue {
+private:
+    typedef HashMap<String, RefPtr<JSONValue> > Dictionary;
+
+public:
+    typedef Dictionary::iterator iterator;
+    typedef Dictionary::const_iterator const_iterator;
+
+    virtual PassRefPtr<JSONObject> asObject();
+    JSONObject* openAccessors();
+
+protected:
+    ~JSONObjectBase();
+
+    virtual bool asObject(RefPtr<JSONObject>* output);
+
+    void setBoolean(const String& name, bool);
+    void setNumber(const String& name, double);
+    void setString(const String& name, const String&);
+    void setValue(const String& name, PassRefPtr<JSONValue>);
+    void setObject(const String& name, PassRefPtr<JSONObject>);
+    void setArray(const String& name, PassRefPtr<JSONArray>);
+
+    iterator find(const String& name);
+    const_iterator find(const String& name) const;
+    bool getBoolean(const String& name, bool* output) const;
+    template<class T> bool getNumber(const String& name, T* output) const
+    {
+        RefPtr<JSONValue> value = get(name);
+        if (!value)
+            return false;
+        return value->asNumber(output);
+    }
+    bool getString(const String& name, String* output) const;
+    PassRefPtr<JSONObject> getObject(const String& name) const;
+    PassRefPtr<JSONArray> getArray(const String& name) const;
+    PassRefPtr<JSONValue> get(const String& name) const;
+
+    void remove(const String& name);
+
+    virtual void writeJSON(StringBuilder* output) const;
+
+    iterator begin() { return m_data.begin(); }
+    iterator end() { return m_data.end(); }
+    const_iterator begin() const { return m_data.begin(); }
+    const_iterator end() const { return m_data.end(); }
+
+    int size() const { return m_data.size(); }
+
+protected:
+    JSONObjectBase();
+
+private:
+    Dictionary m_data;
+    Vector<String> m_order;
+};
+
+class JSONObject : public JSONObjectBase {
+public:
+    static PassRefPtr<JSONObject> create()
+    {
+        return adoptRef(new JSONObject());
+    }
+
+    using JSONObjectBase::asObject;
+
+    using JSONObjectBase::setBoolean;
+    using JSONObjectBase::setNumber;
+    using JSONObjectBase::setString;
+    using JSONObjectBase::setValue;
+    using JSONObjectBase::setObject;
+    using JSONObjectBase::setArray;
+
+    using JSONObjectBase::find;
+    using JSONObjectBase::getBoolean;
+    using JSONObjectBase::getNumber;
+    using JSONObjectBase::getString;
+    using JSONObjectBase::getObject;
+    using JSONObjectBase::getArray;
+    using JSONObjectBase::get;
+
+    using JSONObjectBase::remove;
+
+    using JSONObjectBase::begin;
+    using JSONObjectBase::end;
+
+    using JSONObjectBase::size;
+};
+
+
+class JSONArrayBase : public JSONValue {
+public:
+    typedef Vector<RefPtr<JSONValue> >::iterator iterator;
+    typedef Vector<RefPtr<JSONValue> >::const_iterator const_iterator;
+
+    virtual PassRefPtr<JSONArray> asArray();
+
+    unsigned length() const { return m_data.size(); }
+
+protected:
+    ~JSONArrayBase();
+
+    virtual bool asArray(RefPtr<JSONArray>* output);
+
+    void pushBoolean(bool);
+    void pushInt(int);
+    void pushNumber(double);
+    void pushString(const String&);
+    void pushValue(PassRefPtr<JSONValue>);
+    void pushObject(PassRefPtr<JSONObject>);
+    void pushArray(PassRefPtr<JSONArray>);
+
+    PassRefPtr<JSONValue> get(size_t index);
+
+    virtual void writeJSON(StringBuilder* output) const;
+
+    iterator begin() { return m_data.begin(); }
+    iterator end() { return m_data.end(); }
+    const_iterator begin() const { return m_data.begin(); }
+    const_iterator end() const { return m_data.end(); }
+
+protected:
+    JSONArrayBase();
+
+private:
+    Vector<RefPtr<JSONValue> > m_data;
+};
+
+class JSONArray : public JSONArrayBase {
+public:
+    static PassRefPtr<JSONArray> create()
+    {
+        return adoptRef(new JSONArray());
+    }
+
+    using JSONArrayBase::asArray;
+
+    using JSONArrayBase::pushBoolean;
+    using JSONArrayBase::pushInt;
+    using JSONArrayBase::pushNumber;
+    using JSONArrayBase::pushString;
+    using JSONArrayBase::pushValue;
+    using JSONArrayBase::pushObject;
+    using JSONArrayBase::pushArray;
+
+    using JSONArrayBase::get;
+
+    using JSONArrayBase::begin;
+    using JSONArrayBase::end;
+};
+
+
+inline JSONObjectBase::iterator JSONObjectBase::find(const String& name)
+{
+    return m_data.find(name);
+}
+
+inline JSONObjectBase::const_iterator JSONObjectBase::find(const String& name) const
+{
+    return m_data.find(name);
+}
+
+inline void JSONObjectBase::setBoolean(const String& name, bool value)
+{
+    setValue(name, JSONBasicValue::create(value));
+}
+
+inline void JSONObjectBase::setNumber(const String& name, double value)
+{
+    setValue(name, JSONBasicValue::create(value));
+}
+
+inline void JSONObjectBase::setString(const String& name, const String& value)
+{
+    setValue(name, JSONString::create(value));
+}
+
+inline void JSONObjectBase::setValue(const String& name, PassRefPtr<JSONValue> value)
+{
+    ASSERT(value);
+    if (m_data.set(name, value).isNewEntry)
+        m_order.append(name);
+}
+
+inline void JSONObjectBase::setObject(const String& name, PassRefPtr<JSONObject> value)
+{
+    ASSERT(value);
+    if (m_data.set(name, value).isNewEntry)
+        m_order.append(name);
+}
+
+inline void JSONObjectBase::setArray(const String& name, PassRefPtr<JSONArray> value)
+{
+    ASSERT(value);
+    if (m_data.set(name, value).isNewEntry)
+        m_order.append(name);
+}
+
+inline void JSONArrayBase::pushBoolean(bool value)
+{
+    m_data.append(JSONBasicValue::create(value));
+}
+
+inline void JSONArrayBase::pushInt(int value)
+{
+    m_data.append(JSONBasicValue::create(value));
+}
+
+inline void JSONArrayBase::pushNumber(double value)
+{
+    m_data.append(JSONBasicValue::create(value));
+}
+
+inline void JSONArrayBase::pushString(const String& value)
+{
+    m_data.append(JSONString::create(value));
+}
+
+inline void JSONArrayBase::pushValue(PassRefPtr<JSONValue> value)
+{
+    ASSERT(value);
+    m_data.append(value);
+}
+
+inline void JSONArrayBase::pushObject(PassRefPtr<JSONObject> value)
+{
+    ASSERT(value);
+    m_data.append(value);
+}
+
+inline void JSONArrayBase::pushArray(PassRefPtr<JSONArray> value)
+{
+    ASSERT(value);
+    m_data.append(value);
+}
+
+} // namespace WebCore
+
+#endif // !defined(JSONValues_h)
diff --git a/Source/core/platform/Length.cpp b/Source/core/platform/Length.cpp
index db840a0..89a1ee2 100644
--- a/Source/core/platform/Length.cpp
+++ b/Source/core/platform/Length.cpp
@@ -28,7 +28,6 @@
 #include "core/platform/CalculationValue.h"
 #include <wtf/ASCIICType.h>
 #include <wtf/Assertions.h>
-#include <wtf/OwnArrayPtr.h>
 #include <wtf/text/StringBuffer.h>
 #include <wtf/text/WTFString.h>
 
@@ -36,10 +35,10 @@
 
 namespace WebCore {
 
-static Length parseLength(const UChar* data, unsigned length)
+template<typename CharType>
+static unsigned splitLength(const CharType* data, unsigned length, unsigned& intLength, unsigned& doubleLength)
 {
-    if (length == 0)
-        return Length(1, Relative);
+    ASSERT(length);
 
     unsigned i = 0;
     while (i < length && isSpaceOrNewline(data[i]))
@@ -48,17 +47,44 @@
         ++i;
     while (i < length && isASCIIDigit(data[i]))
         ++i;
-    unsigned intLength = i;
+    intLength = i;
     while (i < length && (isASCIIDigit(data[i]) || data[i] == '.'))
         ++i;
-    unsigned doubleLength = i;
+    doubleLength = i;
 
     // IE quirk: Skip whitespace between the number and the % character (20 % => 20%).
     while (i < length && isSpaceOrNewline(data[i]))
         ++i;
 
+    return i;
+}
+
+template<typename CharType>
+static Length parseHTMLAreaCoordinate(const CharType* data, unsigned length)
+{
+    unsigned intLength;
+    unsigned doubleLength;
+    splitLength(data, length, intLength, doubleLength);
+
     bool ok;
-    UChar next = (i < length) ? data[i] : ' ';
+    int r = charactersToIntStrict(data, intLength, &ok);
+    if (ok)
+        return Length(r, Fixed);
+    return Length(0, Fixed);
+}
+
+template<typename CharType>
+static Length parseFrameSetDimension(const CharType* data, unsigned length)
+{
+    if (!length)
+        return Length(1, Relative);
+
+    unsigned intLength;
+    unsigned doubleLength;
+    unsigned i = splitLength(data, length, intLength, doubleLength);
+
+    bool ok;
+    CharType next = (i < length) ? data[i] : ' ';
     if (next == '%') {
         // IE quirk: accept decimal fractions for percentages.
         double r = charactersToDouble(data, doubleLength, &ok);
@@ -77,87 +103,88 @@
     return Length(0, Relative);
 }
 
-static int countCharacter(const UChar* data, unsigned length, UChar character)
-{
-    int count = 0;
-    for (int i = 0; i < static_cast<int>(length); ++i)
-        count += data[i] == character;
-    return count;
-}
-
-PassOwnArrayPtr<Length> newCoordsArray(const String& string, int& len)
+// FIXME: Per HTML5, this should follow the "rules for parsing a list of integers".
+Vector<Length> parseHTMLAreaElementCoords(const String& string)
 {
     unsigned length = string.length();
-    const UChar* data = string.characters();
-    StringBuffer<UChar> spacified(length);
+    StringBuffer<LChar> spacified(length);
     for (unsigned i = 0; i < length; i++) {
-        UChar cc = data[i];
-        if (cc > '9' || (cc < '0' && cc != '-' && cc != '*' && cc != '.'))
+        UChar cc = string[i];
+        if (cc > '9' || (cc < '0' && cc != '-' && cc != '.'))
             spacified[i] = ' ';
         else
             spacified[i] = cc;
     }
     RefPtr<StringImpl> str = StringImpl::adopt(spacified);
-
     str = str->simplifyWhiteSpace();
+    ASSERT(str->is8Bit());
 
-    len = countCharacter(str->characters(), str->length(), ' ') + 1;
-    OwnArrayPtr<Length> r = adoptArrayPtr(new Length[len]);
+    if (!str->length())
+        return Vector<Length>();
+
+    unsigned len = str->count(' ') + 1;
+    Vector<Length> r(len);
 
     int i = 0;
     unsigned pos = 0;
     size_t pos2;
 
     while ((pos2 = str->find(' ', pos)) != notFound) {
-        r[i++] = parseLength(str->characters() + pos, pos2 - pos);
-        pos = pos2+1;
+        r[i++] = parseHTMLAreaCoordinate(str->characters8() + pos, pos2 - pos);
+        pos = pos2 + 1;
     }
-    r[i] = parseLength(str->characters() + pos, str->length() - pos);
+    r[i] = parseHTMLAreaCoordinate(str->characters8() + pos, str->length() - pos);
 
     ASSERT(i == len - 1);
 
-    return r.release();
+    return r;
 }
 
-PassOwnArrayPtr<Length> newLengthArray(const String& string, int& len)
+template<typename CharType>
+static Vector<Length> parseFrameSetListOfDimensionsInternal(StringImpl* str)
 {
-    RefPtr<StringImpl> str = string.impl()->simplifyWhiteSpace();
-    if (!str->length()) {
-        len = 1;
-        return nullptr;
-    }
-
-    len = countCharacter(str->characters(), str->length(), ',') + 1;
-    OwnArrayPtr<Length> r = adoptArrayPtr(new Length[len]);
+    unsigned len = str->count(',') + 1;
+    Vector<Length> r(len);
 
     int i = 0;
     unsigned pos = 0;
     size_t pos2;
 
     while ((pos2 = str->find(',', pos)) != notFound) {
-        r[i++] = parseLength(str->characters() + pos, pos2 - pos);
-        pos = pos2+1;
+        r[i++] = parseFrameSetDimension(str->getCharacters<CharType>() + pos, pos2 - pos);
+        pos = pos2 + 1;
     }
 
     ASSERT(i == len - 1);
 
     // IE Quirk: If the last comma is the last char skip it and reduce len by one.
-    if (str->length()-pos > 0)
-        r[i] = parseLength(str->characters() + pos, str->length() - pos);
+    if (str->length() - pos > 0)
+        r[i] = parseFrameSetDimension(str->getCharacters<CharType>() + pos, str->length() - pos);
     else
-        len--;
+        r.shrink(r.size() - 1);
 
-    return r.release();
+    return r;
 }
-        
+
+// FIXME: Per HTML5, this should "use the rules for parsing a list of dimensions".
+Vector<Length> parseFrameSetListOfDimensions(const String& string)
+{
+    RefPtr<StringImpl> str = string.impl()->simplifyWhiteSpace();
+    if (!str->length())
+        return Vector<Length>();
+    if (str->is8Bit())
+        return parseFrameSetListOfDimensionsInternal<LChar>(str.get());
+    return parseFrameSetListOfDimensionsInternal<UChar>(str.get());
+}
+
 class CalculationValueHandleMap {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    CalculationValueHandleMap() 
-        : m_index(1) 
+    CalculationValueHandleMap()
+        : m_index(1)
     {
     }
-    
+
     int insert(PassRefPtr<CalculationValue> calcValue)
     {
         ASSERT(m_index);
@@ -166,9 +193,9 @@
         // of the handle space. Consider reusing empty handles.
         while (m_map.contains(m_index))
             m_index++;
-        
-        m_map.set(m_index, calcValue);       
-        
+
+        m_map.set(m_index, calcValue);
+
         return m_index;
     }
 
@@ -177,18 +204,18 @@
         ASSERT(m_map.contains(index));
         m_map.remove(index);
     }
-    
+
     PassRefPtr<CalculationValue> get(int index)
     {
         ASSERT(m_map.contains(index));
         return m_map.get(index);
     }
-    
-private:        
+
+private:
     int m_index;
     HashMap<int, RefPtr<CalculationValue> > m_map;
 };
-    
+
 static CalculationValueHandleMap& calcHandles()
 {
     DEFINE_STATIC_LOCAL(CalculationValueHandleMap, handleMap, ());
@@ -202,25 +229,25 @@
 {
     m_intValue = calcHandles().insert(calc);
 }
-        
+
 Length Length::blendMixedTypes(const Length& from, double progress) const
 {
     if (progress <= 0.0)
         return from;
-        
+
     if (progress >= 1.0)
         return *this;
-        
+
     OwnPtr<CalcExpressionNode> blend = adoptPtr(new CalcExpressionBlendLength(from, *this, progress));
     return Length(CalculationValue::create(blend.release(), CalculationRangeAll));
 }
-          
+
 PassRefPtr<CalculationValue> Length::calculationValue() const
 {
     ASSERT(isCalculated());
     return calcHandles().get(calculationHandle());
 }
-    
+
 void Length::incrementCalculatedRef() const
 {
     ASSERT(isCalculated());
@@ -234,7 +261,7 @@
     if (calcLength->hasOneRef())
         calcHandles().remove(calculationHandle());
     calcLength->deref();
-}    
+}
 
 float Length::nonNanCalculatedValue(int maxValue) const
 {
diff --git a/Source/core/platform/Length.h b/Source/core/platform/Length.h
index 285be4f..516c952 100644
--- a/Source/core/platform/Length.h
+++ b/Source/core/platform/Length.h
@@ -25,12 +25,12 @@
 
 #include <cstring>
 #include "core/platform/animation/AnimationUtilities.h"
-#include <wtf/Assertions.h>
-#include <wtf/FastAllocBase.h>
-#include <wtf/Forward.h>
-#include <wtf/HashMap.h>
-#include <wtf/MathExtras.h>
-#include <wtf/PassOwnArrayPtr.h>
+#include "wtf/Assertions.h"
+#include "wtf/FastAllocBase.h"
+#include "wtf/Forward.h"
+#include "wtf/HashMap.h"
+#include "wtf/MathExtras.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -309,8 +309,8 @@
     bool m_isFloat;
 };
 
-PassOwnArrayPtr<Length> newCoordsArray(const String&, int& len);
-PassOwnArrayPtr<Length> newLengthArray(const String&, int& len);
+Vector<Length> parseHTMLAreaElementCoords(const String&);
+Vector<Length> parseFrameSetListOfDimensions(const String&);
 
 } // namespace WebCore
 
diff --git a/Source/core/css/CSSStyleDeclaration.cpp b/Source/core/platform/Partitions.cpp
similarity index 75%
rename from Source/core/css/CSSStyleDeclaration.cpp
rename to Source/core/platform/Partitions.cpp
index 538e17e..3630819 100644
--- a/Source/core/css/CSSStyleDeclaration.cpp
+++ b/Source/core/platform/Partitions.cpp
@@ -28,19 +28,27 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
+
 #include "config.h"
-#include "core/css/CSSStyleDeclaration.h"
+#include "core/platform/Partitions.h"
 
-#include "core/css/CSSParser.h"
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/css/CSSStyleSheet.h"
-#include "core/css/CSSValue.h"
-#include "core/dom/Document.h"
-#include "core/dom/DocumentStyleSheetCollection.h"
-#include "core/dom/EventTarget.h"
-#include "core/html/HTMLStyleElement.h"
-#include "core/page/RuntimeCSSEnabled.h"
-
+#if ENABLE(PARTITION_ALLOC)
 namespace WebCore {
 
+PartitionRoot Partitions::m_objectModelRoot;
+
+void Partitions::init()
+{
+    partitionAllocInit(&m_objectModelRoot);
+}
+
+void Partitions::shutdown()
+{
+    // We could ASSERT here for a memory leak within the partition, but it leads
+    // to very hard to diagnose ASSERTs, so it's best to leave leak checking for
+    // the valgrind and heapcheck bots, which run without partitions.
+    (void) partitionAllocShutdown(&m_objectModelRoot);
+}
+#endif
+
 } // namespace WebCore
diff --git a/Source/core/workers/WorkerContextProxy.cpp b/Source/core/platform/Partitions.h
similarity index 79%
copy from Source/core/workers/WorkerContextProxy.cpp
copy to Source/core/platform/Partitions.h
index 7f0ff2e..56be59a 100644
--- a/Source/core/workers/WorkerContextProxy.cpp
+++ b/Source/core/platform/Partitions.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2012 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,11 +28,24 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/workers/WorkerContextProxy.h"
+#ifndef Partitions_h
+#define Partitions_h
+
+#include "wtf/PartitionAlloc.h"
 
 namespace WebCore {
 
-WorkerContextProxy::CreateDelegate* WorkerContextProxy::s_createDelegate = 0;
+class Partitions {
+public:
+    static void init();
+    static void shutdown();
+
+    ALWAYS_INLINE static PartitionRoot* getObjectModelPartition() { return &m_objectModelRoot; }
+
+private:
+    static PartitionRoot m_objectModelRoot;
+};
 
 } // namespace WebCore
+
+#endif // Partitions_h
diff --git a/Source/core/platform/PlatformPasteboard.h b/Source/core/platform/PlatformPasteboard.h
deleted file mode 100644
index d2f2036..0000000
--- a/Source/core/platform/PlatformPasteboard.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2012 Apple Inc.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
- */
-
-#ifndef PlatformPasteboard_h
-#define PlatformPasteboard_h
-
-#include "core/platform/SharedBuffer.h"
-#include <wtf/Forward.h>
-#include <wtf/RefCounted.h>
-#include <wtf/Vector.h>
-
-namespace WebCore {
-
-class Color;
-class KURL;
-
-class PlatformPasteboard {
-public:
-    explicit PlatformPasteboard(const String& pasteboardName);
-    static String uniqueName();
-    
-    void getTypes(Vector<String>& types);
-    PassRefPtr<SharedBuffer> bufferForType(const String& pasteboardType);
-    void getPathnamesForType(Vector<String>& pathnames, const String& pasteboardType);
-    String stringForType(const String& pasteboardType);
-    int changeCount() const;
-    Color color();
-    KURL url();
-    
-    void copy(const String& fromPasteboard);
-    void addTypes(const Vector<String>& pasteboardTypes);
-    void setTypes(const Vector<String>& pasteboardTypes);
-    void setBufferForType(PassRefPtr<SharedBuffer>, const String& pasteboardType);
-    void setPathnamesForType(const Vector<String>& pathnames, const String& pasteboardType);
-    void setStringForType(const String&, const String& pasteboardType);
-};
-
-}
-
-#endif // !PlatformPasteboard_h
diff --git a/Source/core/platform/PlatformSpeechSynthesis.h b/Source/core/platform/PlatformSpeechSynthesis.h
deleted file mode 100644
index 15ae4bb..0000000
--- a/Source/core/platform/PlatformSpeechSynthesis.h
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Computer, Inc.  All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef PlatformSpeechSynthesis_h
-#define PlatformSpeechSynthesis_h
-
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/Vector.h>
-
-namespace WebCore {
-    
-class SpeechSynthesis;
-class SpeechSynthesisUtterance;
-class SpeechSynthesisVoice;
-    
-class PlatformSpeechSynthesis : public RefCounted<PlatformSpeechSynthesis> {
-public:
-    static PassRefPtr<PlatformSpeechSynthesis> create(SpeechSynthesis*);
-    
-    void platformInitializeVoiceList(Vector<RefPtr<SpeechSynthesisVoice> >&);
-    void platformSpeak(SpeechSynthesisUtterance*);
-    
-private:
-    PlatformSpeechSynthesis(SpeechSynthesis*);
-
-    SpeechSynthesis* m_speechSynthesis;
-};
-    
-} // namespace WebCore
-
-#endif // PlatformSpeechSynthesis_h
diff --git a/Source/core/platform/ThreadCheck.h b/Source/core/platform/ThreadCheck.h
deleted file mode 100644
index 07eb463..0000000
--- a/Source/core/platform/ThreadCheck.h
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
- */
-
-#ifndef ThreadCheck_h
-#define ThreadCheck_h
-
-namespace WebCore {
-    enum ThreadViolationBehavior {
-        NoThreadCheck,
-        LogOnFirstThreadViolation,
-        LogOnThreadViolation,
-        RaiseExceptionOnThreadViolation
-    };
-    enum ThreadViolationRound {
-        ThreadViolationRoundOne = 0,
-        ThreadViolationRoundTwo,
-        MaximumThreadViolationRound
-    };
-    void setDefaultThreadViolationBehavior(ThreadViolationBehavior, ThreadViolationRound);
-    void reportThreadViolation(const char* function, ThreadViolationRound);
-}
-
-extern "C" void WebCoreReportThreadViolation(const char* function, WebCore::ThreadViolationRound);
-
-#define WebCoreThreadViolationCheckRoundOne() ::WebCore::reportThreadViolation(WTF_PRETTY_FUNCTION, WebCore::ThreadViolationRoundOne)
-#define WebCoreThreadViolationCheckRoundTwo() ::WebCore::reportThreadViolation(WTF_PRETTY_FUNCTION, WebCore::ThreadViolationRoundTwo)
-
-#endif
diff --git a/Source/core/platform/ThreadTimers.cpp b/Source/core/platform/ThreadTimers.cpp
index 9996049..19ec847 100644
--- a/Source/core/platform/ThreadTimers.cpp
+++ b/Source/core/platform/ThreadTimers.cpp
@@ -30,6 +30,7 @@
 #include "core/platform/SharedTimer.h"
 #include "core/platform/ThreadGlobalData.h"
 #include "core/platform/Timer.h"
+#include "core/platform/chromium/TraceEvent.h"
 #include <wtf/CurrentTime.h>
 #include <wtf/MainThread.h>
 
@@ -101,8 +102,12 @@
 
 void ThreadTimers::sharedTimerFired()
 {
+    TRACE_EVENT_SAMPLING_STATE0("Blink\0Blink-Internal");
+
     // Redirect to non-static method.
     threadGlobalData().threadTimers().sharedTimerFiredInternal();
+
+    TRACE_EVENT_SAMPLING_STATE0("Blink\0Blink-Sleeping");
 }
 
 void ThreadTimers::sharedTimerFiredInternal()
diff --git a/Source/core/platform/audio/AudioSession.h b/Source/core/platform/audio/AudioSession.h
deleted file mode 100644
index 7c202eb..0000000
--- a/Source/core/platform/audio/AudioSession.h
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioSession_h
-#define AudioSession_h
-
-#include <wtf/HashSet.h>
-#include <wtf/OwnPtr.h>
-
-namespace WebCore {
-
-class AudioSessionListener;
-class AudioSessionPrivate;
-
-class AudioSession {
-    WTF_MAKE_NONCOPYABLE(AudioSession);
-public:
-    static AudioSession& sharedSession();
-
-    enum CategoryType {
-        None,
-        AmbientSound,
-        SoloAmbientSound,
-        MediaPlayback,
-        RecordAudio,
-        PlayAndRecord,
-        AudioProcessing,
-    };
-    void setCategory(CategoryType);
-    CategoryType category() const;
-
-    void setCategoryOverride(CategoryType);
-    CategoryType categoryOverride() const;
-
-    void addListener(AudioSessionListener*);
-    void removeListener(AudioSessionListener*);
-
-    float sampleRate() const;
-    size_t numberOfOutputChannels() const;
-
-    void setActive(bool);
-
-    float preferredBufferDuration() const;
-    void setPreferredBufferDuration(float seconds);
-
-    void beganAudioInterruption();
-    void endedAudioInterruption();
-
-private:
-    AudioSession();
-    ~AudioSession();
-
-    OwnPtr<AudioSessionPrivate> m_private;
-    HashSet<AudioSessionListener*> m_listeners;
-};
-
-}
-
-#endif // AudioSession_h
diff --git a/Source/core/platform/audio/AudioSessionListener.h b/Source/core/platform/audio/AudioSessionListener.h
deleted file mode 100644
index 62c5b11..0000000
--- a/Source/core/platform/audio/AudioSessionListener.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef AudioSessionListener_h
-#define AudioSessionListener_h
-
-namespace WebCore {
-
-class AudioSessionListener {
-    WTF_MAKE_NONCOPYABLE(AudioSessionListener)
-public:
-    virtual void beganAudioInterruption() = 0;
-    virtual void endedAudioInterruption() = 0;
-protected:
-    AudioSessionListener() { }
-    virtual ~AudioSessionListener() { }
-};
-
-}
-
-#endif // AudioSessionListener_h
diff --git a/Source/core/platform/chromium/ClipboardChromium.cpp b/Source/core/platform/chromium/ClipboardChromium.cpp
index 363d378..2e2dbab 100644
--- a/Source/core/platform/chromium/ClipboardChromium.cpp
+++ b/Source/core/platform/chromium/ClipboardChromium.cpp
@@ -323,19 +323,18 @@
     setDragImage(0, node, loc);
 }
 
-DragImageRef ClipboardChromium::createDragImage(IntPoint& loc) const
+PassOwnPtr<DragImage> ClipboardChromium::createDragImage(IntPoint& loc) const
 {
-    DragImageRef result = 0;
     if (m_dragImageElement) {
         if (m_frame) {
-            result = m_frame->nodeImage(m_dragImageElement.get());
             loc = m_dragLoc;
+            return m_frame->nodeImage(m_dragImageElement.get());
         }
     } else if (m_dragImage) {
-        result = createDragImageFromImage(m_dragImage->image());
         loc = m_dragLoc;
+        return DragImage::create(m_dragImage->image());
     }
-    return result;
+    return nullptr;
 }
 
 static CachedImage* getCachedImage(Element* element)
diff --git a/Source/core/platform/chromium/ClipboardChromium.h b/Source/core/platform/chromium/ClipboardChromium.h
index 0058651..893e98d 100644
--- a/Source/core/platform/chromium/ClipboardChromium.h
+++ b/Source/core/platform/chromium/ClipboardChromium.h
@@ -95,7 +95,7 @@
             return m_dataObject;
         }
 
-        virtual DragImageRef createDragImage(IntPoint& dragLoc) const;
+        virtual PassOwnPtr<DragImage> createDragImage(IntPoint& dragLoc) const;
         virtual void declareAndWriteDragImage(Element*, const KURL&, const String& title, Frame*);
         virtual void writeURL(const KURL&, const String&, Frame*);
         virtual void writeRange(Range*, Frame*);
diff --git a/Source/core/platform/chromium/DragImageChromiumSkia.cpp b/Source/core/platform/chromium/DragImageChromiumSkia.cpp
deleted file mode 100644
index f4663d0..0000000
--- a/Source/core/platform/chromium/DragImageChromiumSkia.cpp
+++ /dev/null
@@ -1,153 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- * 
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- * 
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- * 
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/DragImage.h"
-
-#include "SkBitmap.h"
-#include "SkCanvas.h"
-#include "SkMatrix.h"
-#include "core/platform/NotImplemented.h"
-#include "core/platform/graphics/BitmapImage.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/Image.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
-
-#include "skia/ext/image_operations.h"
-
-#include <wtf/RefPtr.h>
-
-namespace WebCore {
-
-IntSize dragImageSize(DragImageRef image)
-{
-    if (!image)
-        return IntSize();
-
-    return IntSize(image->bitmap->width(), image->bitmap->height());
-}
-
-void deleteDragImage(DragImageRef image)
-{
-    if (image)
-        delete image->bitmap;
-    delete image;
-}
-
-DragImageRef scaleDragImage(DragImageRef image, FloatSize scale)
-{
-    if (!image)
-        return 0;
-
-    int imageWidth = scale.width() * image->bitmap->width();
-    int imageHeight = scale.height() * image->bitmap->height();
-    SkBitmap* scaledImage = new SkBitmap(
-        skia::ImageOperations::Resize(*image->bitmap, skia::ImageOperations::RESIZE_LANCZOS3,
-                                      imageWidth, imageHeight));
-    delete image->bitmap;
-    image->bitmap = scaledImage;
-    return image;
-}
-
-DragImageRef dissolveDragImageToFraction(DragImageRef image, float fraction)
-{
-    if (!image)
-        return 0;
-
-    image->bitmap->setIsOpaque(false);
-    image->bitmap->lockPixels();
-
-    for (int row = 0; row < image->bitmap->height(); ++row) {
-        for (int column = 0; column < image->bitmap->width(); ++column) {
-            uint32_t* pixel = image->bitmap->getAddr32(column, row);
-            *pixel = SkPreMultiplyARGB(SkColorGetA(*pixel) * fraction,
-                                       SkColorGetR(*pixel),
-                                       SkColorGetG(*pixel),
-                                       SkColorGetB(*pixel));
-        }
-    }
-
-    image->bitmap->unlockPixels();
-
-    return image;
-}
-
-DragImageRef createDragImageFromImage(Image* image, RespectImageOrientationEnum shouldRespectImageOrientation)
-{
-    if (!image)
-        return 0;
-
-    RefPtr<NativeImageSkia> bitmap = image->nativeImageForCurrentFrame();
-    if (!bitmap)
-        return 0;
-
-    DragImageChromium* dragImageChromium = new DragImageChromium;
-    dragImageChromium->bitmap = new SkBitmap();
-    dragImageChromium->resolutionScale = bitmap->resolutionScale();
-
-    if (image->isBitmapImage()) {
-        ImageOrientation orientation = DefaultImageOrientation;
-        BitmapImage* bitmapImage = static_cast<BitmapImage*>(image);
-        IntSize sizeRespectingOrientation = bitmapImage->sizeRespectingOrientation();
-
-        if (shouldRespectImageOrientation == RespectImageOrientation)
-            orientation = bitmapImage->currentFrameOrientation();
-
-        if (orientation != DefaultImageOrientation) {
-            // Construct a correctly-rotated copy of the image to use as the drag image.
-            dragImageChromium->bitmap->setConfig(
-                SkBitmap::kARGB_8888_Config, sizeRespectingOrientation.width(), sizeRespectingOrientation.height());
-            dragImageChromium->bitmap->allocPixels();
-
-            FloatRect destRect(FloatPoint(), sizeRespectingOrientation);
-            SkCanvas canvas(*dragImageChromium->bitmap);
-
-            canvas.concat(orientation.transformFromDefault(sizeRespectingOrientation));
-
-            if (orientation.usesWidthAsHeight())
-                destRect = FloatRect(destRect.x(), destRect.y(), destRect.height(), destRect.width());
-
-            canvas.drawBitmapRect(bitmap->bitmap(), 0, destRect);
-            return dragImageChromium;
-        }
-    }
-
-    bitmap->bitmap().copyTo(dragImageChromium->bitmap, SkBitmap::kARGB_8888_Config);
-    return dragImageChromium;
-}
-
-DragImageRef createDragImageIconForCachedImage(CachedImage*)
-{
-    notImplemented();
-    return 0;
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/chromium/DragImageRef.h b/Source/core/platform/chromium/DragImageRef.h
deleted file mode 100644
index 0d03262..0000000
--- a/Source/core/platform/chromium/DragImageRef.h
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright (c) 2008, 2009, Google Inc. All rights reserved.
-// 
-// Redistribution and use in source and binary forms, with or without
-// modification, are permitted provided that the following conditions are
-// met:
-// 
-//     * Redistributions of source code must retain the above copyright
-// notice, this list of conditions and the following disclaimer.
-//     * Redistributions in binary form must reproduce the above
-// copyright notice, this list of conditions and the following disclaimer
-// in the documentation and/or other materials provided with the
-// distribution.
-//     * Neither the name of Google Inc. nor the names of its
-// contributors may be used to endorse or promote products derived from
-// this software without specific prior written permission.
-// 
-// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-#ifndef DragImageRef_h
-#define DragImageRef_h
-
-class SkBitmap;
-
-namespace WebCore {
-
-struct DragImageChromium {
-    SkBitmap* bitmap;
-    float resolutionScale;
-};
-
-typedef DragImageChromium* DragImageRef;
-
-} // namespace WebCore
-
-#endif
diff --git a/Source/core/platform/chromium/FileSystemChromiumWin.cpp b/Source/core/platform/chromium/FileSystemChromiumWin.cpp
index f3c34d9..4ceec8a 100644
--- a/Source/core/platform/chromium/FileSystemChromiumWin.cpp
+++ b/Source/core/platform/chromium/FileSystemChromiumWin.cpp
@@ -38,7 +38,7 @@
 
 String pathGetFileName(const String& path)
 {
-    return String(PathFindFileName(String(path).charactersWithNullTermination()));
+    return String(PathFindFileName(path.charactersWithNullTermination().data()));
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/chromium/TraceEvent.h b/Source/core/platform/chromium/TraceEvent.h
index b9818e9..1e70c41 100644
--- a/Source/core/platform/chromium/TraceEvent.h
+++ b/Source/core/platform/chromium/TraceEvent.h
@@ -541,7 +541,7 @@
 // and thus cannot trace states of multiple threads.
 #define INTERNAL_TRACE_EVENT_SAMPLING_STATE(name, threadBucket) \
     do { \
-        *WebCore::traceSamplingState##threadBucket = reinterpret_cast<TraceEventAPIAtomicWord>("WebKit\0" name); \
+        *WebCore::traceSamplingState##threadBucket = reinterpret_cast<long>(name); \
     } while (0);
 
 // Notes regarding the following definitions:
@@ -793,6 +793,34 @@
     Data m_data;
 };
 
+class SamplingState0Scope {
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    SamplingState0Scope(const char* name)
+    {
+        m_previousState0 = *WebCore::traceSamplingState0;
+        *WebCore::traceSamplingState0 = reinterpret_cast<long>(const_cast<char*>(name));
+    }
+
+    ~SamplingState0Scope()
+    {
+        *WebCore::traceSamplingState0 = m_previousState0;
+    }
+
+    static inline const char* current()
+    {
+        return reinterpret_cast<const char*>(*WebCore::traceSamplingState0);
+    }
+
+    static inline void forceCurrent(const char* name)
+    {
+        *WebCore::traceSamplingState0 = reinterpret_cast<long>(const_cast<char*>(name));
+    }
+
+private:
+    long m_previousState0;
+};
+
 } // namespace TraceEvent
 
 } // namespace WebCore
diff --git a/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp b/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp
new file mode 100644
index 0000000..0ca2d40
--- /dev/null
+++ b/Source/core/platform/chromium/support/WebCryptoAlgorithm.cpp
@@ -0,0 +1,100 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "public/platform/WebCryptoAlgorithm.h"
+
+#include "public/platform/WebCryptoAlgorithmParams.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/ThreadSafeRefCounted.h"
+
+namespace WebKit {
+
+class WebCryptoAlgorithmPrivate : public ThreadSafeRefCounted<WebCryptoAlgorithmPrivate> {
+public:
+    WebCryptoAlgorithmPrivate(WebCryptoAlgorithmId algorithmId, const char* algorithmName, PassOwnPtr<WebCryptoAlgorithmParams> params)
+        : algorithmId(algorithmId)
+        , algorithmName(algorithmName)
+        , params(params)
+    {
+    }
+
+    WebCryptoAlgorithmId algorithmId;
+    const char* const algorithmName;
+    OwnPtr<WebCryptoAlgorithmParams> params;
+};
+
+WebCryptoAlgorithm::WebCryptoAlgorithm(WebCryptoAlgorithmId algorithmId, const char* algorithmName, PassOwnPtr<WebCryptoAlgorithmParams> params)
+    : m_private(adoptRef(new WebCryptoAlgorithmPrivate(algorithmId, algorithmName, params)))
+{
+}
+
+WebCryptoAlgorithmId WebCryptoAlgorithm::algorithmId() const
+{
+    return m_private->algorithmId;
+}
+
+const char* WebCryptoAlgorithm::algorithmName() const
+{
+    return m_private->algorithmName;
+}
+
+WebCryptoAlgorithmParamsType WebCryptoAlgorithm::paramsType() const
+{
+    if (!m_private->params)
+        return WebCryptoAlgorithmParamsTypeNone;
+    return m_private->params->type();
+}
+
+WebCryptoAesCbcParams* WebCryptoAlgorithm::aesCbcParams() const
+{
+    if (paramsType() == WebCryptoAlgorithmParamsTypeAesCbcParams)
+        return static_cast<WebCryptoAesCbcParams*>(m_private->params.get());
+    return 0;
+}
+
+WebCryptoAesKeyGenParams* WebCryptoAlgorithm::aesKeyGenParams() const
+{
+    if (paramsType() == WebCryptoAlgorithmParamsTypeAesKeyGenParams)
+        return static_cast<WebCryptoAesKeyGenParams*>(m_private->params.get());
+    return 0;
+}
+
+void WebCryptoAlgorithm::assign(const WebCryptoAlgorithm& other)
+{
+    m_private = other.m_private;
+}
+
+void WebCryptoAlgorithm::reset()
+{
+    m_private.reset();
+}
+
+} // namespace WebKit
diff --git a/Source/core/platform/chromium/support/WebFilterOperation.cpp b/Source/core/platform/chromium/support/WebFilterOperation.cpp
deleted file mode 100644
index d948cb2..0000000
--- a/Source/core/platform/chromium/support/WebFilterOperation.cpp
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "public/platform/WebFilterOperation.h"
-
-#include <string.h>
-
-namespace WebKit {
-
-bool WebFilterOperation::equals(const WebFilterOperation& other) const
-{
-    if (m_type != other.m_type)
-        return false;
-    if (m_type == FilterTypeColorMatrix)
-        return !memcmp(m_matrix, other.m_matrix, sizeof(m_matrix));
-    if (m_type == FilterTypeDropShadow) {
-        return m_amount == other.m_amount
-            && m_dropShadowOffset == other.m_dropShadowOffset
-            && m_dropShadowColor == other.m_dropShadowColor;
-    } else
-        return m_amount == other.m_amount;
-}
-
-WebFilterOperation::WebFilterOperation(FilterType type, SkScalar matrix[20])
-    : m_type(type)
-    , m_amount(0)
-    , m_dropShadowOffset(0, 0)
-    , m_dropShadowColor(0)
-    , m_zoomInset(0)
-{
-    WEBKIT_ASSERT(m_type == FilterTypeColorMatrix);
-    memcpy(m_matrix, matrix, sizeof(m_matrix));
-}
-
-} // namespace WebKit
diff --git a/Source/core/platform/chromium/support/WebFilterOperations.cpp b/Source/core/platform/chromium/support/WebFilterOperations.cpp
deleted file mode 100644
index 223caf3..0000000
--- a/Source/core/platform/chromium/support/WebFilterOperations.cpp
+++ /dev/null
@@ -1,163 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include <cmath>
-#include "public/platform/WebFilterOperation.h"
-#include "public/platform/WebFilterOperations.h"
-#include <wtf/Vector.h>
-
-namespace WebKit {
-
-class WebFilterOperationsPrivate {
-public:
-    Vector<WebFilterOperation> operations;
-};
-
-
-void WebFilterOperations::initialize()
-{
-    m_private.reset(new WebFilterOperationsPrivate);
-}
-
-void WebFilterOperations::destroy()
-{
-    m_private.reset(0);
-}
-
-void WebFilterOperations::assign(const WebFilterOperations& other)
-{
-    m_private->operations = other.m_private->operations;
-}
-
-bool WebFilterOperations::equals(const WebFilterOperations& other) const
-{
-    if (other.size() != size())
-        return false;
-    for (size_t i = 0; i < m_private->operations.size(); ++i) {
-        if (other.at(i) != at(i))
-            return false;
-    }
-    return true;
-}
-
-void WebFilterOperations::append(const WebFilterOperation& filter)
-{
-    m_private->operations.append(filter);
-}
-
-void WebFilterOperations::clear()
-{
-    m_private->operations.clear();
-}
-
-bool WebFilterOperations::isEmpty() const
-{
-    return m_private->operations.isEmpty();
-}
-
-static int spreadForStdDeviation(float stdDeviation)
-{
-    // https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html#feGaussianBlurElement provides this approximation for
-    // evaluating a gaussian blur by a triple box filter.
-    float d = floorf(stdDeviation * 3 * sqrt(8.f * atan(1.f)) / 4 + 0.5);
-    return static_cast<int>(ceilf(d * 3 / 2));
-}
-
-void WebFilterOperations::getOutsets(int& top, int& right, int& bottom, int& left) const
-{
-    top = right = bottom = left = 0;
-    for (size_t i = 0; i < m_private->operations.size(); ++i) {
-        const WebFilterOperation op = m_private->operations[i];
-        if (op.type() == WebFilterOperation::FilterTypeBlur || op.type() == WebFilterOperation::FilterTypeDropShadow) {
-            int spread = spreadForStdDeviation(op.amount());
-            if (op.type() == WebFilterOperation::FilterTypeBlur) {
-                top += spread;
-                right += spread;
-                bottom += spread;
-                left += spread;
-            } else {
-                top += spread - op.dropShadowOffset().y;
-                right += spread + op.dropShadowOffset().x;
-                bottom += spread + op.dropShadowOffset().y;
-                left += spread - op.dropShadowOffset().x;
-            }
-        }
-    }
-}
-
-bool WebFilterOperations::hasFilterThatMovesPixels() const
-{
-    for (size_t i = 0; i < m_private->operations.size(); ++i) {
-        const WebFilterOperation op = m_private->operations[i];
-        switch (op.type()) {
-        case WebFilterOperation::FilterTypeBlur:
-        case WebFilterOperation::FilterTypeDropShadow:
-        case WebFilterOperation::FilterTypeZoom:
-            return true;
-        default:
-            break;
-        }
-    }
-    return false;
-}
-
-bool WebFilterOperations::hasFilterThatAffectsOpacity() const
-{
-    for (size_t i = 0; i < m_private->operations.size(); ++i) {
-        const WebFilterOperation op = m_private->operations[i];
-        switch (op.type()) {
-        case WebFilterOperation::FilterTypeOpacity:
-        case WebFilterOperation::FilterTypeBlur:
-        case WebFilterOperation::FilterTypeDropShadow:
-        case WebFilterOperation::FilterTypeZoom:
-            return true;
-        case WebFilterOperation::FilterTypeColorMatrix: {
-            const SkScalar* matrix = op.matrix();
-            return matrix[15]
-                || matrix[16]
-                || matrix[17]
-                || matrix[18] != 1
-                || matrix[19];
-        }
-        default:
-            break;
-        }
-    }
-    return false;
-}
-
-size_t WebFilterOperations::size() const
-{
-    return m_private->operations.size();
-}
-
-WebFilterOperation WebFilterOperations::at(size_t i) const
-{
-    return m_private->operations.at(i);
-}
-
-} // namespace WebKit
diff --git a/Source/core/platform/chromium/support/WebMediaStreamSourcesRequest.cpp b/Source/core/platform/chromium/support/WebMediaStreamSourcesRequest.cpp
deleted file mode 100644
index df6af0b..0000000
--- a/Source/core/platform/chromium/support/WebMediaStreamSourcesRequest.cpp
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (C) 2012 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "public/platform/WebMediaStreamSourcesRequest.h"
-
-#include "core/platform/mediastream/MediaStreamSource.h"
-#include "core/platform/mediastream/MediaStreamSourcesQueryClient.h"
-#include "public/platform/WebMediaStreamSource.h"
-#include "public/platform/WebVector.h"
-#include <wtf/Vector.h>
-
-using namespace WebCore;
-
-namespace WebKit {
-
-WebMediaStreamSourcesRequest::WebMediaStreamSourcesRequest(const PassRefPtr<WebCore::MediaStreamSourcesQueryClient>& queryClient)
-    : m_private(queryClient)
-{
-}
-
-void WebMediaStreamSourcesRequest::reset()
-{
-    m_private.reset();
-}
-
-bool WebMediaStreamSourcesRequest::audio() const
-{
-    ASSERT(!isNull());
-    return m_private->audio();
-}
-
-bool WebMediaStreamSourcesRequest::video() const
-{
-    ASSERT(!isNull());
-    return m_private->video();
-}
-
-void WebMediaStreamSourcesRequest::didCompleteQuery(const WebVector<WebMediaStreamSource>& audioSources, const WebVector<WebMediaStreamSource>& videoSources) const
-{
-    ASSERT(!isNull());
-    MediaStreamSourceVector audio;
-    for (size_t i = 0; i < audioSources.size(); ++i) {
-        MediaStreamSource* curr = audioSources[i];
-        audio.append(curr);
-    }
-    MediaStreamSourceVector video;
-    for (size_t i = 0; i < videoSources.size(); ++i) {
-        MediaStreamSource* curr = videoSources[i];
-        video.append(curr);
-    }
-    m_private->didCompleteQuery(audio, video);
-}
-
-} // namespace WebKit
diff --git a/Source/core/platform/graphics/BitmapImage.cpp b/Source/core/platform/graphics/BitmapImage.cpp
index 5a1f9cc..5b6c81b 100644
--- a/Source/core/platform/graphics/BitmapImage.cpp
+++ b/Source/core/platform/graphics/BitmapImage.cpp
@@ -32,10 +32,12 @@
 #include "core/platform/graphics/FloatRect.h"
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/platform/graphics/ImageObserver.h"
+#include "core/platform/graphics/skia/NativeImageSkia.h"
 #include "core/platform/graphics/skia/SkiaUtils.h"
 #include "wtf/CurrentTime.h"
 #include "wtf/MemoryInstrumentationVector.h"
 #include "wtf/MemoryObjectInfo.h"
+#include "wtf/PassRefPtr.h"
 #include "wtf/Vector.h"
 #include "wtf/text/WTFString.h"
 
@@ -370,7 +372,7 @@
     return true;
 }
 
-PassNativeImagePtr BitmapImage::frameAtIndex(size_t index)
+PassRefPtr<NativeImageSkia> BitmapImage::frameAtIndex(size_t index)
 {
     if (!ensureFrameIsCached(index))
         return 0;
@@ -391,7 +393,7 @@
     return m_source.frameDurationAtIndex(index);
 }
 
-PassNativeImagePtr BitmapImage::nativeImageForCurrentFrame()
+PassRefPtr<NativeImageSkia> BitmapImage::nativeImageForCurrentFrame()
 {
     return frameAtIndex(currentFrame());
 }
@@ -672,7 +674,7 @@
 {
     MemoryClassInfo info(memoryObjectInfo, this, PlatformMemoryTypes::Image);
     memoryObjectInfo->setClassName("FrameData");
-    info.addMember(m_frame, "frame", WTF::RetainingPointer);
+    info.addMember(m_frame, "frame");
 }
 
 }
diff --git a/Source/core/platform/graphics/BitmapImage.h b/Source/core/platform/graphics/BitmapImage.h
index ad755e7..6ee322c 100644
--- a/Source/core/platform/graphics/BitmapImage.h
+++ b/Source/core/platform/graphics/BitmapImage.h
@@ -33,19 +33,21 @@
 #include "core/platform/graphics/ImageOrientation.h"
 #include "core/platform/graphics/ImageSource.h"
 #include "core/platform/graphics/IntSize.h"
+#include "wtf/Forward.h"
 
 namespace WebCore {
-    struct FrameData;
+struct FrameData;
 }
 
 namespace WTF {
-    template<> struct VectorTraits<WebCore::FrameData> : public SimpleClassVectorTraits {
-        static const bool canInitializeWithMemset = false; // Not all FrameData members initialize to 0.
-    };
+template<> struct VectorTraits<WebCore::FrameData> : public SimpleClassVectorTraits {
+    static const bool canInitializeWithMemset = false; // Not all FrameData members initialize to 0.
+};
 }
 
 namespace WebCore {
 
+class NativeImageSkia;
 template <typename T> class Timer;
 
 // ================================================
@@ -77,7 +79,7 @@
 
     void reportMemoryUsage(MemoryObjectInfo*) const;
 
-    NativeImagePtr m_frame;
+    RefPtr<NativeImageSkia> m_frame;
     ImageOrientation m_orientation;
     float m_duration;
     bool m_haveMetadata : 1;
@@ -96,7 +98,7 @@
     friend class GeneratorGeneratedImage;
     friend class GraphicsContext;
 public:
-    static PassRefPtr<BitmapImage> create(PassNativeImagePtr nativeImage, ImageObserver* observer = 0)
+    static PassRefPtr<BitmapImage> create(PassRefPtr<NativeImageSkia> nativeImage, ImageObserver* observer = 0)
     {
         return adoptRef(new BitmapImage(nativeImage, observer));
     }
@@ -126,7 +128,7 @@
 
     virtual unsigned decodedSize() const OVERRIDE;
 
-    virtual PassNativeImagePtr nativeImageForCurrentFrame() OVERRIDE;
+    virtual PassRefPtr<NativeImageSkia> nativeImageForCurrentFrame() OVERRIDE;
     virtual bool currentFrameKnownToBeOpaque() OVERRIDE;
 
     ImageOrientation currentFrameOrientation();
@@ -147,7 +149,7 @@
       Certain     // The repetition count is known to be correct.
     };
 
-    BitmapImage(PassNativeImagePtr, ImageObserver* = 0);
+    BitmapImage(PassRefPtr<NativeImageSkia>, ImageObserver* = 0);
     BitmapImage(ImageObserver* = 0);
 
     virtual void draw(GraphicsContext*, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator, BlendMode) OVERRIDE;
@@ -155,7 +157,7 @@
 
     size_t currentFrame() const { return m_currentFrame; }
     size_t frameCount();
-    PassNativeImagePtr frameAtIndex(size_t);
+    PassRefPtr<NativeImageSkia> frameAtIndex(size_t);
     bool frameIsCompleteAtIndex(size_t);
     float frameDurationAtIndex(size_t);
     bool frameHasAlphaAtIndex(size_t);
diff --git a/Source/core/platform/graphics/Color.cpp b/Source/core/platform/graphics/Color.cpp
index c6bdeb2..568815d 100644
--- a/Source/core/platform/graphics/Color.cpp
+++ b/Source/core/platform/graphics/Color.cpp
@@ -167,7 +167,7 @@
         return false;
     if (name.is8Bit())
         return parseHexColor(name.characters8(), name.length(), rgb);
-    return parseHexColor(name.characters(), name.length(), rgb);
+    return parseHexColor(name.characters16(), name.length(), rgb);
 }
 
 int differenceSquared(const Color& c1, const Color& c2)
@@ -184,7 +184,7 @@
         if (name.is8Bit())
             m_valid = parseHexColor(name.characters8() + 1, name.length() - 1, m_color);
         else
-            m_valid = parseHexColor(name.characters() + 1, name.length() - 1, m_color);
+            m_valid = parseHexColor(name.characters16() + 1, name.length() - 1, m_color);
     } else
         setNamedColor(name);
 }
diff --git a/Source/core/platform/graphics/FontDescription.cpp b/Source/core/platform/graphics/FontDescription.cpp
index 89b57b2..5b0f32c 100644
--- a/Source/core/platform/graphics/FontDescription.cpp
+++ b/Source/core/platform/graphics/FontDescription.cpp
@@ -45,27 +45,19 @@
 
 FontWeight FontDescription::lighterWeight(void) const
 {
-    // FIXME: Should actually return the CSS weight corresponding to next lightest
-    // weight of the currently used font family.
     switch (m_weight) {
         case FontWeight100:
         case FontWeight200:
-            return FontWeight100;
-
         case FontWeight300:
-            return FontWeight200;
-
         case FontWeight400:
         case FontWeight500:
-            return FontWeight300;
+            return FontWeight100;
 
         case FontWeight600:
         case FontWeight700:
             return FontWeight400;
 
         case FontWeight800:
-            return FontWeight500;
-
         case FontWeight900:
             return FontWeight700;
     }
@@ -75,13 +67,9 @@
 
 FontWeight FontDescription::bolderWeight(void) const
 {
-    // FIXME: Should actually return the CSS weight corresponding to next heaviest
-    // weight of the currently used font family.
     switch (m_weight) {
         case FontWeight100:
         case FontWeight200:
-            return FontWeight300;
-
         case FontWeight300:
             return FontWeight400;
 
@@ -91,8 +79,6 @@
 
         case FontWeight600:
         case FontWeight700:
-            return FontWeight800;
-
         case FontWeight800:
         case FontWeight900:
             return FontWeight900;
diff --git a/Source/core/platform/graphics/FontSmoothingMode.h b/Source/core/platform/graphics/FontSmoothingMode.h
index 7c23394..8d070eb 100644
--- a/Source/core/platform/graphics/FontSmoothingMode.h
+++ b/Source/core/platform/graphics/FontSmoothingMode.h
@@ -28,7 +28,7 @@
 
 namespace WebCore {
 
-    enum FontSmoothingMode { AutoSmoothing, NoSmoothing, Antialiased, SubpixelAntialiased };
+enum FontSmoothingMode { AutoSmoothing, NoSmoothing, Antialiased, SubpixelAntialiased };
     
 } // namespace WebCore
 
diff --git a/Source/core/platform/graphics/FontTraitsMask.h b/Source/core/platform/graphics/FontTraitsMask.h
index 686c30c..643d5f0 100644
--- a/Source/core/platform/graphics/FontTraitsMask.h
+++ b/Source/core/platform/graphics/FontTraitsMask.h
@@ -28,43 +28,43 @@
 
 namespace WebCore {
 
-    enum {
-        FontStyleNormalBit = 0,
-        FontStyleItalicBit,
-        FontVariantNormalBit,
-        FontVariantSmallCapsBit,
-        FontWeight100Bit,
-        FontWeight200Bit,
-        FontWeight300Bit,
-        FontWeight400Bit,
-        FontWeight500Bit,
-        FontWeight600Bit,
-        FontWeight700Bit,
-        FontWeight800Bit,
-        FontWeight900Bit,
-        FontTraitsMaskWidth
-    };
+enum {
+    FontStyleNormalBit = 0,
+    FontStyleItalicBit,
+    FontVariantNormalBit,
+    FontVariantSmallCapsBit,
+    FontWeight100Bit,
+    FontWeight200Bit,
+    FontWeight300Bit,
+    FontWeight400Bit,
+    FontWeight500Bit,
+    FontWeight600Bit,
+    FontWeight700Bit,
+    FontWeight800Bit,
+    FontWeight900Bit,
+    FontTraitsMaskWidth
+};
 
-    enum FontTraitsMask {
-        FontStyleNormalMask = 1 << FontStyleNormalBit,
-        FontStyleItalicMask = 1 << FontStyleItalicBit,
-        FontStyleMask = FontStyleNormalMask | FontStyleItalicMask,
+enum FontTraitsMask {
+    FontStyleNormalMask = 1 << FontStyleNormalBit,
+    FontStyleItalicMask = 1 << FontStyleItalicBit,
+    FontStyleMask = FontStyleNormalMask | FontStyleItalicMask,
 
-        FontVariantNormalMask = 1 << FontVariantNormalBit,
-        FontVariantSmallCapsMask = 1 << FontVariantSmallCapsBit,
-        FontVariantMask = FontVariantNormalMask | FontVariantSmallCapsMask,
+    FontVariantNormalMask = 1 << FontVariantNormalBit,
+    FontVariantSmallCapsMask = 1 << FontVariantSmallCapsBit,
+    FontVariantMask = FontVariantNormalMask | FontVariantSmallCapsMask,
 
-        FontWeight100Mask = 1 << FontWeight100Bit,
-        FontWeight200Mask = 1 << FontWeight200Bit,
-        FontWeight300Mask = 1 << FontWeight300Bit,
-        FontWeight400Mask = 1 << FontWeight400Bit,
-        FontWeight500Mask = 1 << FontWeight500Bit,
-        FontWeight600Mask = 1 << FontWeight600Bit,
-        FontWeight700Mask = 1 << FontWeight700Bit,
-        FontWeight800Mask = 1 << FontWeight800Bit,
-        FontWeight900Mask = 1 << FontWeight900Bit,
-        FontWeightMask = FontWeight100Mask | FontWeight200Mask | FontWeight300Mask | FontWeight400Mask | FontWeight500Mask | FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask
-    };
+    FontWeight100Mask = 1 << FontWeight100Bit,
+    FontWeight200Mask = 1 << FontWeight200Bit,
+    FontWeight300Mask = 1 << FontWeight300Bit,
+    FontWeight400Mask = 1 << FontWeight400Bit,
+    FontWeight500Mask = 1 << FontWeight500Bit,
+    FontWeight600Mask = 1 << FontWeight600Bit,
+    FontWeight700Mask = 1 << FontWeight700Bit,
+    FontWeight800Mask = 1 << FontWeight800Bit,
+    FontWeight900Mask = 1 << FontWeight900Bit,
+    FontWeightMask = FontWeight100Mask | FontWeight200Mask | FontWeight300Mask | FontWeight400Mask | FontWeight500Mask | FontWeight600Mask | FontWeight700Mask | FontWeight800Mask | FontWeight900Mask
+};
 
 } // namespace WebCore
 #endif // FontTraitsMask_h
diff --git a/Source/core/platform/graphics/GeneratorGeneratedImage.cpp b/Source/core/platform/graphics/GeneratorGeneratedImage.cpp
index 9ec0606..7b0e934 100644
--- a/Source/core/platform/graphics/GeneratorGeneratedImage.cpp
+++ b/Source/core/platform/graphics/GeneratorGeneratedImage.cpp
@@ -32,10 +32,10 @@
 
 namespace WebCore {
 
-void GeneratorGeneratedImage::draw(GraphicsContext* destContext, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator compositeOp, BlendMode)
+void GeneratorGeneratedImage::draw(GraphicsContext* destContext, const FloatRect& destRect, const FloatRect& srcRect, CompositeOperator compositeOp, BlendMode blendMode)
 {
     GraphicsContextStateSaver stateSaver(*destContext);
-    destContext->setCompositeOperation(compositeOp);
+    destContext->setCompositeOperation(compositeOp, blendMode);
     destContext->clip(destRect);
     destContext->translate(destRect.x(), destRect.y());
     if (destRect.size() != srcRect.size())
diff --git a/Source/core/platform/graphics/GraphicsContext.cpp b/Source/core/platform/graphics/GraphicsContext.cpp
index 3170e00..63ca4a9 100644
--- a/Source/core/platform/graphics/GraphicsContext.cpp
+++ b/Source/core/platform/graphics/GraphicsContext.cpp
@@ -38,8 +38,11 @@
 #include "third_party/skia/include/core/SkAnnotation.h"
 #include "third_party/skia/include/core/SkColorFilter.h"
 #include "third_party/skia/include/core/SkData.h"
+#include "third_party/skia/include/core/SkDevice.h"
+#include "third_party/skia/include/core/SkRRect.h"
 #include "third_party/skia/include/core/SkRefCnt.h"
 #include "third_party/skia/include/effects/SkBlurMaskFilter.h"
+#include "third_party/skia/include/effects/SkCornerPathEffect.h"
 #include "weborigin/KURL.h"
 #include "wtf/Assertions.h"
 #include "wtf/MathExtras.h"
@@ -86,6 +89,17 @@
     ASSERT(!m_transparencyCount);
 }
 
+const SkBitmap* GraphicsContext::bitmap() const
+{
+    TRACE_EVENT0("skia", "GraphicsContext::bitmap");
+    return &m_canvas->getDevice()->accessBitmap(false);
+}
+
+const SkBitmap& GraphicsContext::layerBitmap(AccessMode access) const
+{
+    return m_canvas->getTopDevice()->accessBitmap(access == ReadWrite);
+}
+
 SkDevice* GraphicsContext::createCompatibleDevice(const IntSize& size, bool hasAlpha) const
 {
     if (paintingDisabled())
@@ -256,7 +270,9 @@
     m_state->m_fillPattern.clear();
 }
 
-void GraphicsContext::setShadow(const FloatSize& offset, float blur, const Color& color, DrawLooper::ShadowAlphaMode shadowAlphaMode)
+void GraphicsContext::setShadow(const FloatSize& offset, float blur, const Color& color,
+    DrawLooper::ShadowTransformMode shadowTransformMode,
+    DrawLooper::ShadowAlphaMode shadowAlphaMode)
 {
     if (paintingDisabled())
         return;
@@ -266,12 +282,6 @@
         return;
     }
 
-    DrawLooper::ShadowTransformMode shadowTransformMode;
-    if (m_state->m_shadowsIgnoreTransforms)
-        shadowTransformMode = DrawLooper::ShadowIgnoresTransforms;
-    else
-        shadowTransformMode = DrawLooper::ShadowRespectsTransforms;
-
     DrawLooper drawLooper;
     drawLooper.addShadow(offset, blur, color, shadowTransformMode, shadowAlphaMode);
     drawLooper.addUnmodifiedContent();
@@ -347,7 +357,7 @@
     // rendered text cannot be composited correctly when the layer is
     // collapsed. Therefore, subpixel text is disabled when we are drawing
     // onto a layer.
-    if (paintingDisabled() || isDrawingToLayer())
+    if (paintingDisabled() || isDrawingToLayer() || !isCertainlyOpaque())
         return false;
 
     return shouldSmoothFonts();
@@ -423,7 +433,7 @@
 #endif
 }
 
-void GraphicsContext::beginLayerClippedToImage(const FloatRect& rect, const ImageBuffer* imageBuffer)
+void GraphicsContext::clipToImageBuffer(const ImageBuffer* imageBuffer, const FloatRect& rect)
 {
     if (paintingDisabled())
         return;
@@ -528,9 +538,21 @@
     }
 }
 
-void GraphicsContext::drawFocusRing(const Path& path, int width, int offset, const Color& color)
+void GraphicsContext::drawFocusRing(const Path& focusRingPath, int width, int offset, const Color& color)
 {
-    // FIXME: implement
+    // FIXME: Implement support for offset.
+    UNUSED_PARAM(offset);
+
+    if (paintingDisabled())
+        return;
+
+    SkPaint paint;
+    paint.setAntiAlias(true);
+    paint.setStyle(SkPaint::kStroke_Style);
+    paint.setColor(color.rgb());
+
+    drawOuterPath(focusRingPath.skPath(), paint, width);
+    drawInnerPath(focusRingPath.skPath(), paint, width);
 }
 
 void GraphicsContext::drawFocusRing(const Vector<IntRect>& rects, int width, int offset, const Color& color)
@@ -561,6 +583,70 @@
     drawInnerPath(path, paint, width);
 }
 
+static inline IntRect areaCastingShadowInHole(const IntRect& holeRect, int shadowBlur, int shadowSpread, const IntSize& shadowOffset)
+{
+    IntRect bounds(holeRect);
+
+    bounds.inflate(shadowBlur);
+
+    if (shadowSpread < 0)
+        bounds.inflate(-shadowSpread);
+
+    IntRect offsetBounds = bounds;
+    offsetBounds.move(-shadowOffset);
+    return unionRect(bounds, offsetBounds);
+}
+
+void GraphicsContext::drawInnerShadow(const RoundedRect& rect, const Color& shadowColor, const IntSize shadowOffset, int shadowBlur, int shadowSpread, Edges clippedEdges)
+{
+    IntRect holeRect(rect.rect());
+    holeRect.inflate(-shadowSpread);
+
+    if (holeRect.isEmpty()) {
+        if (rect.isRounded())
+            fillRoundedRect(rect, shadowColor);
+        else
+            fillRect(rect.rect(), shadowColor);
+        return;
+    }
+
+    if (clippedEdges & LeftEdge) {
+        holeRect.move(-max(shadowOffset.width(), 0) - shadowBlur, 0);
+        holeRect.setWidth(holeRect.width() + max(shadowOffset.width(), 0) + shadowBlur);
+    }
+    if (clippedEdges & TopEdge) {
+        holeRect.move(0, -max(shadowOffset.height(), 0) - shadowBlur);
+        holeRect.setHeight(holeRect.height() + max(shadowOffset.height(), 0) + shadowBlur);
+    }
+    if (clippedEdges & RightEdge)
+        holeRect.setWidth(holeRect.width() - min(shadowOffset.width(), 0) + shadowBlur);
+    if (clippedEdges & BottomEdge)
+        holeRect.setHeight(holeRect.height() - min(shadowOffset.height(), 0) + shadowBlur);
+
+    Color fillColor(shadowColor.red(), shadowColor.green(), shadowColor.blue(), 255);
+
+    IntRect outerRect = areaCastingShadowInHole(rect.rect(), shadowBlur, shadowSpread, shadowOffset);
+    RoundedRect roundedHole(holeRect, rect.radii());
+
+    save();
+    if (rect.isRounded()) {
+        Path path;
+        path.addRoundedRect(rect);
+        clipPath(path);
+        roundedHole.shrinkRadii(shadowSpread);
+    } else {
+        clip(rect.rect());
+    }
+
+    DrawLooper drawLooper;
+    drawLooper.addShadow(shadowOffset, shadowBlur, shadowColor,
+        DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
+    setDrawLooper(drawLooper);
+    fillRectWithRoundedHole(outerRect, roundedHole, fillColor);
+    restore();
+    clearDrawLooper();
+}
+
 // This is only used to draw borders.
 void GraphicsContext::drawLine(const IntPoint& point1, const IntPoint& point2)
 {
@@ -1328,11 +1414,6 @@
     clipPath(path, antialiased ? AntiAliased : NotAntiAliased);
 }
 
-void GraphicsContext::clipToImageBuffer(ImageBuffer* buffer, const FloatRect& rect)
-{
-    buffer->clip(this, rect);
-}
-
 void GraphicsContext::clipOutRoundedRect(const RoundedRect& rect)
 {
     if (paintingDisabled())
diff --git a/Source/core/platform/graphics/GraphicsContext.h b/Source/core/platform/graphics/GraphicsContext.h
index 8ae8bf8..11d16d2 100644
--- a/Source/core/platform/graphics/GraphicsContext.h
+++ b/Source/core/platform/graphics/GraphicsContext.h
@@ -39,17 +39,16 @@
 #include "core/platform/graphics/ImageOrientation.h"
 #include "core/platform/graphics/skia/OpaqueRegionSkia.h"
 
-#include "third_party/skia/include/core/SkBitmap.h"
-#include "third_party/skia/include/core/SkDevice.h"
-#include "third_party/skia/include/core/SkPaint.h"
-#include "third_party/skia/include/core/SkPath.h"
-#include "third_party/skia/include/core/SkRect.h"
-#include "third_party/skia/include/core/SkRRect.h"
-#include "third_party/skia/include/effects/SkCornerPathEffect.h"
-
 #include <wtf/Noncopyable.h>
 #include <wtf/PassOwnPtr.h>
 
+class SkBitmap;
+class SkDevice;
+class SkPaint;
+class SkPath;
+class SkRRect;
+struct SkRect;
+
 namespace WebCore {
 
 class ImageBuffer;
@@ -83,16 +82,8 @@
     const SkCanvas* canvas() const { return m_canvas; }
     bool paintingDisabled() const { return !m_canvas; }
 
-    const SkBitmap* bitmap() const
-    {
-        TRACE_EVENT0("skia", "GraphicsContext::bitmap");
-        return &m_canvas->getDevice()->accessBitmap(false);
-    }
-
-    const SkBitmap& layerBitmap(AccessMode access = ReadOnly) const
-    {
-        return m_canvas->getTopDevice()->accessBitmap(access == ReadWrite);
-    }
+    const SkBitmap* bitmap() const;
+    const SkBitmap& layerBitmap(AccessMode = ReadOnly) const;
 
     SkDevice* createCompatibleDevice(const IntSize&, bool hasAlpha) const;
 
@@ -145,9 +136,6 @@
     const SkMatrix& getTotalMatrix() const;
     bool isPrintingDevice() const;
 
-    void setShadowsIgnoreTransforms(bool ignoreTransforms) { m_state->m_shadowsIgnoreTransforms = ignoreTransforms; }
-    bool shadowsIgnoreTransforms() const { return m_state->m_shadowsIgnoreTransforms; }
-
     void setShouldAntialias(bool antialias) { m_state->m_shouldAntialias = antialias; }
     bool shouldAntialias() const { return m_state->m_shouldAntialias; }
 
@@ -239,7 +227,6 @@
     void fillRect(const FloatRect&, const Color&, CompositeOperator);
     void fillRoundedRect(const IntRect&, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight, const Color&);
     void fillRoundedRect(const RoundedRect&, const Color&);
-    void fillRectWithRoundedHole(const IntRect&, const RoundedRect& roundedHoleRect, const Color&);
 
     void clearRect(const FloatRect&);
 
@@ -289,7 +276,7 @@
     void clipOutRoundedRect(const RoundedRect&);
     void clipPath(const Path&, WindRule = RULE_EVENODD);
     void clipConvexPolygon(size_t numPoints, const FloatPoint*, bool antialias = true);
-    void clipToImageBuffer(ImageBuffer*, const FloatRect&);
+    void clipToImageBuffer(const ImageBuffer*, const FloatRect&);
     bool clipRect(const SkRect&, AntiAliasingMode = NotAntiAliased, SkRegion::Op = SkRegion::kIntersect_Op);
 
     void drawText(const Font&, const TextRunPaintInfo&, const FloatPoint&);
@@ -306,13 +293,10 @@
 
     void beginTransparencyLayer(float opacity);
     void endTransparencyLayer();
-    // Begins a layer that is clipped to the image |imageBuffer| at the location
-    // |rect|. This layer is implicitly restored when the next restore is invoked.
-    // NOTE: |imageBuffer| may be deleted before the |restore| is invoked.
-    void beginLayerClippedToImage(const FloatRect&, const ImageBuffer*);
 
     bool hasShadow() const;
     void setShadow(const FloatSize& offset, float blur, const Color&,
+        DrawLooper::ShadowTransformMode = DrawLooper::ShadowRespectsTransforms,
         DrawLooper::ShadowAlphaMode = DrawLooper::ShadowRespectsAlpha);
     void clearShadow() { clearDrawLooper(); }
 
@@ -324,6 +308,16 @@
     void drawFocusRing(const Vector<IntRect>&, int width, int offset, const Color&);
     void drawFocusRing(const Path&, int width, int offset, const Color&);
 
+    enum Edge {
+        NoEdge = 0,
+        TopEdge = 1 << 1,
+        RightEdge = 1 << 2,
+        BottomEdge = 1 << 3,
+        LeftEdge = 1 << 4
+    };
+    typedef unsigned Edges;
+    void drawInnerShadow(const RoundedRect&, const Color& shadowColor, const IntSize shadowOffset, int shadowBlur, int shadowSpread, Edges clippedEdges = NoEdge);
+
     // This clip function is used only by <canvas> code. It allows
     // implementations to handle clipping on the canvas differently since
     // the discipline is different.
@@ -433,6 +427,8 @@
 
     void didDrawTextInRect(const SkRect& textRect);
 
+    void fillRectWithRoundedHole(const IntRect&, const RoundedRect& roundedHoleRect, const Color&);
+
     // null indicates painting is disabled. Never delete this object.
     SkCanvas* m_canvas;
 
diff --git a/Source/core/platform/graphics/GraphicsContextAnnotation.h b/Source/core/platform/graphics/GraphicsContextAnnotation.h
index fefcfe2..22684b5 100644
--- a/Source/core/platform/graphics/GraphicsContextAnnotation.h
+++ b/Source/core/platform/graphics/GraphicsContextAnnotation.h
@@ -34,14 +34,10 @@
 #ifndef GraphicsContextAnnotation_h
 #define GraphicsContextAnnotation_h
 
-#if ENABLE(GRAPHICS_CONTEXT_ANNOTATIONS)
 #define ANNOTATE_GRAPHICS_CONTEXT(paintInfo, renderer) \
     GraphicsContextAnnotator scopedGraphicsContextAnnotator; \
     if (UNLIKELY(paintInfo.context->annotationMode())) \
         scopedGraphicsContextAnnotator.annotate(paintInfo, renderer)
-#else
-#define ANNOTATE_GRAPHICS_CONTEXT(paint, renderer) do { } while (0)
-#endif
 
 namespace WebCore {
 
diff --git a/Source/core/platform/graphics/GraphicsContextState.h b/Source/core/platform/graphics/GraphicsContextState.h
index 59396b8..37b5e70 100644
--- a/Source/core/platform/graphics/GraphicsContextState.h
+++ b/Source/core/platform/graphics/GraphicsContextState.h
@@ -72,7 +72,6 @@
 #endif
         , m_shouldAntialias(true)
         , m_shouldSmoothFonts(true)
-        , m_shadowsIgnoreTransforms(false)
     {
     }
 
@@ -93,7 +92,6 @@
         , m_interpolationQuality(other.m_interpolationQuality)
         , m_shouldAntialias(other.m_shouldAntialias)
         , m_shouldSmoothFonts(other.m_shouldSmoothFonts)
-        , m_shadowsIgnoreTransforms(other.m_shadowsIgnoreTransforms)
     {
         // Up the ref count of these. SkSafeRef does nothing if its argument is 0.
         SkSafeRef(m_looper);
@@ -157,7 +155,6 @@
 
     bool m_shouldAntialias : 1;
     bool m_shouldSmoothFonts : 1;
-    bool m_shadowsIgnoreTransforms : 1;
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/GraphicsLayer.cpp b/Source/core/platform/graphics/GraphicsLayer.cpp
index dc61fd0..f7ecd98 100644
--- a/Source/core/platform/graphics/GraphicsLayer.cpp
+++ b/Source/core/platform/graphics/GraphicsLayer.cpp
@@ -56,7 +56,6 @@
 #include "public/platform/Platform.h"
 #include "public/platform/WebAnimation.h"
 #include "public/platform/WebCompositorSupport.h"
-#include "public/platform/WebFilterOperation.h"
 #include "public/platform/WebFilterOperations.h"
 #include "public/platform/WebFloatPoint.h"
 #include "public/platform/WebFloatRect.h"
@@ -70,7 +69,6 @@
 
 using WebKit::Platform;
 using WebKit::WebAnimation;
-using WebKit::WebFilterOperation;
 using WebKit::WebFilterOperations;
 using WebKit::WebLayer;
 using WebKit::WebPoint;
@@ -1230,16 +1228,16 @@
             float amount = static_cast<const BasicColorMatrixFilterOperation*>(&op)->amount();
             switch (op.getOperationType()) {
             case FilterOperation::GRAYSCALE:
-                webFilters.append(WebFilterOperation::createGrayscaleFilter(amount));
+                webFilters.appendGrayscaleFilter(amount);
                 break;
             case FilterOperation::SEPIA:
-                webFilters.append(WebFilterOperation::createSepiaFilter(amount));
+                webFilters.appendSepiaFilter(amount);
                 break;
             case FilterOperation::SATURATE:
-                webFilters.append(WebFilterOperation::createSaturateFilter(amount));
+                webFilters.appendSaturateFilter(amount);
                 break;
             case FilterOperation::HUE_ROTATE:
-                webFilters.append(WebFilterOperation::createHueRotateFilter(amount));
+                webFilters.appendHueRotateFilter(amount);
                 break;
             default:
                 ASSERT_NOT_REACHED();
@@ -1253,16 +1251,16 @@
             float amount = static_cast<const BasicComponentTransferFilterOperation*>(&op)->amount();
             switch (op.getOperationType()) {
             case FilterOperation::INVERT:
-                webFilters.append(WebFilterOperation::createInvertFilter(amount));
+                webFilters.appendInvertFilter(amount);
                 break;
             case FilterOperation::OPACITY:
-                webFilters.append(WebFilterOperation::createOpacityFilter(amount));
+                webFilters.appendOpacityFilter(amount);
                 break;
             case FilterOperation::BRIGHTNESS:
-                webFilters.append(WebFilterOperation::createBrightnessFilter(amount));
+                webFilters.appendBrightnessFilter(amount);
                 break;
             case FilterOperation::CONTRAST:
-                webFilters.append(WebFilterOperation::createContrastFilter(amount));
+                webFilters.appendContrastFilter(amount);
                 break;
             default:
                 ASSERT_NOT_REACHED();
@@ -1271,12 +1269,12 @@
         }
         case FilterOperation::BLUR: {
             float pixelRadius = static_cast<const BlurFilterOperation*>(&op)->stdDeviation().getFloatValue();
-            webFilters.append(WebFilterOperation::createBlurFilter(pixelRadius));
+            webFilters.appendBlurFilter(pixelRadius);
             break;
         }
         case FilterOperation::DROP_SHADOW: {
             const DropShadowFilterOperation& dropShadowOp = *static_cast<const DropShadowFilterOperation*>(&op);
-            webFilters.append(WebFilterOperation::createDropShadowFilter(WebPoint(dropShadowOp.x(), dropShadowOp.y()), dropShadowOp.stdDeviation(), dropShadowOp.color().rgb()));
+            webFilters.appendDropShadowFilter(WebPoint(dropShadowOp.x(), dropShadowOp.y()), dropShadowOp.stdDeviation(), dropShadowOp.color().rgb());
             break;
         }
         case FilterOperation::CUSTOM:
@@ -1308,15 +1306,16 @@
         SkAutoTUnref<SkImageFilter> imageFilter(builder.build(filters));
         m_layer->layer()->setFilter(imageFilter);
     } else {
-        WebFilterOperations webFilters;
-        if (!copyWebCoreFilterOperationsToWebFilterOperations(filters, webFilters)) {
+        OwnPtr<WebFilterOperations> webFilters = adoptPtr(Platform::current()->compositorSupport()->createFilterOperations());
+        if (!copyWebCoreFilterOperationsToWebFilterOperations(filters, *webFilters)) {
             // Make sure the filters are removed from the platform layer, as they are
             // going to fallback to software mode.
-            m_layer->layer()->setFilters(WebFilterOperations());
+            webFilters->clear();
+            m_layer->layer()->setFilters(*webFilters);
             m_filters = FilterOperations();
             return false;
         }
-        m_layer->layer()->setFilters(webFilters);
+        m_layer->layer()->setFilters(*webFilters);
     }
 
     m_filters = filters;
@@ -1325,10 +1324,10 @@
 
 void GraphicsLayer::setBackgroundFilters(const FilterOperations& filters)
 {
-    WebFilterOperations webFilters;
-    if (!copyWebCoreFilterOperationsToWebFilterOperations(filters, webFilters))
+    OwnPtr<WebFilterOperations> webFilters = adoptPtr(Platform::current()->compositorSupport()->createFilterOperations());
+    if (!copyWebCoreFilterOperationsToWebFilterOperations(filters, *webFilters))
         return;
-    m_layer->layer()->setBackgroundFilters(webFilters);
+    m_layer->layer()->setBackgroundFilters(*webFilters);
 }
 
 void GraphicsLayer::setLinkHighlight(LinkHighlightClient* linkHighlight)
diff --git a/Source/core/platform/graphics/Image.h b/Source/core/platform/graphics/Image.h
index b208444..ec42980 100644
--- a/Source/core/platform/graphics/Image.h
+++ b/Source/core/platform/graphics/Image.h
@@ -31,7 +31,7 @@
 #include "core/platform/graphics/GraphicsTypes.h"
 #include "core/platform/graphics/ImageOrientation.h"
 #include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/NativeImagePtr.h"
+#include "core/platform/graphics/skia/NativeImageSkia.h"
 #include "third_party/skia/include/core/SkXfermode.h"
 #include <wtf/PassRefPtr.h>
 #include <wtf/RefCounted.h>
@@ -109,7 +109,7 @@
 
     enum TileRule { StretchTile, RoundTile, SpaceTile, RepeatTile };
 
-    virtual PassNativeImagePtr nativeImageForCurrentFrame() { return 0; }
+    virtual PassRefPtr<NativeImageSkia> nativeImageForCurrentFrame() { return 0; }
 
     virtual void drawPattern(GraphicsContext*, const FloatRect&,
         const FloatSize&, const FloatPoint& phase, CompositeOperator,
diff --git a/Source/core/platform/graphics/ImageBuffer.cpp b/Source/core/platform/graphics/ImageBuffer.cpp
index 80e40bd..0ceb1dc 100644
--- a/Source/core/platform/graphics/ImageBuffer.cpp
+++ b/Source/core/platform/graphics/ImageBuffer.cpp
@@ -1,25 +1,31 @@
 /*
+ * Copyright (c) 2008, Google Inc. All rights reserved.
  * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) Research In Motion Limited 2011. All rights reserved.
+ * Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
+ * modification, are permitted provided that the following conditions are
+ * met:
  *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
@@ -27,12 +33,268 @@
 #include "config.h"
 #include "core/platform/graphics/ImageBuffer.h"
 
+#include "core/html/ImageData.h"
+#include "core/platform/MIMETypeRegistry.h"
 #include "core/platform/PlatformMemoryInstrumentation.h"
+#include "core/platform/graphics/BitmapImage.h"
+#include "core/platform/graphics/Extensions3D.h"
+#include "core/platform/graphics/GraphicsContext.h"
+#include "core/platform/graphics/GraphicsContext3D.h"
 #include "core/platform/graphics/IntRect.h"
-#include <wtf/MathExtras.h>
+#include "core/platform/graphics/chromium/Canvas2DLayerBridge.h"
+#include "core/platform/graphics/gpu/SharedGraphicsContext3D.h"
+#include "core/platform/graphics/skia/MemoryInstrumentationSkia.h"
+#include "core/platform/graphics/skia/NativeImageSkia.h"
+#include "core/platform/graphics/skia/SkiaUtils.h"
+#include "core/platform/image-encoders/skia/JPEGImageEncoder.h"
+#include "core/platform/image-encoders/skia/PNGImageEncoder.h"
+#include "core/platform/image-encoders/skia/WEBPImageEncoder.h"
+#include "public/platform/Platform.h"
+#include "skia/ext/platform_canvas.h"
+#include "third_party/skia/include/core/SkColorPriv.h"
+#include "third_party/skia/include/core/SkSurface.h"
+#include "third_party/skia/include/gpu/GrContext.h"
+#include "third_party/skia/include/gpu/SkGpuDevice.h"
+#include "wtf/MathExtras.h"
+#include "wtf/text/Base64.h"
+#include "wtf/text/WTFString.h"
+
+using namespace std;
 
 namespace WebCore {
 
+static SkCanvas* createAcceleratedCanvas(const IntSize& size, OwnPtr<Canvas2DLayerBridge>* outLayerBridge, OpacityMode opacityMode)
+{
+    RefPtr<GraphicsContext3D> context3D = SharedGraphicsContext3D::get();
+    if (!context3D)
+        return 0;
+    GrContext* gr = context3D->grContext();
+    if (!gr)
+        return 0;
+    gr->resetContext();
+    Canvas2DLayerBridge::OpacityMode bridgeOpacityMode = opacityMode == Opaque ? Canvas2DLayerBridge::Opaque : Canvas2DLayerBridge::NonOpaque;
+    Canvas2DLayerBridge::ThreadMode threadMode = WebKit::Platform::current()->isThreadedCompositingEnabled() ? Canvas2DLayerBridge::Threaded : Canvas2DLayerBridge::SingleThread;
+    SkImage::Info info;
+    info.fWidth = size.width();
+    info.fHeight = size.height();
+    info.fColorType = SkImage::kPMColor_ColorType;
+    info.fAlphaType = SkImage::kPremul_AlphaType;
+    SkAutoTUnref<SkSurface> surface(SkSurface::NewRenderTarget(context3D->grContext(), info));
+    if (!surface.get())
+        return 0;
+    SkDeferredCanvas* canvas = new SkDeferredCanvas(surface.get());
+    *outLayerBridge = Canvas2DLayerBridge::create(context3D.release(), canvas, bridgeOpacityMode, threadMode);
+    // If canvas buffer allocation failed, debug build will have asserted
+    // For release builds, we must verify whether the device has a render target
+    return canvas;
+}
+
+static SkCanvas* createNonPlatformCanvas(const IntSize& size)
+{
+    SkAutoTUnref<SkDevice> device(new SkDevice(SkBitmap::kARGB_8888_Config, size.width(), size.height()));
+    SkPixelRef* pixelRef = device->accessBitmap(false).pixelRef();
+    return pixelRef ? new SkCanvas(device) : 0;
+}
+
+PassOwnPtr<ImageBuffer> ImageBuffer::createCompatibleBuffer(const IntSize& size, float resolutionScale, const GraphicsContext* context, bool hasAlpha)
+{
+    bool success = false;
+    OwnPtr<ImageBuffer> buf = adoptPtr(new ImageBuffer(size, resolutionScale, context, hasAlpha, success));
+    if (!success)
+        return nullptr;
+    return buf.release();
+}
+
+ImageBuffer::ImageBuffer(const IntSize& size, float resolutionScale, const GraphicsContext* compatibleContext, bool hasAlpha, bool& success)
+    : m_size(size)
+    , m_logicalSize(size)
+    , m_resolutionScale(resolutionScale)
+{
+    if (!compatibleContext) {
+        success = false;
+        return;
+    }
+
+    SkAutoTUnref<SkDevice> device(compatibleContext->createCompatibleDevice(size, hasAlpha));
+    if (!device.get()) {
+        success = false;
+        return;
+    }
+
+    SkPixelRef* pixelRef = device->accessBitmap(false).pixelRef();
+    if (!pixelRef) {
+        success = false;
+        return;
+    }
+
+    m_canvas = adoptPtr(new SkCanvas(device));
+    m_context = adoptPtr(new GraphicsContext(m_canvas.get()));
+    m_context->setCertainlyOpaque(!hasAlpha);
+    m_context->scale(FloatSize(m_resolutionScale, m_resolutionScale));
+
+    success = true;
+}
+
+ImageBuffer::ImageBuffer(const IntSize& size, float resolutionScale, RenderingMode renderingMode, OpacityMode opacityMode, bool& success)
+    : m_size(size)
+    , m_logicalSize(size)
+    , m_resolutionScale(resolutionScale)
+{
+    if (renderingMode == Accelerated)
+        m_canvas = adoptPtr(createAcceleratedCanvas(size, &m_layerBridge, opacityMode));
+    else if (renderingMode == UnacceleratedNonPlatformBuffer)
+        m_canvas = adoptPtr(createNonPlatformCanvas(size));
+
+    if (!m_canvas)
+        m_canvas = adoptPtr(skia::TryCreateBitmapCanvas(size.width(), size.height(), false));
+
+    if (!m_canvas) {
+        success = false;
+        return;
+    }
+
+    m_context = adoptPtr(new GraphicsContext(m_canvas.get()));
+    m_context->setCertainlyOpaque(opacityMode == Opaque);
+    m_context->setAccelerated(renderingMode == Accelerated);
+    m_context->scale(FloatSize(m_resolutionScale, m_resolutionScale));
+
+    // Clear the background transparent or opaque, as required. It would be nice if this wasn't
+    // required, but the canvas is currently filled with the magic transparency
+    // color. Can we have another way to manage this?
+    if (opacityMode == Opaque)
+        m_canvas->drawARGB(255, 0, 0, 0, SkXfermode::kSrc_Mode);
+    else
+        m_canvas->drawARGB(0, 0, 0, 0, SkXfermode::kClear_Mode);
+
+    success = true;
+}
+
+ImageBuffer::~ImageBuffer()
+{
+}
+
+GraphicsContext* ImageBuffer::context() const
+{
+    if (m_layerBridge) {
+        // We're using context acquisition as a signal that someone is about to render into our buffer and we need
+        // to be ready. This isn't logically const-correct, hence the cast.
+        const_cast<Canvas2DLayerBridge*>(m_layerBridge.get())->contextAcquired();
+    }
+    return m_context.get();
+}
+
+static SkBitmap deepSkBitmapCopy(const SkBitmap& bitmap)
+{
+    SkBitmap tmp;
+    if (!bitmap.deepCopyTo(&tmp, bitmap.config()))
+        bitmap.copyTo(&tmp, bitmap.config());
+
+    return tmp;
+}
+
+PassRefPtr<Image> ImageBuffer::copyImage(BackingStoreCopy copyBehavior, ScaleBehavior) const
+{
+    const SkBitmap& bitmap = *context()->bitmap();
+    // FIXME: Start honoring ScaleBehavior to scale 2x buffers down to 1x.
+    return BitmapImage::create(NativeImageSkia::create(copyBehavior == CopyBackingStore ? deepSkBitmapCopy(bitmap) : bitmap, m_resolutionScale));
+}
+
+BackingStoreCopy ImageBuffer::fastCopyImageMode()
+{
+    return DontCopyBackingStore;
+}
+
+WebKit::WebLayer* ImageBuffer::platformLayer() const
+{
+    return m_layerBridge ? m_layerBridge->layer() : 0;
+}
+
+bool ImageBuffer::copyToPlatformTexture(GraphicsContext3D& context, Platform3DObject texture, GC3Denum internalFormat, GC3Denum destType, GC3Dint level, bool premultiplyAlpha, bool flipY)
+{
+    if (!m_layerBridge || !platformLayer())
+        return false;
+
+    Platform3DObject sourceTexture = m_layerBridge->backBufferTexture();
+
+    if (!context.makeContextCurrent())
+        return false;
+
+    Extensions3D* extensions = context.getExtensions();
+    if (!extensions->supports("GL_CHROMIUM_copy_texture") || !extensions->supports("GL_CHROMIUM_flipy")
+        || !extensions->canUseCopyTextureCHROMIUM(internalFormat, destType, level))
+        return false;
+
+    // The canvas is stored in a premultiplied format, so unpremultiply if necessary.
+    context.pixelStorei(Extensions3D::UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM, !premultiplyAlpha);
+
+    // The canvas is stored in an inverted position, so the flip semantics are reversed.
+    context.pixelStorei(Extensions3D::UNPACK_FLIP_Y_CHROMIUM, !flipY);
+
+    extensions->copyTextureCHROMIUM(GraphicsContext3D::TEXTURE_2D, sourceTexture, texture, level, internalFormat, destType);
+
+    context.pixelStorei(Extensions3D::UNPACK_FLIP_Y_CHROMIUM, false);
+    context.pixelStorei(Extensions3D::UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM, false);
+    context.flush();
+    return true;
+}
+
+static bool drawNeedsCopy(GraphicsContext* src, GraphicsContext* dst)
+{
+    return (src == dst);
+}
+
+void ImageBuffer::draw(GraphicsContext* context, const FloatRect& destRect, const FloatRect& srcRect,
+    CompositeOperator op, BlendMode blendMode, bool useLowQualityScale)
+{
+    const SkBitmap& bitmap = *m_context->bitmap();
+    RefPtr<Image> image = BitmapImage::create(NativeImageSkia::create(drawNeedsCopy(m_context.get(), context) ? deepSkBitmapCopy(bitmap) : bitmap));
+    context->drawImage(image.get(), destRect, srcRect, op, blendMode, DoNotRespectImageOrientation, useLowQualityScale);
+}
+
+void ImageBuffer::drawPattern(GraphicsContext* context, const FloatRect& srcRect, const FloatSize& scale,
+    const FloatPoint& phase, CompositeOperator op, const FloatRect& destRect)
+{
+    const SkBitmap& bitmap = *m_context->bitmap();
+    RefPtr<Image> image = BitmapImage::create(NativeImageSkia::create(drawNeedsCopy(m_context.get(), context) ? deepSkBitmapCopy(bitmap) : bitmap));
+    image->drawPattern(context, srcRect, scale, phase, op, destRect);
+}
+
+void ImageBuffer::transformColorSpace(ColorSpace srcColorSpace, ColorSpace dstColorSpace)
+{
+    if (srcColorSpace == dstColorSpace)
+        return;
+
+    // only sRGB <-> linearRGB are supported at the moment
+    if ((srcColorSpace != ColorSpaceLinearRGB && srcColorSpace != ColorSpaceDeviceRGB)
+        || (dstColorSpace != ColorSpaceLinearRGB && dstColorSpace != ColorSpaceDeviceRGB))
+        return;
+
+    // FIXME: Disable color space conversions on accelerated canvases (for now).
+    if (context()->isAccelerated())
+        return;
+
+    const SkBitmap& bitmap = *context()->bitmap();
+    if (bitmap.isNull())
+        return;
+
+    const Vector<uint8_t>& lookUpTable = dstColorSpace == ColorSpaceLinearRGB ?
+        getLinearRgbLUT() : getDeviceRgbLUT();
+
+    ASSERT(bitmap.config() == SkBitmap::kARGB_8888_Config);
+    SkAutoLockPixels bitmapLock(bitmap);
+    for (int y = 0; y < m_size.height(); ++y) {
+        uint32_t* srcRow = bitmap.getAddr32(0, y);
+        for (int x = 0; x < m_size.width(); ++x) {
+            SkColor color = SkPMColorToColor(srcRow[x]);
+            srcRow[x] = SkPreMultiplyARGB(
+                SkColorGetA(color),
+                lookUpTable[SkColorGetR(color)],
+                lookUpTable[SkColorGetG(color)],
+                lookUpTable[SkColorGetB(color)]);
+        }
+    }
+}
+
 const Vector<uint8_t>& ImageBuffer::getLinearRgbLUT()
 {
     DEFINE_STATIC_LOCAL(Vector<uint8_t>, linearRgbLUT, ());
@@ -63,28 +325,96 @@
     return deviceRgbLUT;
 }
 
-void ImageBuffer::transformColorSpace(ColorSpace srcColorSpace, ColorSpace dstColorSpace)
+
+template <Multiply multiplied>
+PassRefPtr<Uint8ClampedArray> getImageData(const IntRect& rect, GraphicsContext* context, const IntSize& size)
 {
-    if (srcColorSpace == dstColorSpace)
-        return;
+    float area = 4.0f * rect.width() * rect.height();
+    if (area > static_cast<float>(std::numeric_limits<int>::max()))
+        return 0;
 
-    // only sRGB <-> linearRGB are supported at the moment
-    if ((srcColorSpace != ColorSpaceLinearRGB && srcColorSpace != ColorSpaceDeviceRGB)
-        || (dstColorSpace != ColorSpaceLinearRGB && dstColorSpace != ColorSpaceDeviceRGB))
-        return;
+    RefPtr<Uint8ClampedArray> result = Uint8ClampedArray::createUninitialized(rect.width() * rect.height() * 4);
 
-    if (dstColorSpace == ColorSpaceLinearRGB) {
-        platformTransformColorSpace(getLinearRgbLUT());
-    } else if (dstColorSpace == ColorSpaceDeviceRGB) {
-        platformTransformColorSpace(getDeviceRgbLUT());
-    }
+    unsigned char* data = result->data();
+
+    if (rect.x() < 0
+        || rect.y() < 0
+        || rect.maxX() > size.width()
+        || rect.maxY() > size.height())
+        result->zeroFill();
+
+    unsigned destBytesPerRow = 4 * rect.width();
+    SkBitmap destBitmap;
+    destBitmap.setConfig(SkBitmap::kARGB_8888_Config, rect.width(), rect.height(), destBytesPerRow);
+    destBitmap.setPixels(data);
+
+    SkCanvas::Config8888 config8888;
+    if (multiplied == Premultiplied)
+        config8888 = SkCanvas::kRGBA_Premul_Config8888;
+    else
+        config8888 = SkCanvas::kRGBA_Unpremul_Config8888;
+
+    context->readPixels(&destBitmap, rect.x(), rect.y(), config8888);
+    return result.release();
 }
 
-inline void ImageBuffer::genericConvertToLuminanceMask()
+PassRefPtr<Uint8ClampedArray> ImageBuffer::getUnmultipliedImageData(const IntRect& rect, CoordinateSystem) const
+{
+    return getImageData<Unmultiplied>(rect, context(), m_size);
+}
+
+PassRefPtr<Uint8ClampedArray> ImageBuffer::getPremultipliedImageData(const IntRect& rect, CoordinateSystem) const
+{
+    return getImageData<Premultiplied>(rect, context(), m_size);
+}
+
+void ImageBuffer::putByteArray(Multiply multiplied, Uint8ClampedArray* source, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint, CoordinateSystem)
+{
+    ASSERT(sourceRect.width() > 0);
+    ASSERT(sourceRect.height() > 0);
+
+    int originX = sourceRect.x();
+    int destX = destPoint.x() + sourceRect.x();
+    ASSERT(destX >= 0);
+    ASSERT(destX < m_size.width());
+    ASSERT(originX >= 0);
+    ASSERT(originX < sourceRect.maxX());
+
+    int endX = destPoint.x() + sourceRect.maxX();
+    ASSERT(endX <= m_size.width());
+
+    int numColumns = endX - destX;
+
+    int originY = sourceRect.y();
+    int destY = destPoint.y() + sourceRect.y();
+    ASSERT(destY >= 0);
+    ASSERT(destY < m_size.height());
+    ASSERT(originY >= 0);
+    ASSERT(originY < sourceRect.maxY());
+
+    int endY = destPoint.y() + sourceRect.maxY();
+    ASSERT(endY <= m_size.height());
+    int numRows = endY - destY;
+
+    unsigned srcBytesPerRow = 4 * sourceSize.width();
+    SkBitmap srcBitmap;
+    srcBitmap.setConfig(SkBitmap::kARGB_8888_Config, numColumns, numRows, srcBytesPerRow);
+    srcBitmap.setPixels(source->data() + originY * srcBytesPerRow + originX * 4);
+
+    SkCanvas::Config8888 config8888;
+    if (multiplied == Premultiplied)
+        config8888 = SkCanvas::kRGBA_Premul_Config8888;
+    else
+        config8888 = SkCanvas::kRGBA_Unpremul_Config8888;
+
+    context()->writePixels(srcBitmap, destX, destY, config8888);
+}
+
+void ImageBuffer::convertToLuminanceMask()
 {
     IntRect luminanceRect(IntPoint(), internalSize());
     RefPtr<Uint8ClampedArray> srcPixelArray = getUnmultipliedImageData(luminanceRect);
-    
+
     unsigned pixelArrayLength = srcPixelArray->length();
     for (unsigned pixelOffset = 0; pixelOffset < pixelArrayLength; pixelOffset += 4) {
         unsigned char a = srcPixelArray->item(pixelOffset + 3);
@@ -93,24 +423,73 @@
         unsigned char r = srcPixelArray->item(pixelOffset);
         unsigned char g = srcPixelArray->item(pixelOffset + 1);
         unsigned char b = srcPixelArray->item(pixelOffset + 2);
-        
+
         double luma = (r * 0.2125 + g * 0.7154 + b * 0.0721) * ((double)a / 255.0);
         srcPixelArray->set(pixelOffset + 3, luma);
     }
     putByteArray(Unmultiplied, srcPixelArray.get(), luminanceRect.size(), luminanceRect, IntPoint());
 }
 
-void ImageBuffer::convertToLuminanceMask()
+template <typename T>
+static bool encodeImage(T& source, const String& mimeType, const double* quality, Vector<char>* output)
 {
-    // Add platform specific functions with platformConvertToLuminanceMask here later.
-    genericConvertToLuminanceMask();
+    Vector<unsigned char>* encodedImage = reinterpret_cast<Vector<unsigned char>*>(output);
+
+    if (mimeType == "image/jpeg") {
+        int compressionQuality = JPEGImageEncoder::DefaultCompressionQuality;
+        if (quality && *quality >= 0.0 && *quality <= 1.0)
+            compressionQuality = static_cast<int>(*quality * 100 + 0.5);
+        if (!JPEGImageEncoder::encode(source, compressionQuality, encodedImage))
+            return false;
+    } else if (mimeType == "image/webp") {
+        int compressionQuality = WEBPImageEncoder::DefaultCompressionQuality;
+        if (quality && *quality >= 0.0 && *quality <= 1.0)
+            compressionQuality = static_cast<int>(*quality * 100 + 0.5);
+        if (!WEBPImageEncoder::encode(source, compressionQuality, encodedImage))
+            return false;
+    } else {
+        if (!PNGImageEncoder::encode(source, encodedImage))
+            return false;
+        ASSERT(mimeType == "image/png");
+    }
+
+    return true;
+}
+
+String ImageBuffer::toDataURL(const String& mimeType, const double* quality, CoordinateSystem) const
+{
+    ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
+
+    Vector<char> encodedImage;
+    if (!encodeImage(*context()->bitmap(), mimeType, quality, &encodedImage))
+        return "data:,";
+
+    Vector<char> base64Data;
+    base64Encode(encodedImage, base64Data);
+
+    return "data:" + mimeType + ";base64," + base64Data;
+}
+
+String ImageDataToDataURL(const ImageData& imageData, const String& mimeType, const double* quality)
+{
+    ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
+
+    Vector<char> encodedImage;
+    if (!encodeImage(imageData, mimeType, quality, &encodedImage))
+        return "data:,";
+
+    Vector<char> base64Data;
+    base64Encode(encodedImage, base64Data);
+
+    return "data:" + mimeType + ";base64," + base64Data;
 }
 
 void ImageBuffer::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
 {
     MemoryClassInfo info(memoryObjectInfo, this, PlatformMemoryTypes::Image);
-    info.addMember(m_data, "data");
+    info.addMember(m_canvas, "canvas");
     info.addMember(m_context, "context");
+    info.addMember(m_layerBridge, "layerBridge");
 }
 
-}
+} // namespace WebCore
diff --git a/Source/core/platform/graphics/ImageBuffer.h b/Source/core/platform/graphics/ImageBuffer.h
index 482ea7e..fd96acf 100644
--- a/Source/core/platform/graphics/ImageBuffer.h
+++ b/Source/core/platform/graphics/ImageBuffer.h
@@ -34,130 +34,127 @@
 #include "core/platform/graphics/GraphicsTypes.h"
 #include "core/platform/graphics/GraphicsTypes3D.h"
 #include "core/platform/graphics/IntSize.h"
-#include "core/platform/graphics/chromium/ImageBufferDataSkia.h"
 #include "core/platform/graphics/transforms/AffineTransform.h"
-#include <wtf/Forward.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/Uint8ClampedArray.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/Uint8ClampedArray.h"
+#include "wtf/Vector.h"
+
+class SkCanvas;
 
 namespace WebKit { class WebLayer; }
 
 namespace WebCore {
 
-    class Image;
-    class ImageData;
-    class IntPoint;
-    class IntRect;
-    class GraphicsContext3D;
+class Canvas2DLayerBridge;
+class Image;
+class ImageData;
+class IntPoint;
+class IntRect;
+class GraphicsContext3D;
 
-    enum Multiply {
-        Premultiplied,
-        Unmultiplied
-    };
+enum Multiply {
+    Premultiplied,
+    Unmultiplied
+};
 
-    enum RenderingMode {
-        Unaccelerated,
-        UnacceleratedNonPlatformBuffer, // Use plain memory allocation rather than platform API to allocate backing store.
-        Accelerated
-    };
+enum RenderingMode {
+    Unaccelerated,
+    UnacceleratedNonPlatformBuffer, // Use plain memory allocation rather than platform API to allocate backing store.
+    Accelerated
+};
 
-    enum BackingStoreCopy {
-        CopyBackingStore, // Guarantee subsequent draws don't affect the copy.
-        DontCopyBackingStore // Subsequent draws may affect the copy.
-    };
+enum BackingStoreCopy {
+    CopyBackingStore, // Guarantee subsequent draws don't affect the copy.
+    DontCopyBackingStore // Subsequent draws may affect the copy.
+};
 
-    enum ScaleBehavior {
-        Scaled,
-        Unscaled
-    };
+enum ScaleBehavior {
+    Scaled,
+    Unscaled
+};
 
-    enum OpacityMode {
-        NonOpaque,
-        Opaque,
-    };
+enum OpacityMode {
+    NonOpaque,
+    Opaque,
+};
 
-    class ImageBuffer {
-        WTF_MAKE_NONCOPYABLE(ImageBuffer); WTF_MAKE_FAST_ALLOCATED;
-    public:
-        // Will return a null pointer on allocation failure.
-        static PassOwnPtr<ImageBuffer> create(const IntSize& size, float resolutionScale = 1, RenderingMode renderingMode = Unaccelerated, OpacityMode opacityMode = NonOpaque)
-        {
-            bool success = false;
-            OwnPtr<ImageBuffer> buf = adoptPtr(new ImageBuffer(size, resolutionScale, renderingMode, opacityMode, success));
-            if (!success)
-                return nullptr;
-            return buf.release();
-        }
+class ImageBuffer {
+    WTF_MAKE_NONCOPYABLE(ImageBuffer); WTF_MAKE_FAST_ALLOCATED;
+public:
+    // Will return a null pointer on allocation failure.
+    static PassOwnPtr<ImageBuffer> create(const IntSize& size, float resolutionScale = 1, RenderingMode renderingMode = Unaccelerated, OpacityMode opacityMode = NonOpaque)
+    {
+        bool success = false;
+        OwnPtr<ImageBuffer> buf = adoptPtr(new ImageBuffer(size, resolutionScale, renderingMode, opacityMode, success));
+        if (!success)
+            return nullptr;
+        return buf.release();
+    }
 
-        static PassOwnPtr<ImageBuffer> createCompatibleBuffer(const IntSize&, float resolutionScale, const GraphicsContext*, bool hasAlpha);
+    static PassOwnPtr<ImageBuffer> createCompatibleBuffer(const IntSize&, float resolutionScale, const GraphicsContext*, bool hasAlpha);
 
-        ~ImageBuffer();
+    ~ImageBuffer();
 
-        // The actual resolution of the backing store
-        const IntSize& internalSize() const { return m_size; }
-        const IntSize& logicalSize() const { return m_logicalSize; }
+    // The actual resolution of the backing store
+    const IntSize& internalSize() const { return m_size; }
+    const IntSize& logicalSize() const { return m_logicalSize; }
 
-        GraphicsContext* context() const;
+    GraphicsContext* context() const;
 
-        PassRefPtr<Image> copyImage(BackingStoreCopy = CopyBackingStore, ScaleBehavior = Scaled) const;
-        // Give hints on the faster copyImage Mode, return DontCopyBackingStore if it supports the DontCopyBackingStore behavior
-        // or return CopyBackingStore if it doesn't.  
-        static BackingStoreCopy fastCopyImageMode();
+    PassRefPtr<Image> copyImage(BackingStoreCopy = CopyBackingStore, ScaleBehavior = Scaled) const;
+    // Give hints on the faster copyImage Mode, return DontCopyBackingStore if it supports the DontCopyBackingStore behavior
+    // or return CopyBackingStore if it doesn't.
+    static BackingStoreCopy fastCopyImageMode();
 
-        enum CoordinateSystem { LogicalCoordinateSystem, BackingStoreCoordinateSystem };
+    enum CoordinateSystem { LogicalCoordinateSystem, BackingStoreCoordinateSystem };
 
-        PassRefPtr<Uint8ClampedArray> getUnmultipliedImageData(const IntRect&, CoordinateSystem = LogicalCoordinateSystem) const;
-        PassRefPtr<Uint8ClampedArray> getPremultipliedImageData(const IntRect&, CoordinateSystem = LogicalCoordinateSystem) const;
+    PassRefPtr<Uint8ClampedArray> getUnmultipliedImageData(const IntRect&, CoordinateSystem = LogicalCoordinateSystem) const;
+    PassRefPtr<Uint8ClampedArray> getPremultipliedImageData(const IntRect&, CoordinateSystem = LogicalCoordinateSystem) const;
 
-        void putByteArray(Multiply multiplied, Uint8ClampedArray*, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint, CoordinateSystem = LogicalCoordinateSystem);
-        
-        void convertToLuminanceMask();
-        
-        String toDataURL(const String& mimeType, const double* quality = 0, CoordinateSystem = LogicalCoordinateSystem) const;
-        AffineTransform baseTransform() const { return AffineTransform(); }
-        void transformColorSpace(ColorSpace srcColorSpace, ColorSpace dstColorSpace);
-        void platformTransformColorSpace(const Vector<uint8_t>&);
-        static const Vector<uint8_t>& getLinearRgbLUT();
-        static const Vector<uint8_t>& getDeviceRgbLUT();
-        WebKit::WebLayer* platformLayer() const;
+    void putByteArray(Multiply multiplied, Uint8ClampedArray*, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint, CoordinateSystem = LogicalCoordinateSystem);
 
-        // FIXME: current implementations of this method have the restriction that they only work
-        // with textures that are RGB or RGBA format, UNSIGNED_BYTE type and level 0, as specified in
-        // Extensions3D::canUseCopyTextureCHROMIUM().
-        bool copyToPlatformTexture(GraphicsContext3D&, Platform3DObject, GC3Denum, GC3Denum, GC3Dint, bool, bool);
+    void convertToLuminanceMask();
 
-        void reportMemoryUsage(MemoryObjectInfo*) const;
+    String toDataURL(const String& mimeType, const double* quality = 0, CoordinateSystem = LogicalCoordinateSystem) const;
+    AffineTransform baseTransform() const { return AffineTransform(); }
+    void transformColorSpace(ColorSpace srcColorSpace, ColorSpace dstColorSpace);
+    static const Vector<uint8_t>& getLinearRgbLUT();
+    static const Vector<uint8_t>& getDeviceRgbLUT();
+    WebKit::WebLayer* platformLayer() const;
 
-    private:
-        void clip(GraphicsContext*, const FloatRect&) const;
+    // FIXME: current implementations of this method have the restriction that they only work
+    // with textures that are RGB or RGBA format, UNSIGNED_BYTE type and level 0, as specified in
+    // Extensions3D::canUseCopyTextureCHROMIUM().
+    bool copyToPlatformTexture(GraphicsContext3D&, Platform3DObject, GC3Denum, GC3Denum, GC3Dint, bool, bool);
 
-        void draw(GraphicsContext*, const FloatRect&, const FloatRect& = FloatRect(0, 0, -1, -1), CompositeOperator = CompositeSourceOver, BlendMode = BlendModeNormal, bool useLowQualityScale = false);
-        void drawPattern(GraphicsContext*, const FloatRect&, const FloatSize&, const FloatPoint&, CompositeOperator, const FloatRect&);
+    void reportMemoryUsage(MemoryObjectInfo*) const;
 
-        inline void genericConvertToLuminanceMask();
+private:
+    void draw(GraphicsContext*, const FloatRect&, const FloatRect& = FloatRect(0, 0, -1, -1), CompositeOperator = CompositeSourceOver, BlendMode = BlendModeNormal, bool useLowQualityScale = false);
+    void drawPattern(GraphicsContext*, const FloatRect&, const FloatSize&, const FloatPoint&, CompositeOperator, const FloatRect&);
 
-        friend class GraphicsContext;
-        friend class GeneratedImage;
-        friend class CrossfadeGeneratedImage;
-        friend class GeneratorGeneratedImage;
+    friend class GraphicsContext;
+    friend class GeneratedImage;
+    friend class CrossfadeGeneratedImage;
+    friend class GeneratorGeneratedImage;
 
-    private:
-        ImageBufferData m_data;
-        IntSize m_size;
-        IntSize m_logicalSize;
-        float m_resolutionScale;
-        OwnPtr<GraphicsContext> m_context;
+    IntSize m_size;
+    IntSize m_logicalSize;
+    float m_resolutionScale;
+    OwnPtr<SkCanvas> m_canvas;
+    OwnPtr<GraphicsContext> m_context;
+    OwnPtr<Canvas2DLayerBridge> m_layerBridge;
 
-        // This constructor will place its success into the given out-variable
-        // so that create() knows when it should return failure.
-        ImageBuffer(const IntSize&, float resolutionScale, RenderingMode, OpacityMode, bool& success);
-        ImageBuffer(const IntSize&, float resolutionScale, const GraphicsContext*, bool hasAlpha, bool& success);
-    };
+    // This constructor will place its success into the given out-variable
+    // so that create() knows when it should return failure.
+    ImageBuffer(const IntSize&, float resolutionScale, RenderingMode, OpacityMode, bool& success);
+    ImageBuffer(const IntSize&, float resolutionScale, const GraphicsContext*, bool hasAlpha, bool& success);
+};
 
-    String ImageDataToDataURL(const ImageData&, const String& mimeType, const double* quality);
+String ImageDataToDataURL(const ImageData&, const String& mimeType, const double* quality);
 
 } // namespace WebCore
 
diff --git a/Source/core/platform/graphics/ImageRenderingMode.h b/Source/core/platform/graphics/ImageRenderingMode.h
deleted file mode 100644
index 3e462fb..0000000
--- a/Source/core/platform/graphics/ImageRenderingMode.h
+++ /dev/null
@@ -1,34 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- * 
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1.  Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
- * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef ImageRenderingMode_h
-#define ImageRenderingMode_h
-    
-namespace WebCore {
-
-enum ImageRenderingMode { AutoImageRendering, OptimizeContrast };
-
-} // namespace WebCore
-    
-#endif // ImageRenderingMode_h
diff --git a/Source/core/platform/graphics/ImageSource.cpp b/Source/core/platform/graphics/ImageSource.cpp
index 07f164c..0340650 100644
--- a/Source/core/platform/graphics/ImageSource.cpp
+++ b/Source/core/platform/graphics/ImageSource.cpp
@@ -28,12 +28,11 @@
 #include "config.h"
 #include "core/platform/graphics/ImageSource.h"
 
-#include "core/platform/image-decoders/ImageDecoder.h"
-
 #include "core/platform/PlatformMemoryInstrumentation.h"
 #include "core/platform/graphics/ImageOrientation.h"
-
 #include "core/platform/graphics/chromium/DeferredImageDecoder.h"
+#include "core/platform/image-decoders/ImageDecoder.h"
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
@@ -64,7 +63,7 @@
     // If insufficient bytes are available to determine the image type, no decoder plugin will be
     // made.
     if (!m_decoder)
-        m_decoder = NativeImageDecoder::create(*data, m_alphaOption, m_gammaAndColorProfileOption);
+        m_decoder = DeferredImageDecoder::create(*data, m_alphaOption, m_gammaAndColorProfileOption);
 
     if (m_decoder)
         m_decoder->setData(data, allDataReceived);
@@ -117,7 +116,7 @@
     return m_decoder ? m_decoder->frameCount() : 0;
 }
 
-PassNativeImagePtr ImageSource::createFrameAtIndex(size_t index)
+PassRefPtr<NativeImageSkia> ImageSource::createFrameAtIndex(size_t index)
 {
     if (!m_decoder)
         return 0;
diff --git a/Source/core/platform/graphics/ImageSource.h b/Source/core/platform/graphics/ImageSource.h
index e9fc415..f711871 100644
--- a/Source/core/platform/graphics/ImageSource.h
+++ b/Source/core/platform/graphics/ImageSource.h
@@ -27,24 +27,20 @@
 #define ImageSource_h
 
 #include "core/platform/graphics/ImageOrientation.h"
-#include "core/platform/graphics/NativeImagePtr.h"
-
-#include <wtf/Forward.h>
-#include <wtf/Noncopyable.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/Forward.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
+class DeferredImageDecoder;
 class ImageOrientation;
 class IntPoint;
 class IntSize;
+class NativeImageSkia;
 class SharedBuffer;
 
-class DeferredImageDecoder;
-typedef DeferredImageDecoder NativeImageDecoder;
-typedef DeferredImageDecoder* NativeImageDecoderPtr;
-
 // Right now GIFs are the only recognized image format that supports animation.
 // The animation system and the constants below are designed with this in mind.
 // GIFs have an optional 16-bit unsigned loop count that describes how an
@@ -116,7 +112,7 @@
 
     size_t frameCount() const;
 
-    PassNativeImagePtr createFrameAtIndex(size_t);
+    PassRefPtr<NativeImageSkia> createFrameAtIndex(size_t);
 
     float frameDurationAtIndex(size_t) const;
     bool frameHasAlphaAtIndex(size_t) const; // Whether or not the frame actually used any alpha.
@@ -130,7 +126,7 @@
     void reportMemoryUsage(MemoryObjectInfo*) const;
 
 private:
-    OwnPtr<NativeImageDecoderPtr> m_decoder;
+    OwnPtr<DeferredImageDecoder> m_decoder;
 
     AlphaOption m_alphaOption;
     GammaAndColorProfileOption m_gammaAndColorProfileOption;
diff --git a/Source/core/platform/graphics/IntPointHash.h b/Source/core/platform/graphics/IntPointHash.h
deleted file mode 100644
index 1842f29..0000000
--- a/Source/core/platform/graphics/IntPointHash.h
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
- 
- This library is free software; you can redistribute it and/or
- modify it under the terms of the GNU Library General Public
- License as published by the Free Software Foundation; either
- version 2 of the License, or (at your option) any later version.
- 
- This library is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- Library General Public License for more details.
- 
- You should have received a copy of the GNU Library General Public License
- along with this library; see the file COPYING.LIB.  If not, write to
- the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- Boston, MA 02110-1301, USA.
- */
-
-#ifndef IntPointHash_h
-#define IntPointHash_h
-
-#include "core/platform/graphics/IntPoint.h"
-#include <wtf/HashFunctions.h>
-#include <wtf/HashTraits.h>
-
-namespace WTF {
-    
-// The empty value is (0, INT_MIN), the deleted value is (INT_MIN, 0)
-struct IntPointHash {
-    static unsigned hash(const WebCore::IntPoint& p) { return pairIntHash(p.x(), p.y()); }
-    static bool equal(const WebCore::IntPoint& a, const WebCore::IntPoint& b) { return a == b; }
-    static const bool safeToCompareToEmptyOrDeleted = true;
-};
-template<> struct HashTraits<WebCore::IntPoint> : GenericHashTraits<WebCore::IntPoint> {
-    static const bool needsDestruction = false;
-    static WebCore::IntPoint emptyValue() { return WebCore::IntPoint(0, std::numeric_limits<int>::min()); }
-    
-    static void constructDeletedValue(WebCore::IntPoint& slot) { slot = WebCore::IntPoint(std::numeric_limits<int>::min(), 0); }
-    static bool isDeletedValue(const WebCore::IntPoint& slot) { return slot == WebCore::IntPoint(std::numeric_limits<int>::min(), 0); }
-};
-template<> struct DefaultHash<WebCore::IntPoint> {
-    typedef IntPointHash Hash;
-};
-
-}
-
-#endif
diff --git a/Source/core/platform/graphics/IntRectHash.h b/Source/core/platform/graphics/IntRectHash.h
deleted file mode 100644
index 80cd4e2..0000000
--- a/Source/core/platform/graphics/IntRectHash.h
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2011 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
- 
-#ifndef IntRectHash_h
-#define IntRectHash_h
-
-#include "core/platform/graphics/IntPointHash.h"
-#include "core/platform/graphics/IntRect.h"
-#include "core/platform/graphics/IntSizeHash.h"
-#include <wtf/HashMap.h>
-#include <wtf/HashSet.h>
-
-namespace WTF {
-
-template<> struct IntHash<WebCore::IntRect> {
-    static unsigned hash(const WebCore::IntRect& key)
-    {
-        return pairIntHash(DefaultHash<WebCore::IntPoint>::Hash::hash(key.location()), DefaultHash<WebCore::IntSize>::Hash::hash(key.size()));
-    }
-    static bool equal(const WebCore::IntRect& a, const WebCore::IntRect& b)
-    {
-        return DefaultHash<WebCore::IntPoint>::Hash::equal(a.location(), b.location()) && DefaultHash<WebCore::IntSize>::Hash::equal(a.size(), b.size());
-    }
-    static const bool safeToCompareToEmptyOrDeleted = true;
-};
-template<> struct DefaultHash<WebCore::IntRect> { typedef IntHash<WebCore::IntRect> Hash; };
-
-template<> struct HashTraits<WebCore::IntRect> : GenericHashTraits<WebCore::IntRect> {
-    static const bool emptyValueIsZero = true;
-    static const bool needsDestruction = false;
-    static void constructDeletedValue(WebCore::IntRect& slot) { new (NotNull, &slot) WebCore::IntRect(-1, -1, -1, -1); }
-    static bool isDeletedValue(const WebCore::IntRect& value) { return value.x() == -1 && value.y() == -1 && value.width() == -1 && value.height() == -1; }
-};
-
-}
-
-#endif
diff --git a/Source/core/platform/graphics/IntSizeHash.h b/Source/core/platform/graphics/IntSizeHash.h
index b435336..f882904 100644
--- a/Source/core/platform/graphics/IntSizeHash.h
+++ b/Source/core/platform/graphics/IntSizeHash.h
@@ -26,19 +26,23 @@
 
 namespace WTF {
 
-    template<> struct IntHash<WebCore::IntSize> {
-        static unsigned hash(const WebCore::IntSize& key) { return pairIntHash(key.width(), key.height()); }
-        static bool equal(const WebCore::IntSize& a, const WebCore::IntSize& b) { return a == b; }
-        static const bool safeToCompareToEmptyOrDeleted = true;
-    };
-    template<> struct DefaultHash<WebCore::IntSize> { typedef IntHash<WebCore::IntSize> Hash; };
-    
-    template<> struct HashTraits<WebCore::IntSize> : GenericHashTraits<WebCore::IntSize> {
-        static const bool emptyValueIsZero = true;
-        static const bool needsDestruction = false;
-        static void constructDeletedValue(WebCore::IntSize& slot) { new (NotNull, &slot) WebCore::IntSize(-1, -1); }
-        static bool isDeletedValue(const WebCore::IntSize& value) { return value.width() == -1 && value.height() == -1; }
-    };
+template<> struct IntHash<WebCore::IntSize> {
+    static unsigned hash(const WebCore::IntSize& key) { return pairIntHash(key.width(), key.height()); }
+    static bool equal(const WebCore::IntSize& a, const WebCore::IntSize& b) { return a == b; }
+    static const bool safeToCompareToEmptyOrDeleted = true;
+};
+
+template<> struct DefaultHash<WebCore::IntSize> {
+    typedef IntHash<WebCore::IntSize> Hash;
+};
+
+template<> struct HashTraits<WebCore::IntSize> : GenericHashTraits<WebCore::IntSize> {
+    static const bool emptyValueIsZero = true;
+    static const bool needsDestruction = false;
+    static void constructDeletedValue(WebCore::IntSize& slot) { new (NotNull, &slot) WebCore::IntSize(-1, -1); }
+    static bool isDeletedValue(const WebCore::IntSize& value) { return value.width() == -1 && value.height() == -1; }
+};
+
 } // namespace WTF
 
 #endif
diff --git a/Source/core/platform/graphics/MediaPlayer.h b/Source/core/platform/graphics/MediaPlayer.h
index f39b697..0796e04 100644
--- a/Source/core/platform/graphics/MediaPlayer.h
+++ b/Source/core/platform/graphics/MediaPlayer.h
@@ -87,7 +87,7 @@
     
     virtual CORSMode mediaPlayerCORSMode() const = 0;
 
-    virtual void mediaPlayerNeedsStyleRecalc() = 0;
+    virtual void scheduleLayerUpdate() = 0;
 
     virtual void mediaPlayerDidAddTrack(PassRefPtr<InbandTextTrackPrivate>) = 0;
     virtual void mediaPlayerDidRemoveTrack(PassRefPtr<InbandTextTrackPrivate>) = 0;
diff --git a/Source/core/platform/graphics/NativeImagePtr.h b/Source/core/platform/graphics/NativeImagePtr.h
deleted file mode 100644
index 85861e4..0000000
--- a/Source/core/platform/graphics/NativeImagePtr.h
+++ /dev/null
@@ -1,49 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc.  All rights reserved.
- * Copyright (C) 2007-2008 Torch Mobile, Inc.
- * Copyright (C) 2012 Company 100 Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE COMPUTER, INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
- */
-
-#ifndef NativeImagePtr_h
-#define NativeImagePtr_h
-
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-namespace WebCore {
-class NativeImageSkia;
-}
-
-namespace WTF {
-class MemoryObjectInfo;
-}
-
-namespace WebCore {
-
-// FIXME: NativeImagePtr and PassNativeImagePtr should be smart
-// pointers (see SVGImage::nativeImageForCurrentFrame()).
-typedef RefPtr<NativeImageSkia> NativeImagePtr;
-typedef PassRefPtr<NativeImageSkia> PassNativeImagePtr;
-void reportMemoryUsage(const NativeImageSkia*, WTF::MemoryObjectInfo*);
-}
-
-#endif
diff --git a/Source/core/platform/graphics/Path.h b/Source/core/platform/graphics/Path.h
index 6a6f810..6288b0c 100644
--- a/Source/core/platform/graphics/Path.h
+++ b/Source/core/platform/graphics/Path.h
@@ -39,91 +39,91 @@
 
 namespace WebCore {
 
-    class AffineTransform;
-    class FloatPoint;
-    class FloatRect;
-    class FloatSize;
-    class GraphicsContext;
-    class StrokeData;
+class AffineTransform;
+class FloatPoint;
+class FloatRect;
+class FloatSize;
+class GraphicsContext;
+class StrokeData;
 
-    enum PathElementType {
-        PathElementMoveToPoint, // The points member will contain 1 value.
-        PathElementAddLineToPoint, // The points member will contain 1 value.
-        PathElementAddQuadCurveToPoint, // The points member will contain 2 values.
-        PathElementAddCurveToPoint, // The points member will contain 3 values.
-        PathElementCloseSubpath // The points member will contain no values.
+enum PathElementType {
+    PathElementMoveToPoint, // The points member will contain 1 value.
+    PathElementAddLineToPoint, // The points member will contain 1 value.
+    PathElementAddQuadCurveToPoint, // The points member will contain 2 values.
+    PathElementAddCurveToPoint, // The points member will contain 3 values.
+    PathElementCloseSubpath // The points member will contain no values.
+};
+
+// The points in the sturcture are the same as those that would be used with the
+// add... method. For example, a line returns the endpoint, while a cubic returns
+// two tangent points and the endpoint.
+struct PathElement {
+    PathElementType type;
+    FloatPoint* points;
+};
+
+typedef void (*PathApplierFunction)(void* info, const PathElement*);
+
+class Path {
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    Path();
+    ~Path();
+
+    Path(const Path&);
+    Path& operator=(const Path&);
+    bool operator==(const Path&) const;
+
+    bool contains(const FloatPoint&, WindRule = RULE_NONZERO) const;
+    bool strokeContains(const FloatPoint&, const StrokeData&) const;
+    FloatRect boundingRect() const;
+    FloatRect strokeBoundingRect(const StrokeData&) const;
+
+    float length() const;
+    FloatPoint pointAtLength(float length, bool& ok) const;
+    float normalAngleAtLength(float length, bool& ok) const;
+    bool pointAndNormalAtLength(float length, FloatPoint&, float&) const;
+
+    void clear();
+    bool isEmpty() const;
+    // Gets the current point of the current path, which is conceptually the final point reached by the path so far.
+    // Note the Path can be empty (isEmpty() == true) and still have a current point.
+    bool hasCurrentPoint() const;
+    FloatPoint currentPoint() const;
+
+    void moveTo(const FloatPoint&);
+    void addLineTo(const FloatPoint&);
+    void addQuadCurveTo(const FloatPoint& controlPoint, const FloatPoint& endPoint);
+    void addBezierCurveTo(const FloatPoint& controlPoint1, const FloatPoint& controlPoint2, const FloatPoint& endPoint);
+    void addArcTo(const FloatPoint&, const FloatPoint&, float radius);
+    void closeSubpath();
+
+    void addArc(const FloatPoint&, float radius, float startAngle, float endAngle, bool anticlockwise);
+    void addRect(const FloatRect&);
+    void addEllipse(const FloatRect&);
+
+    enum RoundedRectStrategy {
+        PreferNativeRoundedRect,
+        PreferBezierRoundedRect
     };
 
-    // The points in the sturcture are the same as those that would be used with the
-    // add... method. For example, a line returns the endpoint, while a cubic returns
-    // two tangent points and the endpoint.
-    struct PathElement {
-        PathElementType type;
-        FloatPoint* points;
-    };
+    void addRoundedRect(const FloatRect&, const FloatSize& roundingRadii, RoundedRectStrategy = PreferNativeRoundedRect);
+    void addRoundedRect(const FloatRect&, const FloatSize& topLeftRadius, const FloatSize& topRightRadius, const FloatSize& bottomLeftRadius, const FloatSize& bottomRightRadius, RoundedRectStrategy = PreferNativeRoundedRect);
+    void addRoundedRect(const RoundedRect&);
 
-    typedef void (*PathApplierFunction)(void* info, const PathElement*);
+    void translate(const FloatSize&);
 
-    class Path {
-        WTF_MAKE_FAST_ALLOCATED;
-    public:
-        Path();
-        ~Path();
+    const SkPath& skPath() const { return m_path; }
 
-        Path(const Path&);
-        Path& operator=(const Path&);
-        bool operator==(const Path&) const;
+    void apply(void* info, PathApplierFunction) const;
+    void transform(const AffineTransform&);
 
-        bool contains(const FloatPoint&, WindRule rule = RULE_NONZERO) const;
-        bool strokeContains(const FloatPoint&, const StrokeData&) const;
-        FloatRect boundingRect() const;
-        FloatRect strokeBoundingRect(const StrokeData&) const;
-        
-        float length() const;
-        FloatPoint pointAtLength(float length, bool& ok) const;
-        float normalAngleAtLength(float length, bool& ok) const;
-        bool pointAndNormalAtLength(float length, FloatPoint&, float&) const;
+    void addPathForRoundedRect(const FloatRect&, const FloatSize& topLeftRadius, const FloatSize& topRightRadius, const FloatSize& bottomLeftRadius, const FloatSize& bottomRightRadius, RoundedRectStrategy = PreferNativeRoundedRect);
+    void addBeziersForRoundedRect(const FloatRect&, const FloatSize& topLeftRadius, const FloatSize& topRightRadius, const FloatSize& bottomLeftRadius, const FloatSize& bottomRightRadius);
 
-        void clear();
-        bool isEmpty() const;
-        // Gets the current point of the current path, which is conceptually the final point reached by the path so far.
-        // Note the Path can be empty (isEmpty() == true) and still have a current point.
-        bool hasCurrentPoint() const;
-        FloatPoint currentPoint() const;
-
-        void moveTo(const FloatPoint&);
-        void addLineTo(const FloatPoint&);
-        void addQuadCurveTo(const FloatPoint& controlPoint, const FloatPoint& endPoint);
-        void addBezierCurveTo(const FloatPoint& controlPoint1, const FloatPoint& controlPoint2, const FloatPoint& endPoint);
-        void addArcTo(const FloatPoint&, const FloatPoint&, float radius);
-        void closeSubpath();
-
-        void addArc(const FloatPoint&, float radius, float startAngle, float endAngle, bool anticlockwise);
-        void addRect(const FloatRect&);
-        void addEllipse(const FloatRect&);
-
-        enum RoundedRectStrategy {
-            PreferNativeRoundedRect,
-            PreferBezierRoundedRect
-        };
-
-        void addRoundedRect(const FloatRect&, const FloatSize& roundingRadii, RoundedRectStrategy = PreferNativeRoundedRect);
-        void addRoundedRect(const FloatRect&, const FloatSize& topLeftRadius, const FloatSize& topRightRadius, const FloatSize& bottomLeftRadius, const FloatSize& bottomRightRadius, RoundedRectStrategy = PreferNativeRoundedRect);
-        void addRoundedRect(const RoundedRect&);
-
-        void translate(const FloatSize&);
-
-        const SkPath& skPath() const { return m_path; }
-
-        void apply(void* info, PathApplierFunction) const;
-        void transform(const AffineTransform&);
-
-        void addPathForRoundedRect(const FloatRect&, const FloatSize& topLeftRadius, const FloatSize& topRightRadius, const FloatSize& bottomLeftRadius, const FloatSize& bottomRightRadius, RoundedRectStrategy = PreferNativeRoundedRect);
-        void addBeziersForRoundedRect(const FloatRect&, const FloatSize& topLeftRadius, const FloatSize& topRightRadius, const FloatSize& bottomLeftRadius, const FloatSize& bottomRightRadius);
-
-    private:
-        SkPath m_path;
-    };
+private:
+    SkPath m_path;
+};
 
 }
 
diff --git a/Source/core/platform/graphics/StringTruncator.cpp b/Source/core/platform/graphics/StringTruncator.cpp
index ba4e8e4..ef80369 100644
--- a/Source/core/platform/graphics/StringTruncator.cpp
+++ b/Source/core/platform/graphics/StringTruncator.cpp
@@ -63,16 +63,16 @@
     ASSERT(keepCount < STRING_BUFFER_SIZE);
     
     unsigned omitStart = (keepCount + 1) / 2;
-    NonSharedCharacterBreakIterator it(string.characters(), length);
+    NonSharedCharacterBreakIterator it(string.bloatedCharacters(), length);
     unsigned omitEnd = boundedTextBreakFollowing(it, omitStart + (length - keepCount) - 1, length);
     omitStart = textBreakAtOrPreceding(it, omitStart);
     
     unsigned truncatedLength = omitStart + 1 + (length - omitEnd);
     ASSERT(truncatedLength <= length);
 
-    memcpy(buffer, string.characters(), sizeof(UChar) * omitStart);
+    memcpy(buffer, string.bloatedCharacters(), sizeof(UChar) * omitStart);
     buffer[omitStart] = horizontalEllipsis;
-    memcpy(&buffer[omitStart + 1], &string.characters()[omitEnd], sizeof(UChar) * (length - omitEnd));
+    memcpy(&buffer[omitStart + 1], &string.bloatedCharacters()[omitEnd], sizeof(UChar) * (length - omitEnd));
     
     return truncatedLength;
 }
@@ -82,11 +82,11 @@
     ASSERT(keepCount < length);
     ASSERT(keepCount < STRING_BUFFER_SIZE);
     
-    NonSharedCharacterBreakIterator it(string.characters(), length);
+    NonSharedCharacterBreakIterator it(string.bloatedCharacters(), length);
     unsigned keepLength = textBreakAtOrPreceding(it, keepCount);
     unsigned truncatedLength = keepLength + 1;
     
-    memcpy(buffer, string.characters(), sizeof(UChar) * keepLength);
+    memcpy(buffer, string.bloatedCharacters(), sizeof(UChar) * keepLength);
     buffer[keepLength] = horizontalEllipsis;
     
     return truncatedLength;
@@ -119,7 +119,7 @@
         truncatedLength = centerTruncateToBuffer(string, length, keepCount, stringBuffer);
     } else {
         keepCount = length;
-        memcpy(stringBuffer, string.characters(), sizeof(UChar) * length);
+        memcpy(stringBuffer, string.bloatedCharacters(), sizeof(UChar) * length);
         truncatedLength = length;
     }
 
@@ -193,7 +193,7 @@
 
 float StringTruncator::width(const String& string, const Font& font, EnableRoundingHacksOrNot enableRoundingHacks)
 {
-    return stringWidth(font, string.characters(), string.length(), !enableRoundingHacks);
+    return stringWidth(font, string.bloatedCharacters(), string.length(), !enableRoundingHacks);
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/StringTruncator.h b/Source/core/platform/graphics/StringTruncator.h
index 1499c10..0c9e429 100644
--- a/Source/core/platform/graphics/StringTruncator.h
+++ b/Source/core/platform/graphics/StringTruncator.h
@@ -33,16 +33,16 @@
 
 namespace WebCore {
     
-    class Font;
-    
-    class StringTruncator {
-    public:
-        enum EnableRoundingHacksOrNot { DisableRoundingHacks, EnableRoundingHacks };
+class Font;
 
-        static String centerTruncate(const String&, float maxWidth, const Font&, EnableRoundingHacksOrNot = DisableRoundingHacks);
-        static String rightTruncate(const String&, float maxWidth, const Font&, EnableRoundingHacksOrNot = DisableRoundingHacks);
-        static float width(const String&, const Font&, EnableRoundingHacksOrNot = DisableRoundingHacks);
-    };
+class StringTruncator {
+public:
+    enum EnableRoundingHacksOrNot { DisableRoundingHacks, EnableRoundingHacks };
+
+    static String centerTruncate(const String&, float maxWidth, const Font&, EnableRoundingHacksOrNot = DisableRoundingHacks);
+    static String rightTruncate(const String&, float maxWidth, const Font&, EnableRoundingHacksOrNot = DisableRoundingHacks);
+    static float width(const String&, const Font&, EnableRoundingHacksOrNot = DisableRoundingHacks);
+};
     
 } // namespace WebCore
 
diff --git a/Source/core/platform/graphics/TextRenderingMode.h b/Source/core/platform/graphics/TextRenderingMode.h
index 4f817a4..d4d64ee 100644
--- a/Source/core/platform/graphics/TextRenderingMode.h
+++ b/Source/core/platform/graphics/TextRenderingMode.h
@@ -28,7 +28,7 @@
 
 namespace WebCore {
 
-    enum TextRenderingMode { AutoTextRendering, OptimizeSpeed, OptimizeLegibility, GeometricPrecision };
+enum TextRenderingMode { AutoTextRendering, OptimizeSpeed, OptimizeLegibility, GeometricPrecision };
     
 } // namespace WebCore
 
diff --git a/Source/core/platform/graphics/TextRun.h b/Source/core/platform/graphics/TextRun.h
index c948324..ab28956 100644
--- a/Source/core/platform/graphics/TextRun.h
+++ b/Source/core/platform/graphics/TextRun.h
@@ -122,11 +122,11 @@
             m_data.characters8 = s.characters8();
             m_is8Bit = true;
         } else {
-            m_data.characters16 = s.characters();
+            m_data.characters16 = s.bloatedCharacters();
             m_is8Bit = false;
         }
 #else
-        m_data.characters16 = s.characters();
+        m_data.characters16 = s.bloatedCharacters();
         m_is8Bit = false;
 #endif
     }
diff --git a/Source/core/platform/graphics/TypesettingFeatures.h b/Source/core/platform/graphics/TypesettingFeatures.h
index aa46beb..1dec5e4 100644
--- a/Source/core/platform/graphics/TypesettingFeatures.h
+++ b/Source/core/platform/graphics/TypesettingFeatures.h
@@ -27,12 +27,14 @@
 #define TypesettingFeatures_h
 
 namespace WebCore {
-    enum TypesettingFeature {
-        Kerning = 1 << 0,
-        Ligatures = 1 << 1,
-    };
 
-    typedef unsigned TypesettingFeatures;
+enum TypesettingFeature {
+    Kerning = 1 << 0,
+    Ligatures = 1 << 1,
+};
+
+typedef unsigned TypesettingFeatures;
+
 } // namespace WebCore
 
 #endif // TypesettingFeatures_h
diff --git a/Source/core/platform/graphics/UnitBezier.h b/Source/core/platform/graphics/UnitBezier.h
index df47e41..5321dd4 100644
--- a/Source/core/platform/graphics/UnitBezier.h
+++ b/Source/core/platform/graphics/UnitBezier.h
@@ -30,98 +30,100 @@
 
 namespace WebCore {
 
-    struct UnitBezier {
-        UnitBezier(double p1x, double p1y, double p2x, double p2y)
-        {
-            // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
-            cx = 3.0 * p1x;
-            bx = 3.0 * (p2x - p1x) - cx;
-            ax = 1.0 - cx -bx;
-             
-            cy = 3.0 * p1y;
-            by = 3.0 * (p2y - p1y) - cy;
-            ay = 1.0 - cy - by;
-        }
-        
-        double sampleCurveX(double t)
-        {
-            // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
-            return ((ax * t + bx) * t + cx) * t;
-        }
-        
-        double sampleCurveY(double t)
-        {
-            return ((ay * t + by) * t + cy) * t;
-        }
-        
-        double sampleCurveDerivativeX(double t)
-        {
-            return (3.0 * ax * t + 2.0 * bx) * t + cx;
-        }
-        
-        // Given an x value, find a parametric value it came from.
-        double solveCurveX(double x, double epsilon)
-        {
-            ASSERT(x >= 0.0);
-            ASSERT(x <= 1.0);
+struct UnitBezier {
+    UnitBezier(double p1x, double p1y, double p2x, double p2y)
+    {
+        // Calculate the polynomial coefficients, implicit first and last control points are (0,0) and (1,1).
+        cx = 3.0 * p1x;
+        bx = 3.0 * (p2x - p1x) - cx;
+        ax = 1.0 - cx -bx;
 
-            double t0;
-            double t1;
-            double t2;
-            double x2;
-            double d2;
-            int i;
+        cy = 3.0 * p1y;
+        by = 3.0 * (p2y - p1y) - cy;
+        ay = 1.0 - cy - by;
+    }
 
-            // First try a few iterations of Newton's method -- normally very fast.
-            for (t2 = x, i = 0; i < 8; i++) {
-                x2 = sampleCurveX(t2) - x;
-                if (fabs (x2) < epsilon)
-                    return t2;
-                d2 = sampleCurveDerivativeX(t2);
-                if (fabs(d2) < 1e-6)
-                    break;
-                t2 = t2 - x2 / d2;
-            }
+    double sampleCurveX(double t)
+    {
+        // `ax t^3 + bx t^2 + cx t' expanded using Horner's rule.
+        return ((ax * t + bx) * t + cx) * t;
+    }
 
-            // Fall back to the bisection method for reliability.
-            t0 = 0.0;
-            t1 = 1.0;
-            t2 = x;
+    double sampleCurveY(double t)
+    {
+        return ((ay * t + by) * t + cy) * t;
+    }
 
-            while (t0 < t1) {
-                x2 = sampleCurveX(t2);
-                if (fabs(x2 - x) < epsilon)
-                    return t2;
-                if (x > x2)
-                    t0 = t2;
-                else
-                    t1 = t2;
-                t2 = (t1 - t0) * .5 + t0;
-            }
+    double sampleCurveDerivativeX(double t)
+    {
+        return (3.0 * ax * t + 2.0 * bx) * t + cx;
+    }
 
-            // Failure.
-            return t2;
+    // Given an x value, find a parametric value it came from.
+    double solveCurveX(double x, double epsilon)
+    {
+        ASSERT(x >= 0.0);
+        ASSERT(x <= 1.0);
+
+        double t0;
+        double t1;
+        double t2;
+        double x2;
+        double d2;
+        int i;
+
+        // First try a few iterations of Newton's method -- normally very fast.
+        for (t2 = x, i = 0; i < 8; i++) {
+            x2 = sampleCurveX(t2) - x;
+            if (fabs (x2) < epsilon)
+                return t2;
+            d2 = sampleCurveDerivativeX(t2);
+            if (fabs(d2) < 1e-6)
+                break;
+            t2 = t2 - x2 / d2;
         }
 
-        // Evaluates y at the given x. The epsilon parameter provides a hint as to the required
-        // accuracy and is not guaranteed.
-        double solve(double x, double epsilon)
-        {
-            if (x < 0.0)
-                return 0.0;
-            if (x > 1.0)
-                return 1.0;
-            return sampleCurveY(solveCurveX(x, epsilon));
+        // Fall back to the bisection method for reliability.
+        t0 = 0.0;
+        t1 = 1.0;
+        t2 = x;
+
+        while (t0 < t1) {
+            x2 = sampleCurveX(t2);
+            if (fabs(x2 - x) < epsilon)
+                return t2;
+            if (x > x2)
+                t0 = t2;
+            else
+                t1 = t2;
+            t2 = (t1 - t0) * .5 + t0;
         }
-        
-    private:
-        double ax;
-        double bx;
-        double cx;
-        
-        double ay;
-        double by;
-        double cy;
-    };
-}
-#endif
+
+        // Failure.
+        return t2;
+    }
+
+    // Evaluates y at the given x. The epsilon parameter provides a hint as to the required
+    // accuracy and is not guaranteed.
+    double solve(double x, double epsilon)
+    {
+        if (x < 0.0)
+            return 0.0;
+        if (x > 1.0)
+            return 1.0;
+        return sampleCurveY(solveCurveX(x, epsilon));
+    }
+
+private:
+    double ax;
+    double bx;
+    double cx;
+
+    double ay;
+    double by;
+    double cy;
+};
+
+} // namespace WebCore
+
+#endif // UnitBezier_h
diff --git a/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp b/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp
index 7e62354..04726dc 100644
--- a/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp
+++ b/Source/core/platform/graphics/chromium/FontCacheChromiumWin.cpp
@@ -235,8 +235,7 @@
 
 static HFONT createFontIndirectAndGetWinName(const String& family, LOGFONT* winfont, String* winName)
 {
-    int len = min(static_cast<int>(family.length()), LF_FACESIZE - 1);
-    memcpy(winfont->lfFaceName, family.characters(), len * sizeof(WORD));
+    unsigned len = family.copyTo(winfont->lfFaceName, LF_FACESIZE - 1);
     winfont->lfFaceName[len] = '\0';
 
     HFONT hfont = CreateFontIndirect(winfont);
diff --git a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp b/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
index 865a9b4..3ea7c21 100644
--- a/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
+++ b/Source/core/platform/graphics/chromium/FontPlatformDataChromiumWin.cpp
@@ -289,31 +289,6 @@
     return m_scriptFontProperties;
 }
 
-#if ENABLE(OPENTYPE_VERTICAL)
-PassRefPtr<OpenTypeVerticalData> FontPlatformData::verticalData() const
-{
-    SkFontID id = typeface()->uniqueID();
-    return fontCache()->getVerticalData(id, *this);
-}
-
-PassRefPtr<SharedBuffer> FontPlatformData::openTypeTable(uint32_t table) const
-{
-    HWndDC hdc(0);
-    HGDIOBJ oldFont = SelectObject(hdc, hfont());
-
-    DWORD size = GetFontData(hdc, table, 0, 0, 0);
-    RefPtr<SharedBuffer> buffer;
-    if (size != GDI_ERROR) {
-        buffer = SharedBuffer::create(size);
-        DWORD result = GetFontData(hdc, table, 0, (PVOID)buffer->data(), size);
-        ASSERT(result == size);
-    }
-
-    SelectObject(hdc, oldFont);
-    return buffer.release();
-}
-#endif
-
 #ifndef NDEBUG
 String FontPlatformData::description() const
 {
diff --git a/Source/core/platform/graphics/chromium/ImageBufferDataSkia.h b/Source/core/platform/graphics/chromium/ImageBufferDataSkia.h
deleted file mode 100644
index 06bc124..0000000
--- a/Source/core/platform/graphics/chromium/ImageBufferDataSkia.h
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2008, 2009, Google Inc. All rights reserved.
- * 
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- * 
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- * 
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "skia/ext/platform_canvas.h"
-
-namespace WebCore {
-
-class Canvas2DLayerBridge;
-
-class ImageBufferData {
-public:
-    ImageBufferData(const IntSize&);
-
-    void reportMemoryUsage(MemoryObjectInfo*) const;
-
-    OwnPtr<SkCanvas> m_canvas;
-    OwnPtr<Canvas2DLayerBridge> m_layerBridge;
-};
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp b/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp
index 1d9f8f2..bf62235 100644
--- a/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp
+++ b/Source/core/platform/graphics/chromium/OpaqueRectTrackingContentLayerDelegate.cpp
@@ -52,7 +52,7 @@
     GraphicsContext context(canvas);
     context.setTrackOpaqueRegion(!m_opaque);
     context.setCertainlyOpaque(m_opaque);
-    context.setShouldSmoothFonts(canPaintLCDText && m_opaque);
+    context.setShouldSmoothFonts(canPaintLCDText);
 
     // Record transform prior to painting, as all opaque tracking will be
     // relative to this current value.
diff --git a/Source/core/platform/graphics/cocoa/FontPlatformDataCocoa.mm b/Source/core/platform/graphics/cocoa/FontPlatformDataCocoa.mm
index f82ed91..aa7a5e7 100644
--- a/Source/core/platform/graphics/cocoa/FontPlatformDataCocoa.mm
+++ b/Source/core/platform/graphics/cocoa/FontPlatformDataCocoa.mm
@@ -25,6 +25,7 @@
 #import "core/platform/graphics/FontPlatformData.h"
 
 #import <AppKit/NSFont.h>
+#import <AvailabilityMacros.h>
 #import <wtf/text/WTFString.h>
 
 #if OS(DARWIN)
@@ -78,7 +79,7 @@
 
 void FontPlatformData::platformDataInit(const FontPlatformData& f)
 {
-    m_font = f.m_font && f.m_font != reinterpret_cast<NSFont *>(-1) ? const_cast<NSFont *>(static_cast<const NSFont *>(CFRetain(f.m_font))) : f.m_font;
+    m_font = f.m_font && f.m_font != reinterpret_cast<NSFont *>(-1) ? [f.m_font retain] : f.m_font;
 
     m_cgFont = f.m_cgFont;
     m_CTFont = f.m_CTFont;
@@ -233,23 +234,13 @@
     return descriptor;
 }
 
-// Adding a cascade list breaks the font on Leopard
-static bool canSetCascadeListForCustomFont()
-{
-#if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1060
-    return true;
-#else
-    return false;
-#endif
-}
-
 CTFontRef FontPlatformData::ctFont() const
 {
     if (m_CTFont)
         return m_CTFont.get();
 
     if (m_inMemoryFont) {
-        m_CTFont.adoptCF(CTFontCreateWithGraphicsFont(m_inMemoryFont->cgFont(), m_size, 0, canSetCascadeListForCustomFont() ? cascadeToLastResortFontDescriptor() : 0));
+        m_CTFont.adoptCF(CTFontCreateWithGraphicsFont(m_inMemoryFont->cgFont(), m_size, 0, cascadeToLastResortFontDescriptor()));
         return m_CTFont.get();
     }
 
@@ -264,7 +255,7 @@
             fontDescriptor = cascadeToLastResortFontDescriptor();
         m_CTFont.adoptCF(CTFontCreateCopyWithAttributes(m_CTFont.get(), m_size, 0, fontDescriptor));
     } else
-        m_CTFont.adoptCF(CTFontCreateWithGraphicsFont(m_cgFont.get(), m_size, 0, canSetCascadeListForCustomFont() ? cascadeToLastResortFontDescriptor() : 0));
+        m_CTFont.adoptCF(CTFontCreateWithGraphicsFont(m_cgFont.get(), m_size, 0, cascadeToLastResortFontDescriptor()));
 
     if (m_widthVariant != RegularWidth) {
         int featureTypeValue = kTextSpacingType;
diff --git a/Source/core/platform/graphics/filters/FEComposite.cpp b/Source/core/platform/graphics/filters/FEComposite.cpp
index eaa5a62..35c7268 100644
--- a/Source/core/platform/graphics/filters/FEComposite.cpp
+++ b/Source/core/platform/graphics/filters/FEComposite.cpp
@@ -35,6 +35,7 @@
 #include "core/platform/graphics/filters/Filter.h"
 #include "core/platform/text/TextStream.h"
 #include "core/rendering/RenderTreeAsText.h"
+#include "third_party/skia/include/core/SkDevice.h"
 
 #include <wtf/Uint8ClampedArray.h>
 
diff --git a/Source/core/platform/graphics/filters/FEDisplacementMap.cpp b/Source/core/platform/graphics/filters/FEDisplacementMap.cpp
index 56c91c0..5f9a0b8 100644
--- a/Source/core/platform/graphics/filters/FEDisplacementMap.cpp
+++ b/Source/core/platform/graphics/filters/FEDisplacementMap.cpp
@@ -205,8 +205,10 @@
     SkAutoTUnref<SkImageFilter> displSource(new SkBitmapSource(displBitmap));
     SkDisplacementMapEffect::ChannelSelectorType typeX = toSkiaMode(m_xChannelSelector);
     SkDisplacementMapEffect::ChannelSelectorType typeY = toSkiaMode(m_yChannelSelector);
+    // FIXME : Only applyHorizontalScale is used and applyVerticalScale is ignored
+    // This can be fixed by adding a 2nd scale parameter to SkDisplacementMapEffect
     SkAutoTUnref<SkImageFilter> displEffect(new SkDisplacementMapEffect(
-        typeX, typeY, SkFloatToScalar(m_scale), displSource, colorSource));
+        typeX, typeY, SkFloatToScalar(filter()->applyHorizontalScale(m_scale)), displSource, colorSource));
     SkPaint paint;
     paint.setImageFilter(displEffect);
     resultImage->context()->drawBitmap(colorBitmap, 0, 0, &paint);
@@ -219,7 +221,9 @@
     SkImageFilter* displ = builder->build(inputEffect(1), operatingColorSpace());
     SkDisplacementMapEffect::ChannelSelectorType typeX = toSkiaMode(m_xChannelSelector);
     SkDisplacementMapEffect::ChannelSelectorType typeY = toSkiaMode(m_yChannelSelector);
-    return new SkDisplacementMapEffect(typeX, typeY, SkFloatToScalar(m_scale), displ, color);
+    // FIXME : Only applyHorizontalScale is used and applyVerticalScale is ignored
+    // This can be fixed by adding a 2nd scale parameter to SkDisplacementMapEffect
+    return new SkDisplacementMapEffect(typeX, typeY, SkFloatToScalar(filter()->applyHorizontalScale(m_scale)), displ, color);
 }
 
 static TextStream& operator<<(TextStream& ts, const ChannelSelectorType& type)
diff --git a/Source/core/platform/graphics/filters/FEFlood.cpp b/Source/core/platform/graphics/filters/FEFlood.cpp
index bc27f02..4b85b44 100644
--- a/Source/core/platform/graphics/filters/FEFlood.cpp
+++ b/Source/core/platform/graphics/filters/FEFlood.cpp
@@ -31,6 +31,7 @@
 #include "core/platform/graphics/filters/Filter.h"
 #include "core/platform/text/TextStream.h"
 #include "core/rendering/RenderTreeAsText.h"
+#include "third_party/skia/include/core/SkDevice.h"
 
 namespace {
 
diff --git a/Source/core/platform/graphics/filters/FEGaussianBlur.cpp b/Source/core/platform/graphics/filters/FEGaussianBlur.cpp
index 8bdb12f..c90d001 100644
--- a/Source/core/platform/graphics/filters/FEGaussianBlur.cpp
+++ b/Source/core/platform/graphics/filters/FEGaussianBlur.cpp
@@ -341,7 +341,9 @@
 SkImageFilter* FEGaussianBlur::createImageFilter(SkiaImageFilterBuilder* builder)
 {
     SkAutoTUnref<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
-    return new SkBlurImageFilter(SkFloatToScalar(m_stdX), SkFloatToScalar(m_stdY), input);
+    float stdX = filter()->applyHorizontalScale(m_stdX);
+    float stdY = filter()->applyVerticalScale(m_stdY);
+    return new SkBlurImageFilter(SkFloatToScalar(stdX), SkFloatToScalar(stdY), input);
 }
 
 TextStream& FEGaussianBlur::externalRepresentation(TextStream& ts, int indent) const
diff --git a/Source/core/platform/graphics/filters/FEMorphology.cpp b/Source/core/platform/graphics/filters/FEMorphology.cpp
index c8912d0..1d9f783 100644
--- a/Source/core/platform/graphics/filters/FEMorphology.cpp
+++ b/Source/core/platform/graphics/filters/FEMorphology.cpp
@@ -270,8 +270,8 @@
 SkImageFilter* FEMorphology::createImageFilter(SkiaImageFilterBuilder* builder)
 {
     SkAutoTUnref<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
-    SkScalar radiusX = SkFloatToScalar(m_radiusX);
-    SkScalar radiusY = SkFloatToScalar(m_radiusY);
+    SkScalar radiusX = SkFloatToScalar(filter()->applyHorizontalScale(m_radiusX));
+    SkScalar radiusY = SkFloatToScalar(filter()->applyVerticalScale(m_radiusY));
     if (m_type == FEMORPHOLOGY_OPERATOR_DILATE)
         return new SkDilateImageFilter(radiusX, radiusY, input);
     return new SkErodeImageFilter(radiusX, radiusY, input);
diff --git a/Source/core/platform/graphics/filters/FEOffset.cpp b/Source/core/platform/graphics/filters/FEOffset.cpp
index c7023f5..c18fa35 100644
--- a/Source/core/platform/graphics/filters/FEOffset.cpp
+++ b/Source/core/platform/graphics/filters/FEOffset.cpp
@@ -34,6 +34,7 @@
 #include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
 #include "core/platform/text/TextStream.h"
 #include "core/rendering/RenderTreeAsText.h"
+#include "third_party/skia/include/core/SkDevice.h"
 
 namespace WebCore {
 
@@ -154,7 +155,8 @@
 SkImageFilter* FEOffset::createImageFilter(SkiaImageFilterBuilder* builder)
 {
     SkAutoTUnref<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
-    return new OffsetImageFilter(SkFloatToScalar(m_dx), SkFloatToScalar(m_dy), input);
+    Filter* filter = this->filter();
+    return new OffsetImageFilter(SkFloatToScalar(filter->applyHorizontalScale(m_dx)), SkFloatToScalar(filter->applyVerticalScale(m_dy)), input);
 }
 
 TextStream& FEOffset::externalRepresentation(TextStream& ts, int indent) const
diff --git a/Source/core/platform/graphics/filters/FETile.cpp b/Source/core/platform/graphics/filters/FETile.cpp
index 72061c8..6ceb85b 100644
--- a/Source/core/platform/graphics/filters/FETile.cpp
+++ b/Source/core/platform/graphics/filters/FETile.cpp
@@ -23,16 +23,85 @@
 
 #include "core/platform/graphics/filters/FETile.h"
 
+#include "SkFlattenableBuffers.h"
+#include "SkImageFilter.h"
+
 #include "core/platform/graphics/GraphicsContext.h"
 #include "core/platform/graphics/Pattern.h"
 #include "core/platform/graphics/filters/Filter.h"
+#include "core/platform/graphics/filters/SkiaImageFilterBuilder.h"
 #include "core/platform/graphics/transforms/AffineTransform.h"
 #include "core/platform/text/TextStream.h"
 #include "core/rendering/RenderTreeAsText.h"
 #include "core/rendering/svg/SVGRenderingContext.h"
+#include "third_party/skia/include/core/SkDevice.h"
 
 namespace WebCore {
 
+class TileImageFilter : public SkImageFilter {
+public:
+    TileImageFilter(const SkRect& srcRect, const SkRect& dstRect, SkImageFilter* input)
+        : SkImageFilter(input)
+        , m_srcRect(srcRect)
+        , m_dstRect(dstRect)
+    {
+    }
+
+    virtual bool onFilterImage(Proxy* proxy, const SkBitmap& src, const SkMatrix& ctm, SkBitmap* dst, SkIPoint* offset)
+    {
+        SkBitmap source = src;
+        SkImageFilter* input = getInput(0);
+        SkIPoint localOffset = SkIPoint::Make(0, 0);
+        if (input && !input->filterImage(proxy, src, ctm, &source, &localOffset))
+            return false;
+
+        if (!m_srcRect.width() || !m_srcRect.height() || !m_dstRect.width() || !m_dstRect.height())
+            return false;
+
+        SkIRect srcRect;
+        m_srcRect.roundOut(&srcRect);
+        SkBitmap subset;
+        if (!source.extractSubset(&subset, srcRect))
+            return false;
+
+        SkAutoTUnref<SkDevice> device(proxy->createDevice(m_dstRect.width(), m_dstRect.height()));
+        SkIRect bounds;
+        source.getBounds(&bounds);
+        SkCanvas canvas(device);
+        SkPaint paint;
+        paint.setXfermodeMode(SkXfermode::kSrc_Mode);
+
+        SkAutoTUnref<SkShader> shader(SkShader::CreateBitmapShader(subset, SkShader::kRepeat_TileMode, SkShader::kRepeat_TileMode));
+        paint.setShader(shader);
+        SkRect dstRect = m_dstRect;
+        dstRect.offset(localOffset.fX, localOffset.fY);
+        canvas.drawRect(dstRect, paint);
+        *dst = device->accessBitmap(false);
+        return true;
+    }
+
+    SK_DECLARE_PUBLIC_FLATTENABLE_DESERIALIZATION_PROCS(TileImageFilter)
+
+protected:
+    explicit TileImageFilter(SkFlattenableReadBuffer& buffer)
+        : SkImageFilter(buffer)
+    {
+        buffer.readRect(&m_srcRect);
+        buffer.readRect(&m_dstRect);
+    }
+
+    virtual void flatten(SkFlattenableWriteBuffer& buffer) const
+    {
+        this->SkImageFilter::flatten(buffer);
+        buffer.writeRect(m_srcRect);
+        buffer.writeRect(m_dstRect);
+    }
+
+private:
+    SkRect m_srcRect;
+    SkRect m_dstRect;
+};
+
 FETile::FETile(Filter* filter)
     : FilterEffect(filter)
 {
@@ -82,6 +151,13 @@
     filterContext->fillRect(FloatRect(FloatPoint(), absolutePaintRect().size()));
 }
 
+SkImageFilter* FETile::createImageFilter(SkiaImageFilterBuilder* builder)
+{
+    SkAutoTUnref<SkImageFilter> input(builder->build(inputEffect(0), operatingColorSpace()));
+    FloatRect srcRect = inputEffect(0) ? inputEffect(0)->effectBoundaries() : FloatRect();
+    return new TileImageFilter(srcRect, effectBoundaries(), input);
+}
+
 TextStream& FETile::externalRepresentation(TextStream& ts, int indent) const
 {
     writeIndent(ts, indent);
diff --git a/Source/core/platform/graphics/filters/FETile.h b/Source/core/platform/graphics/filters/FETile.h
index 25859eb..a9c6e12 100644
--- a/Source/core/platform/graphics/filters/FETile.h
+++ b/Source/core/platform/graphics/filters/FETile.h
@@ -32,6 +32,8 @@
 public:
     static PassRefPtr<FETile> create(Filter* filter);
 
+    virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
+
     virtual void determineAbsolutePaintRect() { setAbsolutePaintRect(enclosingIntRect(maxEffectRect())); }
 
     virtual FilterEffectType filterEffectType() const { return FilterEffectTypeTile; }
diff --git a/Source/core/platform/graphics/filters/FETurbulence.cpp b/Source/core/platform/graphics/filters/FETurbulence.cpp
index b6834af..57b74d5 100644
--- a/Source/core/platform/graphics/filters/FETurbulence.cpp
+++ b/Source/core/platform/graphics/filters/FETurbulence.cpp
@@ -267,13 +267,11 @@
     return linearInterpolation(sy, a, b);
 }
 
-unsigned char FETurbulence::calculateTurbulenceValueForPoint(int channel, PaintingData& paintingData, StitchData& stitchData, const FloatPoint& point)
+unsigned char FETurbulence::calculateTurbulenceValueForPoint(int channel, PaintingData& paintingData, StitchData& stitchData, const FloatPoint& point, float baseFrequencyX, float baseFrequencyY)
 {
     float tileWidth = paintingData.filterSize.width();
     float tileHeight = paintingData.filterSize.height();
     ASSERT(tileWidth > 0 && tileHeight > 0);
-    float baseFrequencyX = m_baseFrequencyX;
-    float baseFrequencyY = m_baseFrequencyY;
     // Adjust the base frequencies if necessary for stitching.
     if (m_stitchTiles) {
         // When stitching tiled turbulence, the frequencies must be adjusted
@@ -331,7 +329,7 @@
     return static_cast<unsigned char>(turbulenceFunctionResult * 255);
 }
 
-inline void FETurbulence::fillRegion(Uint8ClampedArray* pixelArray, PaintingData& paintingData, int startY, int endY)
+inline void FETurbulence::fillRegion(Uint8ClampedArray* pixelArray, PaintingData& paintingData, int startY, int endY, float baseFrequencyX, float baseFrequencyY)
 {
     IntRect filterRegion = absolutePaintRect();
     IntPoint point(0, filterRegion.y() + startY);
@@ -345,14 +343,14 @@
         for (int x = 0; x < filterRegion.width(); ++x) {
             point.setX(point.x() + 1);
             for (channel = 0; channel < 4; ++channel, ++indexOfPixelChannel)
-                pixelArray->set(indexOfPixelChannel, calculateTurbulenceValueForPoint(channel, paintingData, stitchData, filter()->mapAbsolutePointToLocalPoint(point)));
+                pixelArray->set(indexOfPixelChannel, calculateTurbulenceValueForPoint(channel, paintingData, stitchData, filter()->mapAbsolutePointToLocalPoint(point), baseFrequencyX, baseFrequencyY));
         }
     }
 }
 
 void FETurbulence::fillRegionWorker(FillRegionParameters* parameters)
 {
-    parameters->filter->fillRegion(parameters->pixelArray, *parameters->paintingData, parameters->startY, parameters->endY);
+    parameters->filter->fillRegion(parameters->pixelArray, *parameters->paintingData, parameters->startY, parameters->endY, parameters->baseFrequencyX, parameters->baseFrequencyY);
 }
 
 void FETurbulence::applySoftware()
@@ -368,6 +366,8 @@
 
     PaintingData paintingData(m_seed, roundedIntSize(filterPrimitiveSubregion().size()));
     initPaint(paintingData);
+    float baseFrequencyX = 1.0f / filter()->applyHorizontalScale(1.0f / m_baseFrequencyX);
+    float baseFrequencyY = 1.0f / filter()->applyVerticalScale(1.0f / m_baseFrequencyY);
 
     int optimalThreadNumber = (absolutePaintRect().width() * absolutePaintRect().height()) / s_minimalRectDimension;
     if (optimalThreadNumber > 1) {
@@ -391,6 +391,8 @@
                 params.startY = startY;
                 startY += i < jobsWithExtra ? stepY + 1 : stepY;
                 params.endY = startY;
+                params.baseFrequencyX = baseFrequencyX;
+                params.baseFrequencyY = baseFrequencyY;
             }
 
             // Execute parallel jobs
@@ -400,18 +402,20 @@
     }
 
     // Fallback to single threaded mode if there is no room for a new thread or the paint area is too small.
-    fillRegion(pixelArray, paintingData, 0, absolutePaintRect().height());
+    fillRegion(pixelArray, paintingData, 0, absolutePaintRect().height(), baseFrequencyX, baseFrequencyY);
 }
 
-SkShader* FETurbulence::createShader(const IntRect& filterRegion) const
+SkShader* FETurbulence::createShader(const IntRect& filterRegion)
 {
     const SkISize size = SkISize::Make(filterRegion.width(), filterRegion.height());
+    float baseFrequencyX = 1.0f / filter()->applyHorizontalScale(1.0f / m_baseFrequencyX);
+    const float baseFrequencyY = 1.0f / filter()->applyVerticalScale(1.0f / m_baseFrequencyY);
     return (type() == FETURBULENCE_TYPE_FRACTALNOISE) ?
-        SkPerlinNoiseShader::CreateFractalNoise(SkFloatToScalar(baseFrequencyX()),
-            SkFloatToScalar(baseFrequencyY()), numOctaves(), SkFloatToScalar(seed()),
+        SkPerlinNoiseShader::CreateFractalNoise(SkFloatToScalar(baseFrequencyX),
+            SkFloatToScalar(baseFrequencyY), numOctaves(), SkFloatToScalar(seed()),
             stitchTiles() ? &size : 0) :
-        SkPerlinNoiseShader::CreateTubulence(SkFloatToScalar(baseFrequencyX()),
-            SkFloatToScalar(baseFrequencyY()), numOctaves(), SkFloatToScalar(seed()),
+        SkPerlinNoiseShader::CreateTubulence(SkFloatToScalar(baseFrequencyX),
+            SkFloatToScalar(baseFrequencyY), numOctaves(), SkFloatToScalar(seed()),
             stitchTiles() ? &size : 0);
 }
 
diff --git a/Source/core/platform/graphics/filters/FETurbulence.h b/Source/core/platform/graphics/filters/FETurbulence.h
index 3b01edf..c757c01 100644
--- a/Source/core/platform/graphics/filters/FETurbulence.h
+++ b/Source/core/platform/graphics/filters/FETurbulence.h
@@ -109,6 +109,8 @@
         PaintingData* paintingData;
         int startY;
         int endY;
+        float baseFrequencyX;
+        float baseFrequencyY;
     };
 
     static void fillRegionWorker(FillRegionParameters*);
@@ -118,12 +120,12 @@
     virtual void applySoftware() OVERRIDE;
     virtual bool applySkia() OVERRIDE;
     virtual SkImageFilter* createImageFilter(SkiaImageFilterBuilder*);
-    SkShader* createShader(const IntRect& filterRegion) const;
+    SkShader* createShader(const IntRect& filterRegion);
 
     inline void initPaint(PaintingData&);
     float noise2D(int channel, PaintingData&, StitchData&, const FloatPoint&);
-    unsigned char calculateTurbulenceValueForPoint(int channel, PaintingData&, StitchData&, const FloatPoint&);
-    inline void fillRegion(Uint8ClampedArray*, PaintingData&, int, int);
+    unsigned char calculateTurbulenceValueForPoint(int channel, PaintingData&, StitchData&, const FloatPoint&, float, float);
+    inline void fillRegion(Uint8ClampedArray*, PaintingData&, int, int, float, float);
 
     TurbulenceType m_type;
     float m_baseFrequencyX;
diff --git a/Source/core/platform/graphics/filters/Filter.h b/Source/core/platform/graphics/filters/Filter.h
index 120de23..786f653 100644
--- a/Source/core/platform/graphics/filters/Filter.h
+++ b/Source/core/platform/graphics/filters/Filter.h
@@ -48,8 +48,18 @@
     RenderingMode renderingMode() const { return m_renderingMode; }
     void setRenderingMode(RenderingMode renderingMode) { m_renderingMode = renderingMode; }
 
-    virtual float applyHorizontalScale(float value) const { return value * m_filterResolution.width(); }
-    virtual float applyVerticalScale(float value) const { return value * m_filterResolution.height(); }
+    virtual float applyHorizontalScale(float value) const
+    {
+        float filterRegionScale = absoluteFilterRegion().isEmpty() || filterRegion().isEmpty() ?
+            1.0f : absoluteFilterRegion().width() / filterRegion().width();
+        return value * m_filterResolution.width() * filterRegionScale;
+    }
+    virtual float applyVerticalScale(float value) const
+    {
+        float filterRegionScale = absoluteFilterRegion().isEmpty() || filterRegion().isEmpty() ?
+            1.0f : absoluteFilterRegion().height() / filterRegion().height();
+        return value * m_filterResolution.height() * filterRegionScale;
+    }
     
     virtual FloatRect sourceImageRect() const = 0;
 
diff --git a/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp b/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp
index 0f6eb4e..b7ad003 100644
--- a/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp
+++ b/Source/core/platform/graphics/harfbuzz/FontPlatformDataHarfBuzz.cpp
@@ -307,30 +307,4 @@
         m_style.useSubpixelRendering = useSkiaSubpixelRendering;
 }
 
-#if ENABLE(OPENTYPE_VERTICAL)
-static SkFontTableTag reverseByteOrder(uint32_t tableTag)
-{
-    return (tableTag >> 24) | ((tableTag >> 8) & 0xff00) | ((tableTag & 0xff00) << 8) | ((tableTag & 0xff) << 24);
-}
-
-PassRefPtr<OpenTypeVerticalData> FontPlatformData::verticalData() const
-{
-    return fontCache()->getVerticalData(uniqueID(), *this);
-}
-
-PassRefPtr<SharedBuffer> FontPlatformData::openTypeTable(uint32_t table) const
-{
-    RefPtr<SharedBuffer> buffer;
-
-    SkFontTableTag tag = reverseByteOrder(table);
-    const size_t tableSize = m_typeface->getTableSize(tag);
-    if (tableSize) {
-        Vector<char> tableBuffer(tableSize);
-        m_typeface->getTableData(tag, 0, tableSize, &tableBuffer[0]);
-        buffer = SharedBuffer::adoptVector(tableBuffer);
-    }
-    return buffer.release();
-}
-#endif
-
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp b/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp
index 24b5d6c..6b40ad8 100644
--- a/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp
+++ b/Source/core/platform/graphics/harfbuzz/HarfBuzzShaper.cpp
@@ -480,7 +480,7 @@
             String upperText = String(m_normalizedBuffer.get() + currentRun->startIndex(), currentRun->numCharacters());
             upperText.makeUpper();
             currentFontData = m_font->glyphDataForCharacter(upperText[0], false, SmallCapsVariant).fontData;
-            hb_buffer_add_utf16(harfBuzzBuffer.get(), upperText.characters(), currentRun->numCharacters(), 0, currentRun->numCharacters());
+            hb_buffer_add_utf16(harfBuzzBuffer.get(), upperText.bloatedCharacters(), currentRun->numCharacters(), 0, currentRun->numCharacters());
         } else
             hb_buffer_add_utf16(harfBuzzBuffer.get(), m_normalizedBuffer.get() + currentRun->startIndex(), currentRun->numCharacters(), 0, currentRun->numCharacters());
 
diff --git a/Source/core/platform/graphics/mac/ComplexTextControllerCoreText.mm b/Source/core/platform/graphics/mac/ComplexTextControllerCoreText.mm
index c0f2606..e5c514b 100644
--- a/Source/core/platform/graphics/mac/ComplexTextControllerCoreText.mm
+++ b/Source/core/platform/graphics/mac/ComplexTextControllerCoreText.mm
@@ -31,6 +31,7 @@
 #include "core/platform/graphics/TextRun.h"
 
 #include <ApplicationServices/ApplicationServices.h>
+#import <AvailabilityMacros.h>
 
 // Forward declare Mac SPIs.
 extern "C" {
diff --git a/Source/core/platform/graphics/mac/SimpleFontDataMac.mm b/Source/core/platform/graphics/mac/SimpleFontDataMac.mm
index aea9c2b..cf920c4 100644
--- a/Source/core/platform/graphics/mac/SimpleFontDataMac.mm
+++ b/Source/core/platform/graphics/mac/SimpleFontDataMac.mm
@@ -107,34 +107,6 @@
     return webFallbackFontFamily.get();
 }
 
-#if !ERROR_DISABLED
-#if defined(__LP64__) || __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070 || (__MAC_OS_X_VERSION_MAX_ALLOWED >= 1070 && __MAC_OS_X_VERSION_MIN_REQUIRED >= 1060)
-static NSString* pathFromFont(NSFont*)
-{
-    // FMGetATSFontRefFromFont is not available. As pathFromFont is only used for debugging purposes,
-    // returning nil is acceptable.
-    return nil;
-}
-#else
-static NSString* pathFromFont(NSFont *font)
-{
-    ATSFontRef atsFont = FMGetATSFontRefFromFont(CTFontGetPlatformFont(toCTFontRef(font), 0));
-    FSRef fileRef;
-
-    OSStatus status = ATSFontGetFileReference(atsFont, &fileRef);
-    if (status != noErr)
-        return nil;
-
-    UInt8 filePathBuffer[PATH_MAX];
-    status = FSRefMakePath(&fileRef, filePathBuffer, PATH_MAX);
-    if (status == noErr)
-        return [NSString stringWithUTF8String:(const char*)filePathBuffer];
-
-    return nil;
-}
-#endif // __LP64__
-#endif // !ERROR_DISABLED
-
 const SimpleFontData* SimpleFontData::getCompositeFontReferenceFontData(NSFont *key) const
 {
     if (key && !CFEqual(RetainPtr<CFStringRef>(AdoptCF, CTFontCopyPostScriptName(CTFontRef(key))).get(), CFSTR("LastResort"))) {
@@ -194,11 +166,7 @@
             m_platformData.setFont([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toFamily:fallbackFontFamily]);
         else
             m_platformData.setFont([NSFont fontWithName:fallbackFontFamily size:m_platformData.size()]);
-#if !ERROR_DISABLED
-        NSString *filePath = pathFromFont(initialFont.get());
-        if (!filePath)
-            filePath = @"not known";
-#endif
+
         if (!initFontData(this)) {
             if ([fallbackFontFamily isEqual:@"Times New Roman"]) {
                 // OK, couldn't setup Times New Roman as an alternate to Times, fallback
@@ -206,19 +174,19 @@
                 m_platformData.setFont([[NSFontManager sharedFontManager] convertFont:m_platformData.font() toFamily:webFallbackFontFamily()]);
                 if (!initFontData(this)) {
                     // We tried, Times, Times New Roman, and the system font. No joy. We have to give up.
-                    LOG_ERROR("unable to initialize with font %@ at %@", initialFont.get(), filePath);
+                    LOG_ERROR("unable to initialize with font %@", initialFont.get());
                     failedSetup = true;
                 }
             } else {
                 // We tried the requested font and the system font. No joy. We have to give up.
-                LOG_ERROR("unable to initialize with font %@ at %@", initialFont.get(), filePath);
+                LOG_ERROR("unable to initialize with font %@", initialFont.get());
                 failedSetup = true;
             }
         }
 
         // Report the problem.
-        LOG_ERROR("Corrupt font detected, using %@ in place of %@ located at \"%@\".",
-            [m_platformData.font() familyName], [initialFont.get() familyName], filePath);
+        LOG_ERROR("Corrupt font detected, using %@ in place of %@.",
+            [m_platformData.font() familyName], [initialFont.get() familyName]);
     }
 
     // If all else fails, try to set up using the system font.
diff --git a/Source/core/platform/graphics/skia/FontCustomPlatformData.cpp b/Source/core/platform/graphics/skia/FontCustomPlatformData.cpp
index 7ac3094..826baf8 100644
--- a/Source/core/platform/graphics/skia/FontCustomPlatformData.cpp
+++ b/Source/core/platform/graphics/skia/FontCustomPlatformData.cpp
@@ -78,8 +78,8 @@
         ASSERT_NOT_REACHED();
         return FontPlatformData();
     }
-    memcpy(logFont.lfFaceName, m_name.charactersWithNullTermination(),
-           sizeof(logFont.lfFaceName[0]) * (1 + m_name.length()));
+    unsigned len = m_name.copyTo(logFont.lfFaceName, LF_FACESIZE - 1);
+    logFont.lfFaceName[len] = '\0';
 
     // FIXME: almost identical to FillLogFont in FontCacheWin.cpp.
     // Need to refactor.
diff --git a/Source/core/editing/chromium/FrameSelectionChromium.cpp b/Source/core/platform/graphics/skia/FontPlatformDataSkia.cpp
similarity index 64%
copy from Source/core/editing/chromium/FrameSelectionChromium.cpp
copy to Source/core/platform/graphics/skia/FontPlatformDataSkia.cpp
index ef88491..33c5662 100644
--- a/Source/core/editing/chromium/FrameSelectionChromium.cpp
+++ b/Source/core/platform/graphics/skia/FontPlatformDataSkia.cpp
@@ -1,10 +1,10 @@
 /*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- * 
+ * Copyright (c) 2006, 2007, 2008, Google Inc. All rights reserved.
+ *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
  * met:
- * 
+ *
  *     * Redistributions of source code must retain the above copyright
  * notice, this list of conditions and the following disclaimer.
  *     * Redistributions in binary form must reproduce the above
@@ -14,7 +14,7 @@
  *     * Neither the name of Google Inc. nor the names of its
  * contributors may be used to endorse or promote products derived from
  * this software without specific prior written permission.
- * 
+ *
  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
@@ -29,21 +29,33 @@
  */
 
 #include "config.h"
-#include "core/editing/FrameSelection.h"
+#include "core/platform/graphics/FontPlatformData.h"
 
-#include "core/accessibility/AXObjectCache.h"
-#include "core/dom/Document.h"
-#include "core/page/Frame.h"
+#include "SkEndian.h"
+#include "SkTypeface.h"
+#include "core/platform/graphics/FontCache.h"
 
 namespace WebCore {
 
-void FrameSelection::notifyAccessibilityForSelectionChange()
+#if ENABLE(OPENTYPE_VERTICAL)
+PassRefPtr<OpenTypeVerticalData> FontPlatformData::verticalData() const
 {
-    // FIXME: Support editable text in chromium.
-    if (m_selection.start().isNotNull() && m_selection.end().isNotNull()) {
-        if (AXObjectCache* cache = m_frame->document()->existingAXObjectCache())
-            cache->postNotification(m_selection.start().deprecatedNode(), AXObjectCache::AXSelectedTextChanged, false);
-    }
+    return fontCache()->getVerticalData(typeface()->uniqueID(), *this);
 }
 
+PassRefPtr<SharedBuffer> FontPlatformData::openTypeTable(uint32_t table) const
+{
+    RefPtr<SharedBuffer> buffer;
+
+    SkFontTableTag tag = SkEndianSwap32(table);
+    const size_t tableSize = m_typeface->getTableSize(tag);
+    if (tableSize) {
+        Vector<char> tableBuffer(tableSize);
+        m_typeface->getTableData(tag, 0, tableSize, &tableBuffer[0]);
+        buffer = SharedBuffer::adoptVector(tableBuffer);
+    }
+    return buffer.release();
+}
+#endif
+
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp b/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp
index 1b47568..2b231bf 100644
--- a/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp
+++ b/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp
@@ -49,8 +49,15 @@
     SkPaint paint;
     fontData->platformData().setupPaint(&paint);
     paint.setTextEncoding(SkPaint::kUTF16_TextEncoding);
-    
-    SkAutoSTMalloc <GlyphPage::size, uint16_t> glyphStorage(length);
+
+#if OS(WINDOWS)
+    // FIXME: For some reason SkAutoSTMalloc fails to link on Windows.
+    // SkAutoSTArray works fine though...
+    SkAutoSTArray<GlyphPage::size, uint16_t> glyphStorage(length);
+#else
+    SkAutoSTMalloc<GlyphPage::size, uint16_t> glyphStorage(length);
+#endif
+
     uint16_t* glyphs = glyphStorage.get();
     // textToGlyphs takes a byte count, not a glyph count so we multiply by two.
     unsigned count = paint.textToGlyphs(buffer, bufferLength * 2, glyphs);
diff --git a/Source/core/platform/graphics/skia/ImageBufferSkia.cpp b/Source/core/platform/graphics/skia/ImageBufferSkia.cpp
deleted file mode 100644
index fc16581..0000000
--- a/Source/core/platform/graphics/skia/ImageBufferSkia.cpp
+++ /dev/null
@@ -1,446 +0,0 @@
-/*
- * Copyright (c) 2008, Google Inc. All rights reserved.
- * Copyright (C) 2009 Dirk Schulze <krit@webkit.org>
- * Copyright (C) 2010 Torch Mobile (Beijing) Co. Ltd. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/graphics/ImageBuffer.h"
-
-#include "GrContext.h"
-#include "SkColorPriv.h"
-#include "SkGpuDevice.h"
-#include "SkSurface.h"
-#include "core/html/ImageData.h"
-#include "core/platform/MIMETypeRegistry.h"
-#include "core/platform/graphics/BitmapImage.h"
-#include "core/platform/graphics/Extensions3D.h"
-#include "core/platform/graphics/GraphicsContext.h"
-#include "core/platform/graphics/GraphicsContext3D.h"
-#include "core/platform/graphics/chromium/Canvas2DLayerBridge.h"
-#include "core/platform/graphics/gpu/SharedGraphicsContext3D.h"
-#include "core/platform/graphics/skia/MemoryInstrumentationSkia.h"
-#include "core/platform/graphics/skia/NativeImageSkia.h"
-#include "core/platform/graphics/skia/SkiaUtils.h"
-#include "core/platform/image-encoders/skia/JPEGImageEncoder.h"
-#include "core/platform/image-encoders/skia/PNGImageEncoder.h"
-#include "core/platform/image-encoders/skia/WEBPImageEncoder.h"
-#include "public/platform/Platform.h"
-
-#include <wtf/text/Base64.h>
-#include <wtf/text/WTFString.h>
-
-using namespace std;
-
-namespace WebCore {
-
-// We pass a technically-uninitialized canvas to the platform context here since
-// the canvas initialization completes in ImageBuffer::ImageBuffer. But
-// PlatformContext doesn't actually need to use the object, and this makes all
-// the ownership easier to manage.
-ImageBufferData::ImageBufferData(const IntSize& size)
-{
-}
-
-static SkCanvas* createAcceleratedCanvas(const IntSize& size, ImageBufferData* data, OpacityMode opacityMode)
-{
-    RefPtr<GraphicsContext3D> context3D = SharedGraphicsContext3D::get();
-    if (!context3D)
-        return 0;
-    GrContext* gr = context3D->grContext();
-    if (!gr)
-        return 0;
-    gr->resetContext();
-    Canvas2DLayerBridge::OpacityMode bridgeOpacityMode = opacityMode == Opaque ? Canvas2DLayerBridge::Opaque : Canvas2DLayerBridge::NonOpaque;
-    Canvas2DLayerBridge::ThreadMode threadMode = WebKit::Platform::current()->isThreadedCompositingEnabled() ? Canvas2DLayerBridge::Threaded : Canvas2DLayerBridge::SingleThread;
-    SkImage::Info info;
-    info.fWidth = size.width();
-    info.fHeight = size.height();
-    info.fColorType = SkImage::kPMColor_ColorType;
-    info.fAlphaType = SkImage::kPremul_AlphaType;
-    SkAutoTUnref<SkSurface> surface(SkSurface::NewRenderTarget(context3D->grContext(), info));
-    if (!surface.get())
-        return 0;
-    SkDeferredCanvas* canvas = new SkDeferredCanvas(surface.get());
-    data->m_layerBridge = Canvas2DLayerBridge::create(context3D.release(), canvas, bridgeOpacityMode, threadMode);
-    // If canvas buffer allocation failed, debug build will have asserted
-    // For release builds, we must verify whether the device has a render target
-    return canvas;
-}
-
-static SkCanvas* createNonPlatformCanvas(const IntSize& size)
-{
-    SkAutoTUnref<SkDevice> device(new SkDevice(SkBitmap::kARGB_8888_Config, size.width(), size.height()));
-    SkPixelRef* pixelRef = device->accessBitmap(false).pixelRef();
-    return pixelRef ? new SkCanvas(device) : 0;
-}
-
-PassOwnPtr<ImageBuffer> ImageBuffer::createCompatibleBuffer(const IntSize& size, float resolutionScale, const GraphicsContext* context, bool hasAlpha)
-{
-    bool success = false;
-    OwnPtr<ImageBuffer> buf = adoptPtr(new ImageBuffer(size, resolutionScale, context, hasAlpha, success));
-    if (!success)
-        return nullptr;
-    return buf.release();
-}
-
-ImageBuffer::ImageBuffer(const IntSize& size, float resolutionScale, const GraphicsContext* compatibleContext, bool hasAlpha, bool& success)
-    : m_data(size)
-    , m_size(size)
-    , m_logicalSize(size)
-    , m_resolutionScale(resolutionScale)
-{
-    if (!compatibleContext) {
-        success = false;
-        return;
-    }
-
-    SkAutoTUnref<SkDevice> device(compatibleContext->createCompatibleDevice(size, hasAlpha));
-    if (!device.get()) {
-        success = false;
-        return;
-    }
-
-    SkPixelRef* pixelRef = device->accessBitmap(false).pixelRef();
-    if (!pixelRef) {
-        success = false;
-        return;
-    }
-
-    m_data.m_canvas = adoptPtr(new SkCanvas(device));
-    m_context = adoptPtr(new GraphicsContext(m_data.m_canvas.get()));
-    m_context->setShouldSmoothFonts(false);
-    m_context->scale(FloatSize(m_resolutionScale, m_resolutionScale));
-
-    success = true;
-}
-
-ImageBuffer::ImageBuffer(const IntSize& size, float resolutionScale, RenderingMode renderingMode, OpacityMode opacityMode, bool& success)
-    : m_data(size)
-    , m_size(size)
-    , m_logicalSize(size)
-    , m_resolutionScale(resolutionScale)
-{
-    OwnPtr<SkCanvas> canvas;
-
-    if (renderingMode == Accelerated)
-        canvas = adoptPtr(createAcceleratedCanvas(size, &m_data, opacityMode));
-    else if (renderingMode == UnacceleratedNonPlatformBuffer)
-        canvas = adoptPtr(createNonPlatformCanvas(size));
-
-    if (!canvas)
-        canvas = adoptPtr(skia::TryCreateBitmapCanvas(size.width(), size.height(), false));
-
-    if (!canvas) {
-        success = false;
-        return;
-    }
-
-    m_data.m_canvas = canvas.release();
-    m_context = adoptPtr(new GraphicsContext(m_data.m_canvas.get()));
-    m_context->setShouldSmoothFonts(opacityMode == Opaque);
-    m_context->setAccelerated(renderingMode == Accelerated);
-    m_context->scale(FloatSize(m_resolutionScale, m_resolutionScale));
-
-    // Clear the background transparent or opaque, as required. It would be nice if this wasn't
-    // required, but the canvas is currently filled with the magic transparency
-    // color. Can we have another way to manage this?
-    if (opacityMode == Opaque)
-        m_data.m_canvas->drawARGB(255, 0, 0, 0, SkXfermode::kSrc_Mode);
-    else
-        m_data.m_canvas->drawARGB(0, 0, 0, 0, SkXfermode::kClear_Mode);
-
-    success = true;
-}
-
-ImageBuffer::~ImageBuffer()
-{
-}
-
-GraphicsContext* ImageBuffer::context() const
-{
-    if (m_data.m_layerBridge) {
-        // We're using context acquisition as a signal that someone is about to render into our buffer and we need
-        // to be ready. This isn't logically const-correct, hence the cast.
-        const_cast<Canvas2DLayerBridge*>(m_data.m_layerBridge.get())->contextAcquired();
-    }
-    return m_context.get();
-}
-
-static SkBitmap deepSkBitmapCopy(const SkBitmap& bitmap)
-{
-    SkBitmap tmp;
-    if (!bitmap.deepCopyTo(&tmp, bitmap.config()))
-        bitmap.copyTo(&tmp, bitmap.config());
-
-    return tmp;
-}
-
-PassRefPtr<Image> ImageBuffer::copyImage(BackingStoreCopy copyBehavior, ScaleBehavior) const
-{
-    const SkBitmap& bitmap = *context()->bitmap();
-    // FIXME: Start honoring ScaleBehavior to scale 2x buffers down to 1x.
-    return BitmapImage::create(NativeImageSkia::create(copyBehavior == CopyBackingStore ? deepSkBitmapCopy(bitmap) : bitmap, m_resolutionScale));
-}
-
-BackingStoreCopy ImageBuffer::fastCopyImageMode()
-{
-    return DontCopyBackingStore;
-}
-
-WebKit::WebLayer* ImageBuffer::platformLayer() const
-{
-    return m_data.m_layerBridge ? m_data.m_layerBridge->layer() : 0;
-}
-
-bool ImageBuffer::copyToPlatformTexture(GraphicsContext3D& context, Platform3DObject texture, GC3Denum internalFormat, GC3Denum destType, GC3Dint level, bool premultiplyAlpha, bool flipY)
-{
-    if (!m_data.m_layerBridge || !platformLayer())
-        return false;
-
-    Platform3DObject sourceTexture = m_data.m_layerBridge->backBufferTexture();
-
-    if (!context.makeContextCurrent())
-        return false;
-
-    Extensions3D* extensions = context.getExtensions();
-    if (!extensions->supports("GL_CHROMIUM_copy_texture") || !extensions->supports("GL_CHROMIUM_flipy")
-        || !extensions->canUseCopyTextureCHROMIUM(internalFormat, destType, level))
-        return false;
-
-    // The canvas is stored in a premultiplied format, so unpremultiply if necessary.
-    context.pixelStorei(Extensions3D::UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM, !premultiplyAlpha);
-
-    // The canvas is stored in an inverted position, so the flip semantics are reversed.
-    context.pixelStorei(Extensions3D::UNPACK_FLIP_Y_CHROMIUM, !flipY);
-
-    extensions->copyTextureCHROMIUM(GraphicsContext3D::TEXTURE_2D, sourceTexture, texture, level, internalFormat, destType);
-
-    context.pixelStorei(Extensions3D::UNPACK_FLIP_Y_CHROMIUM, false);
-    context.pixelStorei(Extensions3D::UNPACK_UNPREMULTIPLY_ALPHA_CHROMIUM, false);
-    context.flush();
-    return true;
-}
-
-void ImageBuffer::clip(GraphicsContext* context, const FloatRect& rect) const
-{
-    context->beginLayerClippedToImage(rect, this);
-}
-
-static bool drawNeedsCopy(GraphicsContext* src, GraphicsContext* dst)
-{
-    return (src == dst);
-}
-
-void ImageBuffer::draw(GraphicsContext* context, const FloatRect& destRect, const FloatRect& srcRect,
-    CompositeOperator op, BlendMode blendMode, bool useLowQualityScale)
-{
-    const SkBitmap& bitmap = *m_context->bitmap();
-    RefPtr<Image> image = BitmapImage::create(NativeImageSkia::create(drawNeedsCopy(m_context.get(), context) ? deepSkBitmapCopy(bitmap) : bitmap));
-    context->drawImage(image.get(), destRect, srcRect, op, blendMode, DoNotRespectImageOrientation, useLowQualityScale);
-}
-
-void ImageBuffer::drawPattern(GraphicsContext* context, const FloatRect& srcRect, const FloatSize& scale,
-    const FloatPoint& phase, CompositeOperator op, const FloatRect& destRect)
-{
-    const SkBitmap& bitmap = *m_context->bitmap();
-    RefPtr<Image> image = BitmapImage::create(NativeImageSkia::create(drawNeedsCopy(m_context.get(), context) ? deepSkBitmapCopy(bitmap) : bitmap));
-    image->drawPattern(context, srcRect, scale, phase, op, destRect);
-}
-
-void ImageBuffer::platformTransformColorSpace(const Vector<uint8_t>& lookUpTable)
-{
-    // FIXME: Disable color space conversions on accelerated canvases (for now).
-    if (context()->isAccelerated())
-        return;
-
-    const SkBitmap& bitmap = *context()->bitmap();
-    if (bitmap.isNull())
-        return;
-
-    ASSERT(bitmap.config() == SkBitmap::kARGB_8888_Config);
-    SkAutoLockPixels bitmapLock(bitmap);
-    for (int y = 0; y < m_size.height(); ++y) {
-        uint32_t* srcRow = bitmap.getAddr32(0, y);
-        for (int x = 0; x < m_size.width(); ++x) {
-            SkColor color = SkPMColorToColor(srcRow[x]);
-            srcRow[x] = SkPreMultiplyARGB(SkColorGetA(color),
-                                          lookUpTable[SkColorGetR(color)],
-                                          lookUpTable[SkColorGetG(color)],
-                                          lookUpTable[SkColorGetB(color)]);
-        }
-    }
-}
-
-template <Multiply multiplied>
-PassRefPtr<Uint8ClampedArray> getImageData(const IntRect& rect, GraphicsContext* context, const IntSize& size)
-{
-    float area = 4.0f * rect.width() * rect.height();
-    if (area > static_cast<float>(std::numeric_limits<int>::max()))
-        return 0;
-
-    RefPtr<Uint8ClampedArray> result = Uint8ClampedArray::createUninitialized(rect.width() * rect.height() * 4);
-
-    unsigned char* data = result->data();
-
-    if (rect.x() < 0
-        || rect.y() < 0
-        || rect.maxX() > size.width()
-        || rect.maxY() > size.height())
-        result->zeroFill();
-
-    unsigned destBytesPerRow = 4 * rect.width();
-    SkBitmap destBitmap;
-    destBitmap.setConfig(SkBitmap::kARGB_8888_Config, rect.width(), rect.height(), destBytesPerRow);
-    destBitmap.setPixels(data);
-
-    SkCanvas::Config8888 config8888;
-    if (multiplied == Premultiplied)
-        config8888 = SkCanvas::kRGBA_Premul_Config8888;
-    else
-        config8888 = SkCanvas::kRGBA_Unpremul_Config8888;
-
-    context->readPixels(&destBitmap, rect.x(), rect.y(), config8888);
-    return result.release();
-}
-
-PassRefPtr<Uint8ClampedArray> ImageBuffer::getUnmultipliedImageData(const IntRect& rect, CoordinateSystem) const
-{
-    return getImageData<Unmultiplied>(rect, context(), m_size);
-}
-
-PassRefPtr<Uint8ClampedArray> ImageBuffer::getPremultipliedImageData(const IntRect& rect, CoordinateSystem) const
-{
-    return getImageData<Premultiplied>(rect, context(), m_size);
-}
-
-void ImageBuffer::putByteArray(Multiply multiplied, Uint8ClampedArray* source, const IntSize& sourceSize, const IntRect& sourceRect, const IntPoint& destPoint, CoordinateSystem)
-{
-    ASSERT(sourceRect.width() > 0);
-    ASSERT(sourceRect.height() > 0);
-
-    int originX = sourceRect.x();
-    int destX = destPoint.x() + sourceRect.x();
-    ASSERT(destX >= 0);
-    ASSERT(destX < m_size.width());
-    ASSERT(originX >= 0);
-    ASSERT(originX < sourceRect.maxX());
-
-    int endX = destPoint.x() + sourceRect.maxX();
-    ASSERT(endX <= m_size.width());
-
-    int numColumns = endX - destX;
-
-    int originY = sourceRect.y();
-    int destY = destPoint.y() + sourceRect.y();
-    ASSERT(destY >= 0);
-    ASSERT(destY < m_size.height());
-    ASSERT(originY >= 0);
-    ASSERT(originY < sourceRect.maxY());
-
-    int endY = destPoint.y() + sourceRect.maxY();
-    ASSERT(endY <= m_size.height());
-    int numRows = endY - destY;
-
-    unsigned srcBytesPerRow = 4 * sourceSize.width();
-    SkBitmap srcBitmap;
-    srcBitmap.setConfig(SkBitmap::kARGB_8888_Config, numColumns, numRows, srcBytesPerRow);
-    srcBitmap.setPixels(source->data() + originY * srcBytesPerRow + originX * 4);
-
-    SkCanvas::Config8888 config8888;
-    if (multiplied == Premultiplied)
-        config8888 = SkCanvas::kRGBA_Premul_Config8888;
-    else
-        config8888 = SkCanvas::kRGBA_Unpremul_Config8888;
-
-    context()->writePixels(srcBitmap, destX, destY, config8888);
-}
-
-template <typename T>
-static bool encodeImage(T& source, const String& mimeType, const double* quality, Vector<char>* output)
-{
-    Vector<unsigned char>* encodedImage = reinterpret_cast<Vector<unsigned char>*>(output);
-
-    if (mimeType == "image/jpeg") {
-        int compressionQuality = JPEGImageEncoder::DefaultCompressionQuality;
-        if (quality && *quality >= 0.0 && *quality <= 1.0)
-            compressionQuality = static_cast<int>(*quality * 100 + 0.5);
-        if (!JPEGImageEncoder::encode(source, compressionQuality, encodedImage))
-            return false;
-    } else if (mimeType == "image/webp") {
-        int compressionQuality = WEBPImageEncoder::DefaultCompressionQuality;
-        if (quality && *quality >= 0.0 && *quality <= 1.0)
-            compressionQuality = static_cast<int>(*quality * 100 + 0.5);
-        if (!WEBPImageEncoder::encode(source, compressionQuality, encodedImage))
-            return false;
-    } else {
-        if (!PNGImageEncoder::encode(source, encodedImage))
-            return false;
-        ASSERT(mimeType == "image/png");
-    }
-
-    return true;
-}
-
-String ImageBuffer::toDataURL(const String& mimeType, const double* quality, CoordinateSystem) const
-{
-    ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
-
-    Vector<char> encodedImage;
-    if (!encodeImage(*context()->bitmap(), mimeType, quality, &encodedImage))
-        return "data:,";
-
-    Vector<char> base64Data;
-    base64Encode(encodedImage, base64Data);
-
-    return "data:" + mimeType + ";base64," + base64Data;
-}
-
-void ImageBufferData::reportMemoryUsage(MemoryObjectInfo* memoryObjectInfo) const
-{
-    MemoryClassInfo info(memoryObjectInfo, this);
-    info.addMember(m_canvas, "canvas");
-    info.addMember(m_layerBridge, "layerBridge");
-}
-
-String ImageDataToDataURL(const ImageData& imageData, const String& mimeType, const double* quality)
-{
-    ASSERT(MIMETypeRegistry::isSupportedImageMIMETypeForEncoding(mimeType));
-
-    Vector<char> encodedImage;
-    if (!encodeImage(imageData, mimeType, quality, &encodedImage))
-        return "data:,";
-
-    Vector<char> base64Data;
-    base64Encode(encodedImage, base64Data);
-
-    return "data:" + mimeType + ";base64," + base64Data;
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/graphics/skia/ImageSkia.cpp b/Source/core/platform/graphics/skia/ImageSkia.cpp
index 2fb428b..5b13d69 100644
--- a/Source/core/platform/graphics/skia/ImageSkia.cpp
+++ b/Source/core/platform/graphics/skia/ImageSkia.cpp
@@ -312,7 +312,7 @@
     bool useBicubicFilter = resampling == RESAMPLE_AWESOME
         && DeferredImageDecoder::isLazyDecoded(bitmap.bitmap());
     if (useBicubicFilter)
-        paint.setFlags(paint.getFlags() | SkPaint::kBicubicFilterBitmap_Flag);
+        paint.setFlags(paint.getFlags() | SkPaint::kBicubicFilterBitmap_Flag | SkPaint::kFilterBitmap_Flag);
 
     if (resampling == RESAMPLE_AWESOME && !useBicubicFilter) {
         // Resample the image and then draw the result to canvas with bilinear
diff --git a/Source/core/platform/graphics/skia/NativeImageSkia.cpp b/Source/core/platform/graphics/skia/NativeImageSkia.cpp
index 6a64b35..bcb68cf 100644
--- a/Source/core/platform/graphics/skia/NativeImageSkia.cpp
+++ b/Source/core/platform/graphics/skia/NativeImageSkia.cpp
@@ -184,9 +184,4 @@
     info.addMember(m_cachedImageInfo, "cachedImageInfo");
 }
 
-void reportMemoryUsage(const NativeImageSkia* image, MemoryObjectInfo* memoryObjectInfo)
-{
-    image->reportMemoryUsage(memoryObjectInfo);
-}
-
 } // namespace WebCore
diff --git a/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp b/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp
index 3ac9849..81db97f 100644
--- a/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp
+++ b/Source/core/platform/graphics/skia/SimpleFontDataSkia.cpp
@@ -118,11 +118,6 @@
     }
 
     float lineGap = SkScalarToFloat(metrics.fLeading);
-#if OS(WINDOWS)
-    // FIXME: Windows code uses tmExternalLeading from TEXTMETRIC, SkPaint::FontMetrics does not seem to
-    // offer an equivalent. The formula below tries to proximate it based on fLeading.
-    lineGap = floorf(lineGap * 0.45);
-#endif
     m_fontMetrics.setLineGap(lineGap);
     m_fontMetrics.setLineSpacing(lroundf(ascent) + lroundf(descent) + lroundf(lineGap));
 
@@ -138,9 +133,14 @@
     // In WebKit/WebCore/platform/graphics/SimpleFontData.cpp, m_spaceWidth is
     // calculated for us, but we need to calculate m_maxCharWidth and
     // m_avgCharWidth in order for text entry widgets to be sized correctly.
-
+#if OS(WINDOWS)
+    m_maxCharWidth = SkScalarRound(metrics.fMaxCharWidth);
+#else
+    // FIXME: This seems incorrect and should probably use fMaxCharWidth as
+    // the code path above.
     SkScalar xRange = metrics.fXMax - metrics.fXMin;
     m_maxCharWidth = SkScalarRound(xRange * SkScalarRound(m_platformData.size()));
+#endif
 
     if (metrics.fAvgCharWidth)
         m_avgCharWidth = SkScalarRound(metrics.fAvgCharWidth);
diff --git a/Source/core/platform/image-decoders/ImageDecoder.cpp b/Source/core/platform/image-decoders/ImageDecoder.cpp
index 9eb1de3..fd2da24 100644
--- a/Source/core/platform/image-decoders/ImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/ImageDecoder.cpp
@@ -146,14 +146,6 @@
     if (m_frameBufferCache.size() <= 1)
         return 0;
 
-    // We need to preserve frames such that:
-    //  1. We don't clear |clearExceptFrame|;
-    //  2. We don't clear any frame from which a future initFrameBuffer() call
-    //     will copy bitmap data.
-    // All other frames can be cleared.
-    while ((clearExceptFrame < m_frameBufferCache.size()) && (m_frameBufferCache[clearExceptFrame].status() == ImageFrame::FrameEmpty))
-        clearExceptFrame = m_frameBufferCache[clearExceptFrame].requiredPreviousFrameIndex();
-
     size_t frameBytesCleared = 0;
     for (size_t i = 0; i < m_frameBufferCache.size(); ++i) {
         if (i != clearExceptFrame) {
diff --git a/Source/core/platform/image-decoders/ImageDecoder.h b/Source/core/platform/image-decoders/ImageDecoder.h
index 591548d..90195d4 100644
--- a/Source/core/platform/image-decoders/ImageDecoder.h
+++ b/Source/core/platform/image-decoders/ImageDecoder.h
@@ -77,6 +77,7 @@
         // These do not touch other metadata, only the raw pixel data.
         void clearPixelData();
         void zeroFillPixelData();
+        void zeroFillFrameRect(const IntRect&);
 
         // Makes this frame have an independent copy of the provided image's
         // pixel data, so that modifications in one frame are not reflected in
@@ -106,7 +107,7 @@
         // Returns a caller-owned pointer to the underlying native image data.
         // (Actual use: This pointer will be owned by BitmapImage and freed in
         // FrameData::clear()).
-        PassNativeImagePtr asNewNativeImage() const;
+        PassRefPtr<NativeImageSkia> asNewNativeImage() const;
 
         bool hasAlpha() const;
         const IntRect& originalFrameRect() const { return m_originalFrameRect; }
@@ -207,10 +208,9 @@
         RefPtr<NativeImageSkia> m_bitmap;
         SkBitmap::Allocator* m_allocator;
         bool m_hasAlpha;
-        IntRect m_originalFrameRect; // This will always just be the entire
-                                     // buffer except for GIF frames whose
-                                     // original rect was smaller than the
-                                     // overall image size.
+        // This will always just be the entire buffer except for GIF or WebP
+        // frames whose original rect was smaller than the overall image size.
+        IntRect m_originalFrameRect;
         FrameStatus m_status;
         unsigned m_duration;
         FrameDisposalMethod m_disposalMethod;
@@ -269,9 +269,9 @@
 
         // This will only differ from size() for ICO (where each frame is a
         // different icon) or other formats where different frames are different
-        // sizes.  This does NOT differ from size() for GIF, since decoding GIFs
-        // composites any smaller frames against previous frames to create full-
-        // size frames.
+        // sizes. This does NOT differ from size() for GIF or WebP, since
+        // decoding GIF or WebP composites any smaller frames against previous
+        // frames to create full-size frames.
         virtual IntSize frameSizeAtIndex(size_t) const
         {
             return size();
@@ -382,13 +382,11 @@
 
         bool failed() const { return m_failed; }
 
-        // Clears decoded pixel data from all frames except the provided frame,
-        // unless that frame has status FrameEmpty, in which case we instead
-        // preserve the most recent frame whose data is required in order to
-        // decode this frame. Callers may pass WTF::notFound to clear all frames.
-        //
+        // Clears decoded pixel data from all frames except the provided frame.
+        // Callers may pass WTF::notFound to clear all frames.
+        // Note: If |m_frameBufferCache| contains only one frame, it won't be cleared.
         // Returns the number of bytes of frame data actually cleared.
-        size_t clearCacheExceptFrame(size_t);
+        virtual size_t clearCacheExceptFrame(size_t);
 
         // If the image has a cursor hot-spot, stores it in the argument
         // and returns true. Otherwise returns false.
diff --git a/Source/core/platform/image-decoders/ImageDecoderTest.cpp b/Source/core/platform/image-decoders/ImageDecoderTest.cpp
index b8f2393..65dfe4d 100644
--- a/Source/core/platform/image-decoders/ImageDecoderTest.cpp
+++ b/Source/core/platform/image-decoders/ImageDecoderTest.cpp
@@ -186,31 +186,3 @@
             EXPECT_EQ(ImageFrame::FrameEmpty, decoderFrameBufferCache[i].status());
     }
 }
-
-TEST(ImageDecoderTest, clearCacheExceptFramePreverveRequiredFrame)
-{
-    const size_t numFrames = 10;
-    OwnPtr<TestImageDecoder> decoder(adoptPtr(new TestImageDecoder()));
-    decoder->initFrames(numFrames);
-    Vector<ImageFrame, 1>& decoderFrameBufferCache = decoder->frameBufferCache();
-    for (size_t i = 0; i < numFrames; ++i)
-        decoderFrameBufferCache[i].setStatus(ImageFrame::FrameComplete);
-
-    decoderFrameBufferCache[2].setStatus(ImageFrame::FrameComplete);
-    decoderFrameBufferCache[3].clearPixelData();
-    decoderFrameBufferCache[4].setDisposalMethod(ImageFrame::DisposeOverwritePrevious);
-    decoderFrameBufferCache[5].setDisposalMethod(ImageFrame::DisposeOverwritePrevious);
-    decoderFrameBufferCache[6].clearPixelData();
-    decoder->resetRequiredPreviousFrames();
-
-    // 6 which is empty requires 3 which is empty, and 3 requires 2 which is complete,
-    // so 2 will be required by the next request of 6 and needs to be preserved.
-    decoder->clearCacheExceptFrame(6);
-    for (size_t i = 0; i < numFrames; ++i) {
-        SCOPED_TRACE(testing::Message() << i);
-        if (i == 2)
-            EXPECT_EQ(ImageFrame::FrameComplete, decoderFrameBufferCache[i].status());
-        else
-            EXPECT_EQ(ImageFrame::FrameEmpty, decoderFrameBufferCache[i].status());
-    }
-}
diff --git a/Source/core/platform/image-decoders/skia/ImageDecoderSkia.cpp b/Source/core/platform/image-decoders/ImageFrame.cpp
similarity index 93%
rename from Source/core/platform/image-decoders/skia/ImageDecoderSkia.cpp
rename to Source/core/platform/image-decoders/ImageFrame.cpp
index 0c49900..6c9c073 100644
--- a/Source/core/platform/image-decoders/skia/ImageDecoderSkia.cpp
+++ b/Source/core/platform/image-decoders/ImageFrame.cpp
@@ -21,7 +21,7 @@
  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
 #include "config.h"
@@ -29,6 +29,7 @@
 
 #include "core/platform/PlatformMemoryInstrumentation.h"
 #include "core/platform/graphics/skia/NativeImageSkia.h"
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
@@ -113,7 +114,7 @@
     return true;
 }
 
-PassNativeImagePtr ImageFrame::asNewNativeImage() const
+PassRefPtr<NativeImageSkia> ImageFrame::asNewNativeImage() const
 {
     return m_bitmap->clone();
 }
@@ -151,4 +152,13 @@
     info.addMember(m_bitmap, "bitmap");
 }
 
+void ImageFrame::zeroFillFrameRect(const IntRect& rect)
+{
+    if (rect.isEmpty())
+        return;
+
+    m_bitmap->bitmap().eraseArea(rect, SkColorSetARGB(0, 0, 0, 0));
+    setHasAlpha(true);
+}
+
 } // namespace WebCore
diff --git a/Source/core/platform/image-decoders/OWNERS b/Source/core/platform/image-decoders/OWNERS
index 663da71..bf426d6 100644
--- a/Source/core/platform/image-decoders/OWNERS
+++ b/Source/core/platform/image-decoders/OWNERS
@@ -1 +1 @@
-pkasting@chromium.org
\ No newline at end of file
+pkasting@chromium.org
diff --git a/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp b/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp
index 2b5603b..9626d7b 100644
--- a/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp
@@ -134,6 +134,7 @@
     return ImageDecoder::setFailed();
 }
 
+// FIXME: Can the intermediate |rowBuffer| be avoided?
 bool GIFImageDecoder::haveDecodedRow(size_t frameIndex, const Vector<unsigned char>& rowBuffer, size_t width, size_t rowNumber, unsigned repeatCount, bool writeTransparentPixels)
 {
     const GIFFrameContext* frameContext = m_reader->frameContext(frameIndex);
@@ -242,6 +243,19 @@
     return true;
 }
 
+size_t GIFImageDecoder::clearCacheExceptFrame(size_t clearExceptFrame)
+{
+    // We need to preserve frames such that:
+    //  1. We don't clear |clearExceptFrame|;
+    //  2. We don't clear any frame from which a future initFrameBuffer() call
+    //     will copy bitmap data.
+    // All other frames can be cleared.
+    while ((clearExceptFrame < m_frameBufferCache.size()) && (m_frameBufferCache[clearExceptFrame].status() == ImageFrame::FrameEmpty))
+        clearExceptFrame = m_frameBufferCache[clearExceptFrame].requiredPreviousFrameIndex();
+
+    return ImageDecoder::clearCacheExceptFrame(clearExceptFrame);
+}
+
 void GIFImageDecoder::clearFrameBuffer(size_t frameIndex)
 {
     if (m_reader && m_frameBufferCache[frameIndex].status() == ImageFrame::FramePartial) {
@@ -305,13 +319,8 @@
         frameToDecode = m_frameBufferCache[frameToDecode].requiredPreviousFrameIndex();
     } while (frameToDecode != notFound && m_frameBufferCache[frameToDecode].status() != ImageFrame::FrameComplete);
 
-    // The |rend| variable is needed by some compilers that can't correctly
-    // select from const and non-const versions of overloaded functions.
-    // Can remove the variable if Android compiler can compile
-    // 'iter != framesToDecode.rend()'.
-    Vector<size_t>::const_reverse_iterator rend = framesToDecode.rend();
-    for (Vector<size_t>::const_reverse_iterator iter = framesToDecode.rbegin(); iter != rend; ++iter) {
-        size_t frameIndex = *iter;
+    for (size_t i = framesToDecode.size(); i > 0; --i) {
+        size_t frameIndex = framesToDecode[i - 1];
         if (!m_reader->decode(frameIndex)) {
             setFailed();
             return;
@@ -352,12 +361,7 @@
             // affecting pixels in the image outside of the frame.
             const IntRect& prevRect = prevBuffer->originalFrameRect();
             ASSERT(!prevRect.contains(IntRect(IntPoint(), size())));
-            for (int y = prevRect.y(); y < prevRect.maxY(); ++y) {
-                for (int x = prevRect.x(); x < prevRect.maxX(); ++x)
-                    buffer->setRGBA(x, y, 0, 0, 0, 0);
-            }
-            if ((prevRect.width() > 0) && (prevRect.height() > 0))
-                buffer->setHasAlpha(true);
+            buffer->zeroFillFrameRect(prevRect);
         }
     }
 
diff --git a/Source/core/platform/image-decoders/gif/GIFImageDecoder.h b/Source/core/platform/image-decoders/gif/GIFImageDecoder.h
index 769cde1..3159b7b 100644
--- a/Source/core/platform/image-decoders/gif/GIFImageDecoder.h
+++ b/Source/core/platform/image-decoders/gif/GIFImageDecoder.h
@@ -50,6 +50,7 @@
         virtual ImageFrame* frameBufferAtIndex(size_t) OVERRIDE;
         virtual bool frameIsCompleteAtIndex(size_t) const OVERRIDE;
         virtual float frameDurationAtIndex(size_t) const OVERRIDE;
+        virtual size_t clearCacheExceptFrame(size_t) OVERRIDE;
         // CAUTION: setFailed() deletes |m_reader|.  Be careful to avoid
         // accessing deleted memory, especially when calling this from inside
         // GIFImageReader!
diff --git a/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp b/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp
index 26171f5..5e559e4 100644
--- a/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp
+++ b/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp
@@ -31,19 +31,12 @@
 
 #include "core/platform/PlatformInstrumentation.h"
 
-#ifdef QCMS_WEBP_COLOR_CORRECTION
+#if USE(QCMSLIB)
 #include "qcms.h"
-#include "webp/demux.h"
-#else
-#undef ICCP_FLAG
-#define ICCP_FLAG 0
 #endif
 
-// Backward emulation for earlier versions than 0.1.99.
-#if (WEBP_DECODER_ABI_VERSION < 0x0163)
-#define MODE_rgbA MODE_RGBA
-#define MODE_bgrA MODE_BGRA
-#endif
+#include "RuntimeEnabledFeatures.h"
+#include "webp/format_constants.h"
 
 #if CPU(BIG_ENDIAN) || CPU(MIDDLE_ENDIAN)
 inline WEBP_CSP_MODE outputMode(bool hasAlpha) { return hasAlpha ? MODE_rgbA : MODE_RGBA; }
@@ -59,15 +52,19 @@
                                    ImageSource::GammaAndColorProfileOption gammaAndColorProfileOption)
     : ImageDecoder(alphaOption, gammaAndColorProfileOption)
     , m_decoder(0)
-    , m_hasAlpha(false)
     , m_formatFlags(0)
-#ifdef QCMS_WEBP_COLOR_CORRECTION
+    , m_frameBackgroundHasAlpha(false)
+#if USE(QCMSLIB)
     , m_haveReadProfile(false)
     , m_transform(0)
-    , m_decodedHeight(0)
 #endif
+    , m_demux(0)
+    , m_demuxState(WEBP_DEMUX_PARSING_HEADER)
+    , m_haveAlreadyParsedThisData(false)
+    , m_haveReadAnimationParameters(false)
+    , m_repetitionCount(cAnimationLoopOnce)
+    , m_decodedHeight(0)
 {
-    WebPInitDecBuffer(&m_decoderBuffer);
 }
 
 WEBPImageDecoder::~WEBPImageDecoder()
@@ -77,45 +74,256 @@
 
 void WEBPImageDecoder::clear()
 {
-#ifdef QCMS_WEBP_COLOR_CORRECTION
+#if USE(QCMSLIB)
     if (m_transform)
         qcms_transform_release(m_transform);
     m_transform = 0;
 #endif
-    WebPFreeDecBuffer(&m_decoderBuffer);
-    if (m_decoder)
-        WebPIDelete(m_decoder);
+    WebPDemuxDelete(m_demux);
+    m_demux = 0;
+    clearDecoder();
+}
+
+void WEBPImageDecoder::clearDecoder()
+{
+    WebPIDelete(m_decoder);
     m_decoder = 0;
+    m_decodedHeight = 0;
+    m_frameBackgroundHasAlpha = false;
 }
 
 bool WEBPImageDecoder::isSizeAvailable()
 {
-    if (!ImageDecoder::isSizeAvailable())
-         decode(true);
-
+    if (!ImageDecoder::isSizeAvailable()) {
+        updateDemuxer();
+    }
     return ImageDecoder::isSizeAvailable();
 }
 
+size_t WEBPImageDecoder::frameCount()
+{
+    if (!updateDemuxer())
+        return 0;
+    return m_frameBufferCache.size();
+}
+
 ImageFrame* WEBPImageDecoder::frameBufferAtIndex(size_t index)
 {
-    if (index)
+    if (index >= frameCount())
         return 0;
 
-    if (m_frameBufferCache.isEmpty()) {
-        m_frameBufferCache.resize(1);
-        m_frameBufferCache[0].setPremultiplyAlpha(m_premultiplyAlpha);
+    ImageFrame& frame = m_frameBufferCache[index];
+    if (frame.status() == ImageFrame::FrameComplete)
+        return &frame;
+
+    if (RuntimeEnabledFeatures::animatedWebPEnabled()) {
+        Vector<size_t> framesToDecode;
+        size_t frameToDecode = index;
+        do {
+            framesToDecode.append(frameToDecode);
+            frameToDecode = m_frameBufferCache[frameToDecode].requiredPreviousFrameIndex();
+        } while (frameToDecode != notFound && m_frameBufferCache[frameToDecode].status() != ImageFrame::FrameComplete);
+
+        ASSERT(m_demux);
+        for (size_t i = framesToDecode.size(); i > 0; --i) {
+            size_t frameIndex = framesToDecode[i - 1];
+            WebPIterator webpFrame;
+            if (!WebPDemuxGetFrame(m_demux, frameIndex + 1, &webpFrame))
+                return 0;
+            if ((m_formatFlags & ANIMATION_FLAG) && !initFrameBuffer(webpFrame, frameIndex)) {
+                WebPDemuxReleaseIterator(&webpFrame);
+                return 0;
+            }
+            PlatformInstrumentation::willDecodeImage("WEBP");
+            decode(webpFrame.fragment.bytes, webpFrame.fragment.size, false, frameIndex);
+            PlatformInstrumentation::didDecodeImage();
+            WebPDemuxReleaseIterator(&webpFrame);
+
+            // We need more data to continue decoding.
+            if (m_frameBufferCache[frameIndex].status() != ImageFrame::FrameComplete)
+                break;
+        }
+
+        // It is also a fatal error if all data is received and we have decoded all
+        // frames available but the file is truncated.
+        if (index >= m_frameBufferCache.size() - 1 && isAllDataReceived() && m_demux && m_demuxState != WEBP_DEMUX_DONE)
+            setFailed();
+
+        return &frame;
     }
 
-    ImageFrame& frame = m_frameBufferCache[0];
-    if (frame.status() != ImageFrame::FrameComplete) {
-        PlatformInstrumentation::willDecodeImage("WEBP");
-        decode(false);
-        PlatformInstrumentation::didDecodeImage();
-    }
+    ASSERT(!index);
+    PlatformInstrumentation::willDecodeImage("WEBP");
+    decode(reinterpret_cast<const uint8_t*>(m_data->data()), m_data->size(), false, index);
+    PlatformInstrumentation::didDecodeImage();
     return &frame;
 }
 
-#ifdef QCMS_WEBP_COLOR_CORRECTION
+void WEBPImageDecoder::setData(SharedBuffer* data, bool allDataReceived)
+{
+    if (failed())
+        return;
+
+    ImageDecoder::setData(data, allDataReceived);
+
+    if (m_demuxState != WEBP_DEMUX_DONE)
+        m_haveAlreadyParsedThisData = false;
+}
+
+int WEBPImageDecoder::repetitionCount() const
+{
+    return failed() ? cAnimationLoopOnce : m_repetitionCount;
+}
+
+bool WEBPImageDecoder::frameIsCompleteAtIndex(size_t index) const
+{
+    if (!RuntimeEnabledFeatures::animatedWebPEnabled())
+        return ImageDecoder::frameIsCompleteAtIndex(index);
+    if (!m_demux || m_demuxState <= WEBP_DEMUX_PARSING_HEADER)
+        return false;
+    if (!(m_formatFlags & ANIMATION_FLAG))
+        return ImageDecoder::frameIsCompleteAtIndex(index);
+    bool frameIsLoadedAtIndex = index < m_frameBufferCache.size();
+    return frameIsLoadedAtIndex;
+}
+
+float WEBPImageDecoder::frameDurationAtIndex(size_t index) const
+{
+    return index < m_frameBufferCache.size() ? m_frameBufferCache[index].duration() : 0;
+}
+
+bool WEBPImageDecoder::updateDemuxer()
+{
+    if (m_haveAlreadyParsedThisData)
+        return true;
+
+    m_haveAlreadyParsedThisData = true;
+
+    if (m_data->size() < RIFF_HEADER_SIZE + CHUNK_HEADER_SIZE)
+        return false; // Wait for headers so that WebPDemuxPartial doesn't return null.
+
+    WebPDemuxDelete(m_demux);
+    WebPData inputData = { reinterpret_cast<const uint8_t*>(m_data->data()), m_data->size() };
+    m_demux = WebPDemuxPartial(&inputData, &m_demuxState);
+    if (!m_demux)
+        return setFailed();
+
+    if (m_demuxState <= WEBP_DEMUX_PARSING_HEADER)
+        return false; // Not enough data for parsing canvas width/height yet.
+
+    bool hasAnimation = (m_formatFlags & ANIMATION_FLAG);
+    if (!ImageDecoder::isSizeAvailable()) {
+        m_formatFlags = WebPDemuxGetI(m_demux, WEBP_FF_FORMAT_FLAGS);
+        hasAnimation = (m_formatFlags & ANIMATION_FLAG);
+        if (hasAnimation && !RuntimeEnabledFeatures::animatedWebPEnabled())
+            return setFailed();
+        if (!setSize(WebPDemuxGetI(m_demux, WEBP_FF_CANVAS_WIDTH), WebPDemuxGetI(m_demux, WEBP_FF_CANVAS_HEIGHT)))
+            return setFailed();
+    }
+    ASSERT(ImageDecoder::isSizeAvailable());
+    const size_t newFrameCount = WebPDemuxGetI(m_demux, WEBP_FF_FRAME_COUNT);
+    if (hasAnimation && !m_haveReadAnimationParameters && newFrameCount) {
+        // As we have parsed at least one frame (even if partially),
+        // we must already have parsed the animation properties.
+        // This is because ANIM chunk always precedes ANMF chunks.
+        m_repetitionCount = WebPDemuxGetI(m_demux, WEBP_FF_LOOP_COUNT);
+        ASSERT(m_repetitionCount == (m_repetitionCount & 0xffff)); // Loop count is always <= 16 bits.
+        if (!m_repetitionCount)
+            m_repetitionCount = cAnimationLoopInfinite;
+        m_haveReadAnimationParameters = true;
+    }
+    const size_t oldFrameCount = m_frameBufferCache.size();
+    if (newFrameCount > oldFrameCount) {
+        m_frameBufferCache.resize(newFrameCount);
+        for (size_t i = oldFrameCount; i < newFrameCount; ++i) {
+            m_frameBufferCache[i].setPremultiplyAlpha(m_premultiplyAlpha);
+            if (!hasAnimation) {
+                ASSERT(!i);
+                m_frameBufferCache[i].setRequiredPreviousFrameIndex(notFound);
+                continue;
+            }
+            WebPIterator animatedFrame;
+            WebPDemuxGetFrame(m_demux, i + 1, &animatedFrame);
+            ASSERT(animatedFrame.complete == 1);
+            m_frameBufferCache[i].setDuration(animatedFrame.duration);
+            m_frameBufferCache[i].setDisposalMethod(animatedFrame.dispose_method == WEBP_MUX_DISPOSE_BACKGROUND ? ImageFrame::DisposeOverwriteBgcolor : ImageFrame::DisposeKeep);
+            WebPDemuxReleaseIterator(&animatedFrame);
+            m_frameBufferCache[i].setRequiredPreviousFrameIndex(findRequiredPreviousFrame(i));
+        }
+    }
+    return true;
+}
+
+bool WEBPImageDecoder::initFrameBuffer(const WebPIterator& frame, size_t frameIndex)
+{
+    ImageFrame& buffer = m_frameBufferCache[frameIndex];
+    if (buffer.status() != ImageFrame::FrameEmpty) // Already initialized.
+        return true;
+
+    // Initialize the frame rect in our buffer.
+    IntRect frameRect(frame.x_offset, frame.y_offset, frame.width, frame.height);
+
+    // Make sure the frameRect doesn't extend outside the buffer.
+    if (frameRect.maxX() > size().width())
+        frameRect.setWidth(size().width() - frame.x_offset);
+    if (frameRect.maxY() > size().height())
+        frameRect.setHeight(size().height() - frame.y_offset);
+    buffer.setOriginalFrameRect(frameRect);
+
+    const size_t requiredPreviousFrameIndex = buffer.requiredPreviousFrameIndex();
+    if (requiredPreviousFrameIndex == notFound) {
+        // This frame doesn't rely on any previous data.
+        if (!buffer.setSize(size().width(), size().height()))
+            return setFailed();
+        m_frameBackgroundHasAlpha = !frameRect.contains(IntRect(IntPoint(), size()));
+    } else {
+        const ImageFrame& prevBuffer = m_frameBufferCache[requiredPreviousFrameIndex];
+        ASSERT(prevBuffer.status() == ImageFrame::FrameComplete);
+
+        // Preserve the last frame as the starting state for this frame.
+        if (!buffer.copyBitmapData(prevBuffer))
+            return setFailed();
+
+        if (prevBuffer.disposalMethod() == ImageFrame::DisposeOverwriteBgcolor) {
+            // We want to clear the previous frame to transparent, without
+            // affecting pixels in the image outside of the frame.
+            const IntRect& prevRect = prevBuffer.originalFrameRect();
+            ASSERT(!prevRect.contains(IntRect(IntPoint(), size())));
+            buffer.zeroFillFrameRect(prevRect);
+        }
+
+        m_frameBackgroundHasAlpha = prevBuffer.hasAlpha() || (prevBuffer.disposalMethod() == ImageFrame::DisposeOverwriteBgcolor);
+    }
+
+    buffer.setStatus(ImageFrame::FramePartial);
+    // The buffer is transparent outside the decoded area while the image is loading.
+    // The correct value of 'hasAlpha' for the frame will be set when it is fully decoded.
+    buffer.setHasAlpha(true);
+    return true;
+}
+
+size_t WEBPImageDecoder::clearCacheExceptFrame(size_t clearExceptFrame)
+{
+    // If |clearExceptFrame| has status FrameComplete, we preserve that frame.
+    // Otherwise, we preserve a previous frame with status FrameComplete whose data is required
+    // to decode |clearExceptFrame|, either in initFrameBuffer() or ApplyPostProcessing().
+    // All other frames can be cleared.
+    while ((clearExceptFrame < m_frameBufferCache.size()) && (m_frameBufferCache[clearExceptFrame].status() != ImageFrame::FrameComplete))
+        clearExceptFrame = m_frameBufferCache[clearExceptFrame].requiredPreviousFrameIndex();
+
+    return ImageDecoder::clearCacheExceptFrame(clearExceptFrame);
+}
+
+void WEBPImageDecoder::clearFrameBuffer(size_t frameIndex)
+{
+    if (m_demux && m_demuxState >= WEBP_DEMUX_PARSED_HEADER && m_frameBufferCache[frameIndex].status() == ImageFrame::FramePartial) {
+        // Clear the decoder state so that this partial frame can be decoded again when requested.
+        clearDecoder();
+    }
+    ImageDecoder::clearFrameBuffer(frameIndex);
+}
+
+#if USE(QCMSLIB)
 
 void WEBPImageDecoder::createColorTransform(const char* data, size_t size)
 {
@@ -140,16 +348,11 @@
     qcms_profile_release(inputProfile);
 }
 
-void WEBPImageDecoder::readColorProfile(const uint8_t* data, size_t size)
+void WEBPImageDecoder::readColorProfile()
 {
     WebPChunkIterator chunkIterator;
-    WebPData inputData = { data, size };
-    WebPDemuxState state;
-
-    WebPDemuxer* demuxer = WebPDemuxPartial(&inputData, &state);
-    if (!WebPDemuxGetChunk(demuxer, "ICCP", 1, &chunkIterator)) {
+    if (!WebPDemuxGetChunk(m_demux, "ICCP", 1, &chunkIterator)) {
         WebPDemuxReleaseChunkIterator(&chunkIterator);
-        WebPDemuxDelete(demuxer);
         return;
     }
 
@@ -169,11 +372,13 @@
         createColorTransform(profileData, profileSize);
 
     WebPDemuxReleaseChunkIterator(&chunkIterator);
-    WebPDemuxDelete(demuxer);
 }
 
-void WEBPImageDecoder::applyColorProfile(const uint8_t* data, size_t dataSize, ImageFrame& buffer)
+#endif // USE(QCMSLIB)
+
+void WEBPImageDecoder::applyPostProcessing(size_t frameIndex)
 {
+    ImageFrame& buffer = m_frameBufferCache[frameIndex];
     int width;
     int decodedHeight;
     if (!WebPIDecGetRGB(m_decoder, &decodedHeight, &width, 0, 0))
@@ -181,69 +386,97 @@
     if (decodedHeight <= 0)
         return;
 
-    if (!m_haveReadProfile) {
-        readColorProfile(data, dataSize);
-        m_haveReadProfile = true;
+    const IntRect& frameRect = buffer.originalFrameRect();
+    ASSERT_WITH_SECURITY_IMPLICATION(width == frameRect.width());
+    ASSERT_WITH_SECURITY_IMPLICATION(decodedHeight <= frameRect.height());
+    const int left = frameRect.x();
+    const int top = frameRect.y();
+
+#if USE(QCMSLIB)
+    if ((m_formatFlags & ICCP_FLAG) && !ignoresGammaAndColorProfile()) {
+        if (!m_haveReadProfile) {
+            readColorProfile();
+            m_haveReadProfile = true;
+        }
+        for (int y = m_decodedHeight; y < decodedHeight; ++y) {
+            const int canvasY = top + y;
+            uint8_t* row = reinterpret_cast<uint8_t*>(buffer.getAddr(left, canvasY));
+            if (qcms_transform* transform = colorTransform())
+                qcms_transform_data_type(transform, row, row, width, QCMS_OUTPUT_RGBX);
+            uint8_t* pixel = row;
+            for (int x = 0; x < width; ++x, pixel += 4) {
+                const int canvasX = left + x;
+                buffer.setRGBA(canvasX, canvasY, pixel[0], pixel[1], pixel[2], pixel[3]);
+            }
+        }
     }
+#endif // USE(QCMSLIB)
 
-    ASSERT(width == size().width());
-    ASSERT(decodedHeight <= size().height());
-
-    for (int y = m_decodedHeight; y < decodedHeight; ++y) {
-        uint8_t* row = reinterpret_cast<uint8_t*>(buffer.getAddr(0, y));
-        if (qcms_transform* transform = colorTransform())
-            qcms_transform_data_type(transform, row, row, width, QCMS_OUTPUT_RGBX);
-        uint8_t* pixel = row;
-        for (int x = 0; x < width; ++x, pixel += 4)
-            buffer.setRGBA(x, y, pixel[0], pixel[1], pixel[2], pixel[3]);
+    // During the decoding of current frame, we may have set some pixels to be transparent (i.e. alpha < 255).
+    // However, the value of each of these pixels should have been determined by blending it against the value
+    // of that pixel in the previous frame. So, we correct these pixels based on disposal method of the previous
+    // frame and the previous frame buffer.
+    // FIXME: This could be avoided if libwebp decoder had an API that used the previous required frame
+    // to do the alpha-blending by itself.
+    if ((m_formatFlags & ANIMATION_FLAG) && frameIndex) {
+        ImageFrame& prevBuffer = m_frameBufferCache[frameIndex - 1];
+        ImageFrame::FrameDisposalMethod prevMethod = prevBuffer.disposalMethod();
+        if (prevMethod == ImageFrame::DisposeKeep) { // Restore transparent pixels to pixels in previous canvas.
+            ASSERT(prevBuffer.status() == ImageFrame::FrameComplete);
+            for (int y = m_decodedHeight; y < decodedHeight; ++y) {
+                const int canvasY = top + y;
+                for (int x = 0; x < width; ++x) {
+                    const int canvasX = left + x;
+                    ImageFrame::PixelData& pixel = *buffer.getAddr(canvasX, canvasY);
+                    // FIXME: Use alpha-blending when alpha is between 0 and 255.
+                    // Alpha-blending is being implemented in: https://bugs.webkit.org/show_bug.cgi?id=17022
+                    if (!((pixel >> SK_A32_SHIFT) & 0xff)) {
+                        ImageFrame::PixelData prevPixel = *prevBuffer.getAddr(canvasX, canvasY);
+                        pixel = prevPixel;
+                    }
+                }
+            }
+        } else if (prevMethod == ImageFrame::DisposeOverwriteBgcolor && buffer.requiredPreviousFrameIndex() != notFound) {
+            // Note: if the requiredPreviousFrameIndex is |notFound|, there's nothing to do.
+            ASSERT(prevBuffer.status() == ImageFrame::FrameComplete);
+            const IntRect& prevRect = prevBuffer.originalFrameRect();
+            // We need to restore transparent pixels to as they were just after initFrame() call. That is:
+            //   * Transparent if it belongs to prevRect <-- This is a no-op.
+            //   * Pixel in the previous canvas otherwise <-- Need to restore.
+            for (int y = m_decodedHeight; y < decodedHeight; ++y) {
+                const int canvasY = top + y;
+                for (int x = 0; x < width; ++x) {
+                    const int canvasX = left + x;
+                    ImageFrame::PixelData& pixel = *buffer.getAddr(canvasX, canvasY);
+                    // FIXME: Use alpha-blending when alpha is between 0 and 255.
+                    if (!((pixel >> SK_A32_SHIFT) & 0xff) && !prevRect.contains(IntPoint(canvasX, canvasY))) {
+                        ImageFrame::PixelData prevPixel = *prevBuffer.getAddr(canvasX, canvasY);
+                        pixel = prevPixel;
+                    }
+                }
+            }
+        }
     }
 
     m_decodedHeight = decodedHeight;
 }
 
-#endif // QCMS_WEBP_COLOR_CORRECTION
-
-bool WEBPImageDecoder::decode(bool onlySize)
+bool WEBPImageDecoder::decode(const uint8_t* dataBytes, size_t dataSize, bool onlySize, size_t frameIndex)
 {
     if (failed())
         return false;
 
-    const uint8_t* dataBytes = reinterpret_cast<const uint8_t*>(m_data->data());
-    const size_t dataSize = m_data->size();
-
     if (!ImageDecoder::isSizeAvailable()) {
         static const size_t imageHeaderSize = 30;
         if (dataSize < imageHeaderSize)
             return false;
         int width, height;
-#ifdef QCMS_WEBP_COLOR_CORRECTION
-        WebPData inputData = { dataBytes, dataSize };
-        WebPDemuxState state;
-        WebPDemuxer* demuxer = WebPDemuxPartial(&inputData, &state);
-        if (!demuxer)
-            return setFailed();
-
-        width = WebPDemuxGetI(demuxer, WEBP_FF_CANVAS_WIDTH);
-        height = WebPDemuxGetI(demuxer, WEBP_FF_CANVAS_HEIGHT);
-        m_formatFlags = WebPDemuxGetI(demuxer, WEBP_FF_FORMAT_FLAGS);
-        m_hasAlpha = !!(m_formatFlags & ALPHA_FLAG);
-
-        WebPDemuxDelete(demuxer);
-        if (state <= WEBP_DEMUX_PARSING_HEADER)
-            return false;
-#elif (WEBP_DECODER_ABI_VERSION >= 0x0163)
         WebPBitstreamFeatures features;
         if (WebPGetFeatures(dataBytes, dataSize, &features) != VP8_STATUS_OK)
             return setFailed();
         width = features.width;
         height = features.height;
-        m_hasAlpha = features.has_alpha;
-#else
-        // Earlier version won't be able to display WebP files with alpha.
-        if (!WebPGetInfo(dataBytes, dataSize, &width, &height))
-            return setFailed();
-        m_hasAlpha = false;
-#endif
+        m_formatFlags = features.has_alpha ? ALPHA_FLAG : 0;
         if (!setSize(width, height))
             return setFailed();
     }
@@ -252,48 +485,53 @@
     if (onlySize)
         return true;
 
-    ASSERT(!m_frameBufferCache.isEmpty());
-    ImageFrame& buffer = m_frameBufferCache[0];
+    ASSERT(m_frameBufferCache.size() > frameIndex);
+    ImageFrame& buffer = m_frameBufferCache[frameIndex];
     ASSERT(buffer.status() != ImageFrame::FrameComplete);
 
     if (buffer.status() == ImageFrame::FrameEmpty) {
         if (!buffer.setSize(size().width(), size().height()))
             return setFailed();
         buffer.setStatus(ImageFrame::FramePartial);
-        buffer.setHasAlpha(m_hasAlpha);
+        // The buffer is transparent outside the decoded area while the image is loading.
+        // The correct value of 'hasAlpha' for the frame will be set when it is fully decoded.
+        buffer.setHasAlpha(true);
         buffer.setOriginalFrameRect(IntRect(IntPoint(), size()));
     }
 
+    const IntRect& frameRect = buffer.originalFrameRect();
     if (!m_decoder) {
-        WEBP_CSP_MODE mode = outputMode(m_hasAlpha);
+        WEBP_CSP_MODE mode = outputMode(m_formatFlags & ALPHA_FLAG);
         if (!m_premultiplyAlpha)
             mode = outputMode(false);
+#if USE(QCMSLIB)
         if ((m_formatFlags & ICCP_FLAG) && !ignoresGammaAndColorProfile())
             mode = MODE_RGBA; // Decode to RGBA for input to libqcms.
+#endif
+        WebPInitDecBuffer(&m_decoderBuffer);
         m_decoderBuffer.colorspace = mode;
         m_decoderBuffer.u.RGBA.stride = size().width() * sizeof(ImageFrame::PixelData);
-        m_decoderBuffer.u.RGBA.size = m_decoderBuffer.u.RGBA.stride * size().height();
+        m_decoderBuffer.u.RGBA.size = m_decoderBuffer.u.RGBA.stride * frameRect.height();
         m_decoderBuffer.is_external_memory = 1;
         m_decoder = WebPINewDecoder(&m_decoderBuffer);
         if (!m_decoder)
             return setFailed();
     }
 
-    m_decoderBuffer.u.RGBA.rgba = reinterpret_cast<uint8_t*>(buffer.getAddr(0, 0));
+    m_decoderBuffer.u.RGBA.rgba = reinterpret_cast<uint8_t*>(buffer.getAddr(frameRect.x(), frameRect.y()));
 
     switch (WebPIUpdate(m_decoder, dataBytes, dataSize)) {
     case VP8_STATUS_OK:
-        if ((m_formatFlags & ICCP_FLAG) && !ignoresGammaAndColorProfile()) 
-            applyColorProfile(dataBytes, dataSize, buffer);
+        applyPostProcessing(frameIndex);
+        buffer.setHasAlpha((m_formatFlags & ALPHA_FLAG) || m_frameBackgroundHasAlpha);
         buffer.setStatus(ImageFrame::FrameComplete);
-        clear();
+        clearDecoder();
         return true;
     case VP8_STATUS_SUSPENDED:
-        if ((m_formatFlags & ICCP_FLAG) && !ignoresGammaAndColorProfile()) 
-            applyColorProfile(dataBytes, dataSize, buffer);
+        applyPostProcessing(frameIndex);
         return false;
     default:
-        clear();                         
+        clear();
         return setFailed();
     }
 }
diff --git a/Source/core/platform/image-decoders/webp/WEBPImageDecoder.h b/Source/core/platform/image-decoders/webp/WEBPImageDecoder.h
index 5e7e2d8..8d6f4b8 100644
--- a/Source/core/platform/image-decoders/webp/WEBPImageDecoder.h
+++ b/Source/core/platform/image-decoders/webp/WEBPImageDecoder.h
@@ -32,9 +32,7 @@
 #include "core/platform/image-decoders/ImageDecoder.h"
 
 #include "webp/decode.h"
-#if USE(QCMSLIB) && (WEBP_DECODER_ABI_VERSION > 0x200)
-#define QCMS_WEBP_COLOR_CORRECTION
-#endif
+#include "webp/demux.h"
 
 namespace WebCore {
 
@@ -43,31 +41,47 @@
     WEBPImageDecoder(ImageSource::AlphaOption, ImageSource::GammaAndColorProfileOption);
     virtual ~WEBPImageDecoder();
 
-    virtual String filenameExtension() const { return "webp"; }
-    virtual bool isSizeAvailable();
-    virtual ImageFrame* frameBufferAtIndex(size_t);
+    virtual String filenameExtension() const OVERRIDE { return "webp"; }
+    virtual bool isSizeAvailable() OVERRIDE;
+    virtual size_t frameCount() OVERRIDE;
+    virtual ImageFrame* frameBufferAtIndex(size_t) OVERRIDE;
+    virtual void setData(SharedBuffer* data, bool allDataReceived) OVERRIDE;
+    virtual int repetitionCount() const OVERRIDE;
+    virtual bool frameIsCompleteAtIndex(size_t) const OVERRIDE;
+    virtual float frameDurationAtIndex(size_t) const OVERRIDE;
+    virtual size_t clearCacheExceptFrame(size_t) OVERRIDE;
 
 private:
-    bool decode(bool onlySize);
+    bool decode(const uint8_t* dataBytes, size_t dataSize, bool onlySize, size_t frameIndex);
 
     WebPIDecoder* m_decoder;
     WebPDecBuffer m_decoderBuffer;
-    bool m_hasAlpha;
     int m_formatFlags;
+    bool m_frameBackgroundHasAlpha;
 
-#ifdef QCMS_WEBP_COLOR_CORRECTION
+#if USE(QCMSLIB)
     qcms_transform* colorTransform() const { return m_transform; }
     void createColorTransform(const char* data, size_t);
-    void readColorProfile(const uint8_t* data, size_t);
-    void applyColorProfile(const uint8_t* data, size_t, ImageFrame&);
+    void readColorProfile();
 
     bool m_haveReadProfile;
     qcms_transform* m_transform;
-    int m_decodedHeight;
-#else
-    void applyColorProfile(const uint8_t*, size_t, ImageFrame&) { };
 #endif
+
+    bool updateDemuxer();
+    bool initFrameBuffer(const WebPIterator&, size_t frameIndex);
+    void applyPostProcessing(size_t frameIndex);
+    virtual void clearFrameBuffer(size_t frameIndex) OVERRIDE;
+
+    WebPDemuxer* m_demux;
+    WebPDemuxState m_demuxState;
+    bool m_haveAlreadyParsedThisData;
+    bool m_haveReadAnimationParameters;
+    int m_repetitionCount;
+    int m_decodedHeight;
+
     void clear();
+    void clearDecoder();
 };
 
 } // namespace WebCore
diff --git a/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp b/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
new file mode 100644
index 0000000..da9ee8e
--- /dev/null
+++ b/Source/core/platform/image-decoders/webp/WEBPImageDecoderTest.cpp
@@ -0,0 +1,446 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+
+#include "core/platform/image-decoders/webp/WEBPImageDecoder.h"
+
+#include "RuntimeEnabledFeatures.h"
+#include "core/platform/FileSystem.h"
+#include "core/platform/SharedBuffer.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebData.h"
+#include "public/platform/WebSize.h"
+#include "public/platform/WebUnitTestSupport.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/StringHasher.h"
+#include "wtf/Vector.h"
+#include "wtf/dtoa/utils.h"
+#include <gtest/gtest.h>
+
+using namespace WebCore;
+using namespace WebKit;
+
+#if !OS(ANDROID)
+
+namespace {
+
+PassRefPtr<SharedBuffer> readFile(const char* fileName)
+{
+    String filePath = Platform::current()->unitTestSupport()->webKitRootDir();
+    filePath.append(fileName);
+
+    long long fileSize;
+    if (!getFileSize(filePath, fileSize))
+        return 0;
+
+    PlatformFileHandle handle = openFile(filePath, OpenForRead);
+    int fileLength = static_cast<int>(fileSize);
+    Vector<char> buffer(fileLength);
+    readFromFile(handle, buffer.data(), fileLength);
+    closeFile(handle);
+    return SharedBuffer::adoptVector(buffer);
+}
+
+PassOwnPtr<WEBPImageDecoder> createDecoder()
+{
+    return adoptPtr(new WEBPImageDecoder(ImageSource::AlphaNotPremultiplied, ImageSource::GammaAndColorProfileApplied));
+}
+
+unsigned hashSkBitmap(const SkBitmap& bitmap)
+{
+    return StringHasher::hashMemory(bitmap.getPixels(), bitmap.getSize());
+}
+
+void createDecodingBaseline(SharedBuffer* data, Vector<unsigned>* baselineHashes)
+{
+    OwnPtr<WEBPImageDecoder> decoder = createDecoder();
+    decoder->setData(data, true);
+    size_t frameCount = decoder->frameCount();
+    for (size_t i = 0; i < frameCount; ++i) {
+        ImageFrame* frame = decoder->frameBufferAtIndex(i);
+        baselineHashes->append(hashSkBitmap(frame->getSkBitmap()));
+    }
+}
+
+void testRandomFrameDecode(const char* webpFile)
+{
+    SCOPED_TRACE(webpFile);
+
+    RefPtr<SharedBuffer> fullData = readFile(webpFile);
+    ASSERT_TRUE(fullData.get());
+    Vector<unsigned> baselineHashes;
+    createDecodingBaseline(fullData.get(), &baselineHashes);
+    size_t frameCount = baselineHashes.size();
+
+    // Random decoding should get the same results as sequential decoding.
+    OwnPtr<WEBPImageDecoder> decoder = createDecoder();
+    decoder->setData(fullData.get(), true);
+    const size_t skippingStep = 5;
+    for (size_t i = 0; i < skippingStep; ++i) {
+        for (size_t j = i; j < frameCount; j += skippingStep) {
+            SCOPED_TRACE(testing::Message() << "Random i:" << i << " j:" << j);
+            ImageFrame* frame = decoder->frameBufferAtIndex(j);
+            EXPECT_EQ(baselineHashes[j], hashSkBitmap(frame->getSkBitmap()));
+        }
+    }
+
+    // Decoding in reverse order.
+    decoder = createDecoder();
+    decoder->setData(fullData.get(), true);
+    for (size_t i = frameCount; i; --i) {
+        SCOPED_TRACE(testing::Message() << "Reverse i:" << i);
+        ImageFrame* frame = decoder->frameBufferAtIndex(i - 1);
+        EXPECT_EQ(baselineHashes[i - 1], hashSkBitmap(frame->getSkBitmap()));
+    }
+}
+
+void testRandomDecodeAfterClearFrameBufferCache(const char* webpFile)
+{
+    SCOPED_TRACE(webpFile);
+
+    RefPtr<SharedBuffer> data = readFile(webpFile);
+    ASSERT_TRUE(data.get());
+    Vector<unsigned> baselineHashes;
+    createDecodingBaseline(data.get(), &baselineHashes);
+    size_t frameCount = baselineHashes.size();
+
+    OwnPtr<WEBPImageDecoder> decoder = createDecoder();
+    decoder->setData(data.get(), true);
+    for (size_t clearExceptFrame = 0; clearExceptFrame < frameCount; ++clearExceptFrame) {
+        decoder->clearCacheExceptFrame(clearExceptFrame);
+        const size_t skippingStep = 5;
+        for (size_t i = 0; i < skippingStep; ++i) {
+            for (size_t j = 0; j < frameCount; j += skippingStep) {
+                SCOPED_TRACE(testing::Message() << "Random i:" << i << " j:" << j);
+                ImageFrame* frame = decoder->frameBufferAtIndex(j);
+                EXPECT_EQ(baselineHashes[j], hashSkBitmap(frame->getSkBitmap()));
+            }
+        }
+    }
+}
+
+} // namespace
+
+class AnimatedWebPTests : public ::testing::Test {
+protected:
+    virtual void SetUp()
+    {
+        // Enable animated WebP for all the tests.
+        WebCore::RuntimeEnabledFeatures::setAnimatedWebPEnabled(true);
+    }
+};
+
+TEST_F(AnimatedWebPTests, verifyAnimationParametersTransparentImage)
+{
+    OwnPtr<WEBPImageDecoder> decoder = createDecoder();
+    EXPECT_EQ(cAnimationLoopOnce, decoder->repetitionCount());
+
+    RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/webp-animated.webp");
+    ASSERT_TRUE(data.get());
+    decoder->setData(data.get(), true);
+
+    const int canvasWidth = 11;
+    const int canvasHeight = 29;
+    const struct AnimParam {
+        int xOffset, yOffset, width, height;
+        ImageFrame::FrameDisposalMethod dispose;
+        unsigned duration;
+        bool hasAlpha;
+    } frameParameters[] = {
+        { 0, 0, 11, 29, ImageFrame::DisposeKeep, 1000u, true },
+        { 2, 10, 7, 17, ImageFrame::DisposeKeep, 500u, true },
+        { 2, 2, 7, 16, ImageFrame::DisposeKeep, 1000u, true },
+    };
+
+    for (size_t i = 0; i < ARRAY_SIZE(frameParameters); ++i) {
+        const ImageFrame* const frame = decoder->frameBufferAtIndex(i);
+        EXPECT_EQ(ImageFrame::FrameComplete, frame->status());
+        EXPECT_EQ(canvasWidth, frame->getSkBitmap().width());
+        EXPECT_EQ(canvasHeight, frame->getSkBitmap().height());
+        EXPECT_EQ(frameParameters[i].xOffset, frame->originalFrameRect().x());
+        EXPECT_EQ(frameParameters[i].yOffset, frame->originalFrameRect().y());
+        EXPECT_EQ(frameParameters[i].width, frame->originalFrameRect().width());
+        EXPECT_EQ(frameParameters[i].height, frame->originalFrameRect().height());
+        EXPECT_EQ(frameParameters[i].dispose, frame->disposalMethod());
+        EXPECT_EQ(frameParameters[i].duration, frame->duration());
+        EXPECT_EQ(frameParameters[i].hasAlpha, frame->hasAlpha());
+    }
+
+    EXPECT_EQ(ARRAY_SIZE(frameParameters), decoder->frameCount());
+    EXPECT_EQ(cAnimationLoopInfinite, decoder->repetitionCount());
+}
+
+TEST_F(AnimatedWebPTests, verifyAnimationParametersOpaqueFramesTransparentBackground)
+{
+    OwnPtr<WEBPImageDecoder> decoder = createDecoder();
+    EXPECT_EQ(cAnimationLoopOnce, decoder->repetitionCount());
+
+    RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/webp-animated-opaque.webp");
+    ASSERT_TRUE(data.get());
+    decoder->setData(data.get(), true);
+
+    const int canvasWidth = 94;
+    const int canvasHeight = 87;
+    const struct AnimParam {
+        int xOffset, yOffset, width, height;
+        ImageFrame::FrameDisposalMethod dispose;
+        unsigned duration;
+        bool hasAlpha;
+    } frameParameters[] = {
+        { 4, 10, 33, 32, ImageFrame::DisposeOverwriteBgcolor, 1000u, true },
+        { 34, 30, 33, 32, ImageFrame::DisposeOverwriteBgcolor, 1000u, true },
+        { 62, 50, 32, 32, ImageFrame::DisposeOverwriteBgcolor, 1000u, true },
+        { 10, 54, 32, 33, ImageFrame::DisposeOverwriteBgcolor, 1000u, true },
+    };
+
+    for (size_t i = 0; i < ARRAY_SIZE(frameParameters); ++i) {
+        const ImageFrame* const frame = decoder->frameBufferAtIndex(i);
+        EXPECT_EQ(ImageFrame::FrameComplete, frame->status());
+        EXPECT_EQ(canvasWidth, frame->getSkBitmap().width());
+        EXPECT_EQ(canvasHeight, frame->getSkBitmap().height());
+        EXPECT_EQ(frameParameters[i].xOffset, frame->originalFrameRect().x());
+        EXPECT_EQ(frameParameters[i].yOffset, frame->originalFrameRect().y());
+        EXPECT_EQ(frameParameters[i].width, frame->originalFrameRect().width());
+        EXPECT_EQ(frameParameters[i].height, frame->originalFrameRect().height());
+        EXPECT_EQ(frameParameters[i].dispose, frame->disposalMethod());
+        EXPECT_EQ(frameParameters[i].duration, frame->duration());
+        EXPECT_EQ(frameParameters[i].hasAlpha, frame->hasAlpha());
+    }
+
+    EXPECT_EQ(ARRAY_SIZE(frameParameters), decoder->frameCount());
+    EXPECT_EQ(cAnimationLoopInfinite, decoder->repetitionCount());
+}
+
+TEST_F(AnimatedWebPTests, parseAndDecodeByteByByte)
+{
+    const struct TestImage {
+        const char* filename;
+        unsigned frameCount;
+        int repetitionCount;
+    } testImages[] = {
+        { "/LayoutTests/fast/images/resources/webp-animated.webp", 3u, cAnimationLoopInfinite },
+        { "/LayoutTests/fast/images/resources/webp-animated-icc-xmp.webp", 13u, 32000 },
+    };
+
+    for (size_t i = 0; i < ARRAY_SIZE(testImages); ++i) {
+        OwnPtr<WEBPImageDecoder> decoder = createDecoder();
+        RefPtr<SharedBuffer> data = readFile(testImages[i].filename);
+        ASSERT_TRUE(data.get());
+
+        size_t frameCount = 0;
+        size_t framesDecoded = 0;
+
+        // Pass data to decoder byte by byte.
+        for (size_t length = 1; length <= data->size(); ++length) {
+            RefPtr<SharedBuffer> tempData = SharedBuffer::create(data->data(), length);
+            decoder->setData(tempData.get(), length == data->size());
+
+            EXPECT_LE(frameCount, decoder->frameCount());
+            frameCount = decoder->frameCount();
+
+            ImageFrame* frame = decoder->frameBufferAtIndex(frameCount - 1);
+            if (frame && frame->status() == ImageFrame::FrameComplete && framesDecoded < frameCount)
+                ++framesDecoded;
+        }
+
+        EXPECT_EQ(testImages[i].frameCount, decoder->frameCount());
+        EXPECT_EQ(testImages[i].frameCount, framesDecoded);
+        EXPECT_EQ(testImages[i].repetitionCount, decoder->repetitionCount());
+    }
+}
+
+TEST_F(AnimatedWebPTests, invalidImage)
+{
+    OwnPtr<WEBPImageDecoder> decoder = createDecoder();
+
+    RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/invalid-animated-webp.webp");
+    ASSERT_TRUE(data.get());
+    decoder->setData(data.get(), true);
+
+    EXPECT_EQ(0u, decoder->frameCount());
+    ImageFrame* frame = decoder->frameBufferAtIndex(0);
+    EXPECT_FALSE(frame);
+    EXPECT_EQ(cAnimationLoopOnce, decoder->repetitionCount());
+}
+
+TEST_F(AnimatedWebPTests, progressiveDecode)
+{
+    RefPtr<SharedBuffer> fullData = readFile("/LayoutTests/fast/images/resources/webp-animated.webp");
+    ASSERT_TRUE(fullData.get());
+    const size_t fullLength = fullData->size();
+
+    OwnPtr<WEBPImageDecoder>  decoder;
+    ImageFrame* frame;
+
+    Vector<unsigned> truncatedHashes;
+    Vector<unsigned> progressiveHashes;
+
+    // Compute hashes when the file is truncated.
+    const size_t increment = 1;
+    for (size_t i = 1; i <= fullLength; i += increment) {
+        decoder = createDecoder();
+        RefPtr<SharedBuffer> data = SharedBuffer::create(fullData->data(), i);
+        decoder->setData(data.get(), i == fullLength);
+        frame = decoder->frameBufferAtIndex(0);
+        if (!frame) {
+            truncatedHashes.append(0);
+            continue;
+        }
+        truncatedHashes.append(hashSkBitmap(frame->getSkBitmap()));
+    }
+
+    // Compute hashes when the file is progressively decoded.
+    decoder = createDecoder();
+    for (size_t i = 1; i <= fullLength; i += increment) {
+        RefPtr<SharedBuffer> data = SharedBuffer::create(fullData->data(), i);
+        decoder->setData(data.get(), i == fullLength);
+        frame = decoder->frameBufferAtIndex(0);
+        if (!frame) {
+            progressiveHashes.append(0);
+            continue;
+        }
+        progressiveHashes.append(hashSkBitmap(frame->getSkBitmap()));
+    }
+
+    bool match = true;
+    for (size_t i = 0; i < truncatedHashes.size(); ++i) {
+        if (truncatedHashes[i] != progressiveHashes[i]) {
+            match = false;
+            break;
+        }
+    }
+    EXPECT_TRUE(match);
+}
+
+TEST_F(AnimatedWebPTests, frameIsCompleteAndDuration)
+{
+    OwnPtr<WEBPImageDecoder> decoder = createDecoder();
+
+    RefPtr<SharedBuffer> data = readFile("/LayoutTests/fast/images/resources/webp-animated.webp");
+    ASSERT_TRUE(data.get());
+
+    ASSERT_GE(data->size(), 10u);
+    RefPtr<SharedBuffer> tempData = SharedBuffer::create(data->data(), data->size() - 10);
+    decoder->setData(tempData.get(), false);
+
+    EXPECT_EQ(2u, decoder->frameCount());
+    EXPECT_FALSE(decoder->failed());
+    EXPECT_TRUE(decoder->frameIsCompleteAtIndex(0));
+    EXPECT_EQ(1000, decoder->frameDurationAtIndex(0));
+    EXPECT_TRUE(decoder->frameIsCompleteAtIndex(1));
+    EXPECT_EQ(500, decoder->frameDurationAtIndex(1));
+
+    decoder->setData(data.get(), true);
+    EXPECT_EQ(3u, decoder->frameCount());
+    EXPECT_TRUE(decoder->frameIsCompleteAtIndex(0));
+    EXPECT_EQ(1000, decoder->frameDurationAtIndex(0));
+    EXPECT_TRUE(decoder->frameIsCompleteAtIndex(1));
+    EXPECT_EQ(500, decoder->frameDurationAtIndex(1));
+    EXPECT_TRUE(decoder->frameIsCompleteAtIndex(2));
+    EXPECT_EQ(1000.0, decoder->frameDurationAtIndex(2));
+}
+
+TEST_F(AnimatedWebPTests, updateRequiredPreviousFrameAfterFirstDecode)
+{
+    OwnPtr<WEBPImageDecoder> decoder = createDecoder();
+
+    RefPtr<SharedBuffer> fullData = readFile("/LayoutTests/fast/images/resources/webp-animated.webp");
+    ASSERT_TRUE(fullData.get());
+
+    // Give it data that is enough to parse but not decode in order to check the status
+    // of requiredPreviousFrameIndex before decoding.
+    size_t partialSize = 1;
+    do {
+        RefPtr<SharedBuffer> data = SharedBuffer::create(fullData->data(), partialSize);
+        decoder->setData(data.get(), false);
+        ++partialSize;
+    } while (!decoder->frameCount() || decoder->frameBufferAtIndex(0)->status() == ImageFrame::FrameEmpty);
+
+    EXPECT_EQ(notFound, decoder->frameBufferAtIndex(0)->requiredPreviousFrameIndex());
+    unsigned frameCount = decoder->frameCount();
+    for (size_t i = 1; i < frameCount; ++i)
+        EXPECT_EQ(i - 1, decoder->frameBufferAtIndex(i)->requiredPreviousFrameIndex());
+
+    decoder->setData(fullData.get(), true);
+    for (size_t i = 0; i < frameCount; ++i)
+        EXPECT_EQ(notFound, decoder->frameBufferAtIndex(i)->requiredPreviousFrameIndex());
+}
+
+TEST_F(AnimatedWebPTests, randomFrameDecode)
+{
+    testRandomFrameDecode("/LayoutTests/fast/images/resources/webp-animated.webp");
+    testRandomFrameDecode("/LayoutTests/fast/images/resources/webp-animated-opaque.webp");
+    testRandomFrameDecode("/LayoutTests/fast/images/resources/webp-animated-large.webp");
+    testRandomFrameDecode("/LayoutTests/fast/images/resources/webp-animated-icc-xmp.webp");
+}
+
+TEST_F(AnimatedWebPTests, randomDecodeAfterClearFrameBufferCache)
+{
+    testRandomDecodeAfterClearFrameBufferCache("/LayoutTests/fast/images/resources/webp-animated.webp");
+    testRandomDecodeAfterClearFrameBufferCache("/LayoutTests/fast/images/resources/webp-animated-opaque.webp");
+    testRandomDecodeAfterClearFrameBufferCache("/LayoutTests/fast/images/resources/webp-animated-large.webp");
+    testRandomDecodeAfterClearFrameBufferCache("/LayoutTests/fast/images/resources/webp-animated-icc-xmp.webp");
+}
+
+TEST_F(AnimatedWebPTests, resumePartialDecodeAfterClearFrameBufferCache)
+{
+    RefPtr<SharedBuffer> fullData = readFile("/LayoutTests/fast/images/resources/webp-animated-large.webp");
+    ASSERT_TRUE(fullData.get());
+    Vector<unsigned> baselineHashes;
+    createDecodingBaseline(fullData.get(), &baselineHashes);
+    size_t frameCount = baselineHashes.size();
+
+    OwnPtr<WEBPImageDecoder> decoder = createDecoder();
+
+    // Let frame 0 be partially decoded.
+    size_t partialSize = 1;
+    do {
+        RefPtr<SharedBuffer> data = SharedBuffer::create(fullData->data(), partialSize);
+        decoder->setData(data.get(), false);
+        ++partialSize;
+    } while (!decoder->frameCount() || decoder->frameBufferAtIndex(0)->status() == ImageFrame::FrameEmpty);
+
+    // Skip to the last frame and clear.
+    decoder->setData(fullData.get(), true);
+    EXPECT_EQ(frameCount, decoder->frameCount());
+    ImageFrame* lastFrame = decoder->frameBufferAtIndex(frameCount - 1);
+    EXPECT_EQ(baselineHashes[frameCount - 1], hashSkBitmap(lastFrame->getSkBitmap()));
+    decoder->clearCacheExceptFrame(notFound);
+
+    // Resume decoding of the first frame.
+    ImageFrame* firstFrame = decoder->frameBufferAtIndex(0);
+    EXPECT_EQ(ImageFrame::FrameComplete, firstFrame->status());
+    EXPECT_EQ(baselineHashes[0], hashSkBitmap(firstFrame->getSkBitmap()));
+}
+
+#endif
+
diff --git a/Source/core/platform/mac/EmptyProtocolDefinitions.h b/Source/core/platform/mac/EmptyProtocolDefinitions.h
index 65a35d1..46e265b 100644
--- a/Source/core/platform/mac/EmptyProtocolDefinitions.h
+++ b/Source/core/platform/mac/EmptyProtocolDefinitions.h
@@ -25,20 +25,13 @@
 
 #if defined(__OBJC__)
 
+#import <AvailabilityMacros.h>
+
 #define EMPTY_PROTOCOL(NAME) \
 @protocol NAME <NSObject> \
 @end
 
-#if __MAC_OS_X_VERSION_MAX_ALLOWED == 1050
-
-EMPTY_PROTOCOL(NSTableViewDataSource)
-EMPTY_PROTOCOL(NSTableViewDelegate)
-EMPTY_PROTOCOL(NSWindowDelegate)
-EMPTY_PROTOCOL(NSAnimationDelegate)
-
-#endif
-
-#if __MAC_OS_X_VERSION_MAX_ALLOWED <= 1060
+#if __MAC_OS_X_VERSION_MAX_ALLOWED == 1060
 
 EMPTY_PROTOCOL(NSURLConnectionDelegate)
 EMPTY_PROTOCOL(NSURLDownloadDelegate)
diff --git a/Source/core/platform/mac/NSScrollerImpDetails.h b/Source/core/platform/mac/NSScrollerImpDetails.h
index f5244bc..309e2d2 100644
--- a/Source/core/platform/mac/NSScrollerImpDetails.h
+++ b/Source/core/platform/mac/NSScrollerImpDetails.h
@@ -27,9 +27,10 @@
 #define WebCore_NSScrollerImpDetails_h
 
 #include "config.h"
+#import <AvailabilityMacros.h>
 
 // Public APIs not available on versions of Mac on which we build
-#if __MAC_OS_X_VERSION_MAX_ALLOWED <= 1060
+#if __MAC_OS_X_VERSION_MAX_ALLOWED == 1060
 enum {
     NSScrollerStyleLegacy       = 0,
     NSScrollerStyleOverlay      = 1
@@ -44,7 +45,7 @@
 typedef NSInteger NSScrollerKnobStyle;
 #endif
 
-#if __MAC_OS_X_VERSION_MAX_ALLOWED <= 1060
+#if __MAC_OS_X_VERSION_MAX_ALLOWED == 1060
 @interface NSScroller(NSObject)
 + (NSScrollerStyle)preferredScrollerStyle;
 @end
diff --git a/Source/core/platform/mac/ScrollElasticityController.mm b/Source/core/platform/mac/ScrollElasticityController.mm
index 291af60..b10f6d2 100644
--- a/Source/core/platform/mac/ScrollElasticityController.mm
+++ b/Source/core/platform/mac/ScrollElasticityController.mm
@@ -32,13 +32,6 @@
 
 #if ENABLE(RUBBER_BANDING)
 
-#if __MAC_OS_X_VERSION_MIN_REQUIRED == 1050
-@interface NSProcessInfo (ScrollAnimatorMacExt)
-- (NSTimeInterval)systemUptime;
-@end
-#endif
-
-#if ENABLE(RUBBER_BANDING)
 static NSTimeInterval systemUptime()
 {
     if ([[NSProcessInfo processInfo] respondsToSelector:@selector(systemUptime)])
@@ -61,8 +54,6 @@
     }
     return 0;
 }
-#endif
-
 
 namespace WebCore {
 
diff --git a/Source/core/platform/mediastream/MediaStreamCenter.cpp b/Source/core/platform/mediastream/MediaStreamCenter.cpp
index 2b608f3..0818082 100644
--- a/Source/core/platform/mediastream/MediaStreamCenter.cpp
+++ b/Source/core/platform/mediastream/MediaStreamCenter.cpp
@@ -34,12 +34,12 @@
 #include "core/platform/mediastream/MediaStreamCenter.h"
 
 #include "core/platform/mediastream/MediaStreamDescriptor.h"
-#include "core/platform/mediastream/MediaStreamSourcesQueryClient.h"
+#include "modules/mediastream/MediaStreamTrackSourcesRequest.h"
 #include "public/platform/Platform.h"
 #include "public/platform/WebMediaStream.h"
 #include "public/platform/WebMediaStreamCenter.h"
-#include "public/platform/WebMediaStreamSourcesRequest.h"
 #include "public/platform/WebMediaStreamTrack.h"
+#include "public/platform/WebMediaStreamTrackSourcesRequest.h"
 #include "wtf/MainThread.h"
 #include "wtf/PassOwnPtr.h"
 
@@ -61,19 +61,9 @@
 {
 }
 
-void MediaStreamCenter::queryMediaStreamSources(PassRefPtr<MediaStreamSourcesQueryClient> client)
+bool MediaStreamCenter::getMediaStreamTrackSources(PassRefPtr<MediaStreamTrackSourcesRequest> request)
 {
-    if (m_private) {
-        m_private->queryMediaStreamSources(client);
-    } else {
-        MediaStreamSourceVector audioSources, videoSources;
-        client->didCompleteQuery(audioSources, videoSources);
-    }
-}
-
-bool MediaStreamCenter::getSourceInfos(const String& url, WebKit::WebVector<WebKit::WebSourceInfo>& sourceInfos)
-{
-    return m_private && m_private->getSourceInfos(url, sourceInfos);
+    return m_private && m_private->getMediaStreamTrackSources(request);
 }
 
 void MediaStreamCenter::didSetMediaStreamTrackEnabled(MediaStreamDescriptor* stream,  MediaStreamComponent* component)
diff --git a/Source/core/platform/mediastream/MediaStreamCenter.h b/Source/core/platform/mediastream/MediaStreamCenter.h
index c5fa261..b215dec 100644
--- a/Source/core/platform/mediastream/MediaStreamCenter.h
+++ b/Source/core/platform/mediastream/MediaStreamCenter.h
@@ -43,14 +43,13 @@
 class WebMediaStream;
 class WebMediaStreamCenter;
 class WebMediaStreamTrack;
-class WebSourceInfo;
 }
 
 namespace WebCore {
 
 class MediaStreamComponent;
 class MediaStreamDescriptor;
-class MediaStreamSourcesQueryClient;
+class MediaStreamTrackSourcesRequest;
 
 class MediaStreamCenter : public WebKit::WebMediaStreamCenterClient {
 public:
@@ -58,8 +57,7 @@
 
     static MediaStreamCenter& instance();
 
-    void queryMediaStreamSources(PassRefPtr<MediaStreamSourcesQueryClient>);
-    bool getSourceInfos(const String& url, WebKit::WebVector<WebKit::WebSourceInfo>&);
+    bool getMediaStreamTrackSources(PassRefPtr<MediaStreamTrackSourcesRequest>);
     void didSetMediaStreamTrackEnabled(MediaStreamDescriptor*, MediaStreamComponent*);
     bool didAddMediaStreamTrack(MediaStreamDescriptor*, MediaStreamComponent*);
     bool didRemoveMediaStreamTrack(MediaStreamDescriptor*, MediaStreamComponent*);
diff --git a/Source/core/platform/midi/MIDIAccessor.cpp b/Source/core/platform/midi/MIDIAccessor.cpp
new file mode 100644
index 0000000..a5f602b
--- /dev/null
+++ b/Source/core/platform/midi/MIDIAccessor.cpp
@@ -0,0 +1,94 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/platform/midi/MIDIAccessor.h"
+
+#include "core/platform/midi/MIDIAccessorClient.h"
+#include "public/platform/Platform.h"
+#include "public/platform/WebMIDIAccessor.h"
+#include "wtf/text/WTFString.h"
+
+using WebKit::WebString;
+
+namespace WebCore {
+
+// Factory method
+PassOwnPtr<MIDIAccessor> MIDIAccessor::create(MIDIAccessorClient* client)
+{
+    return adoptPtr(new MIDIAccessor(client));
+}
+
+MIDIAccessor::MIDIAccessor(MIDIAccessorClient* client)
+    : m_client(client)
+{
+    ASSERT(client);
+
+    m_accessor = adoptPtr(WebKit::Platform::current()->createMIDIAccessor(this));
+
+    ASSERT(m_accessor);
+}
+
+void MIDIAccessor::requestAccess(bool access)
+{
+    m_accessor->requestAccess(access);
+}
+
+void MIDIAccessor::sendMIDIData(unsigned portIndex, const unsigned char* data, size_t length, double timeStamp)
+{
+    m_accessor->sendMIDIData(portIndex, data, length, timeStamp);
+}
+
+void MIDIAccessor::didAddInputPort(const WebString& id, const WebString& manufacturer, const WebString& name, const WebString& version)
+{
+    m_client->didAddInputPort(id, manufacturer, name, version);
+}
+
+void MIDIAccessor::didAddOutputPort(const WebString& id, const WebString& manufacturer, const WebString& name, const WebString& version)
+{
+    m_client->didAddOutputPort(id, manufacturer, name, version);
+}
+
+void MIDIAccessor::didAllowAccess()
+{
+    m_client->didAllowAccess();
+}
+
+void MIDIAccessor::didBlockAccess()
+{
+    m_client->didBlockAccess();
+}
+
+void MIDIAccessor::didReceiveMIDIData(unsigned portIndex, const unsigned char* data, size_t length, double timeStamp)
+{
+    m_client->didReceiveMIDIData(portIndex, data, length, timeStamp);
+}
+
+} // namespace WebCore
diff --git a/Source/core/platform/midi/MIDIAccessor.h b/Source/core/platform/midi/MIDIAccessor.h
new file mode 100644
index 0000000..3eaa90c
--- /dev/null
+++ b/Source/core/platform/midi/MIDIAccessor.h
@@ -0,0 +1,68 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef MIDIAccessor_h
+#define MIDIAccessor_h
+
+#include "public/platform/WebMIDIAccessor.h"
+#include "public/platform/WebMIDIAccessorClient.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+
+namespace WebCore {
+
+class MIDIAccessorClient;
+
+class MIDIAccessor : public WebKit::WebMIDIAccessorClient {
+public:
+    static PassOwnPtr<MIDIAccessor> create(MIDIAccessorClient*);
+
+    virtual ~MIDIAccessor() { }
+
+    void requestAccess(bool access);
+    void sendMIDIData(unsigned portIndex, const unsigned char* data, size_t length, double timeStamp);
+
+    // WebKit::WebMIDIAccessorClient
+    virtual void didAddInputPort(const WebKit::WebString& id, const WebKit::WebString& manufacturer, const WebKit::WebString& name, const WebKit::WebString& version) OVERRIDE;
+    virtual void didAddOutputPort(const WebKit::WebString& id, const WebKit::WebString& manufacturer, const WebKit::WebString& name, const WebKit::WebString& version) OVERRIDE;
+    virtual void didAllowAccess() OVERRIDE;
+    virtual void didBlockAccess() OVERRIDE;
+    virtual void didReceiveMIDIData(unsigned portIndex, const unsigned char* data, size_t length, double timeStamp) OVERRIDE;
+
+private:
+    MIDIAccessor(MIDIAccessorClient*);
+
+    MIDIAccessorClient* m_client;
+    OwnPtr<WebKit::WebMIDIAccessor> m_accessor;
+};
+
+} // namespace WebCore
+
+#endif // MIDIAccessor_h
diff --git a/Source/core/css/CSSStyleDeclaration.cpp b/Source/core/platform/midi/MIDIAccessorClient.h
similarity index 71%
copy from Source/core/css/CSSStyleDeclaration.cpp
copy to Source/core/platform/midi/MIDIAccessorClient.h
index 538e17e..467d96d 100644
--- a/Source/core/css/CSSStyleDeclaration.cpp
+++ b/Source/core/platform/midi/MIDIAccessorClient.h
@@ -28,19 +28,23 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#include "config.h"
-#include "core/css/CSSStyleDeclaration.h"
+#ifndef MIDIAccessorClient_h
+#define MIDIAccessorClient_h
 
-#include "core/css/CSSParser.h"
-#include "core/css/CSSPrimitiveValue.h"
-#include "core/css/CSSStyleSheet.h"
-#include "core/css/CSSValue.h"
-#include "core/dom/Document.h"
-#include "core/dom/DocumentStyleSheetCollection.h"
-#include "core/dom/EventTarget.h"
-#include "core/html/HTMLStyleElement.h"
-#include "core/page/RuntimeCSSEnabled.h"
+#include "wtf/Forward.h"
 
 namespace WebCore {
 
+class MIDIAccessorClient {
+public:
+    virtual void didAddInputPort(const String& id, const String& manufacturer, const String& name, const String& version) = 0;
+    virtual void didAddOutputPort(const String& id, const String& manufacturer, const String& name, const String& version) = 0;
+
+    virtual void didAllowAccess() = 0;
+    virtual void didBlockAccess() = 0;
+    virtual void didReceiveMIDIData(unsigned portIndex, const unsigned char* data, size_t length, double timeStamp) = 0;
+};
+
 } // namespace WebCore
+
+#endif // MIDIAccessorClient_h
diff --git a/Source/core/platform/midi/OWNERS b/Source/core/platform/midi/OWNERS
new file mode 100644
index 0000000..5121485
--- /dev/null
+++ b/Source/core/platform/midi/OWNERS
@@ -0,0 +1,2 @@
+crogers@google.com
+toyoshim@chromium.org
diff --git a/Source/core/platform/network/BlobData.cpp b/Source/core/platform/network/BlobData.cpp
index 31ad0ee..9b9ab90 100644
--- a/Source/core/platform/network/BlobData.cpp
+++ b/Source/core/platform/network/BlobData.cpp
@@ -29,15 +29,15 @@
  */
 
 #include "config.h"
-#include "core/fileapi/BlobURL.h"
-#include "core/fileapi/ThreadableBlobRegistry.h"
 #include "core/platform/network/BlobData.h"
 
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefPtr.h>
-#include <wtf/Vector.h>
+#include "core/fileapi/BlobRegistry.h"
+#include "core/fileapi/BlobURL.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -106,12 +106,12 @@
 {
     UNUSED_PARAM(size);
     m_internalURL = BlobURL::createInternalURL();
-    ThreadableBlobRegistry::registerBlobURL(m_internalURL, data);
+    BlobRegistry::registerBlobURL(m_internalURL, data);
 }
 
 BlobDataHandle::~BlobDataHandle()
 {
-    ThreadableBlobRegistry::unregisterBlobURL(m_internalURL);
+    BlobRegistry::unregisterBlobURL(m_internalURL);
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/network/BlobRegistry.cpp b/Source/core/platform/network/BlobRegistry.cpp
deleted file mode 100644
index bc6b778..0000000
--- a/Source/core/platform/network/BlobRegistry.cpp
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (C) 2013 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
- * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
- * THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/platform/network/BlobRegistry.h"
-
-#include <wtf/MainThread.h>
-
-namespace WebCore {
-
-BlobRegistry::~BlobRegistry()
-{
-}
-
-}
diff --git a/Source/core/platform/network/BlobRegistry.h b/Source/core/platform/network/BlobRegistry.h
deleted file mode 100644
index 9d2dad5..0000000
--- a/Source/core/platform/network/BlobRegistry.h
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef BlobRegistry_h
-#define BlobRegistry_h
-
-#include <wtf/PassOwnPtr.h>
-
-namespace WebCore {
-
-class BlobData;
-class BlobStorageData;
-class BlobRegistry;
-class KURL;
-
-BlobRegistry& blobRegistry();
-
-// BlobRegistry is not thread-safe. It should only be called from main thread.
-class BlobRegistry {
-public:
-    // Registers a blob URL referring to the specified blob data.
-    virtual void registerBlobURL(const KURL&, PassOwnPtr<BlobData>) = 0;
-    
-    // Registers a new blob URL referring to the blob data identified by the specified srcURL.
-    virtual void registerBlobURL(const KURL&, const KURL& srcURL) = 0;
-
-    virtual void unregisterBlobURL(const KURL&) = 0;
-
-protected:
-    virtual ~BlobRegistry();
-};
-
-} // namespace WebCore
-
-#endif // BlobRegistry_h
diff --git a/Source/core/platform/network/BlobRegistryProxy.cpp b/Source/core/platform/network/BlobRegistryProxy.cpp
deleted file mode 100644
index 3a10379..0000000
--- a/Source/core/platform/network/BlobRegistryProxy.cpp
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/platform/network/BlobRegistryProxy.h"
-
-#include "core/platform/network/BlobData.h"
-#include "public/platform/Platform.h"
-#include "public/platform/WebBlobData.h"
-#include "public/platform/WebBlobRegistry.h"
-#include "public/platform/WebURL.h"
-#include "weborigin/KURL.h"
-#include "wtf/MainThread.h"
-#include "wtf/StdLibExtras.h"
-
-namespace WebCore {
-
-BlobRegistry& blobRegistry()
-{
-    ASSERT(isMainThread());
-    DEFINE_STATIC_LOCAL(BlobRegistryProxy, instance, ());
-    return instance;
-}
-
-BlobRegistryProxy::BlobRegistryProxy()
-    : m_webBlobRegistry(WebKit::Platform::current()->blobRegistry())
-{
-}
-
-void BlobRegistryProxy::registerBlobURL(const KURL& url, PassOwnPtr<BlobData> blobData)
-{
-    if (m_webBlobRegistry) {
-        WebKit::WebBlobData webBlobData(blobData);
-        m_webBlobRegistry->registerBlobURL(url, webBlobData);
-    }
-}
-
-void BlobRegistryProxy::registerBlobURL(const KURL& url, const KURL& srcURL)
-{
-    if (m_webBlobRegistry)
-        m_webBlobRegistry->registerBlobURL(url, srcURL);
-}
-
-void BlobRegistryProxy::unregisterBlobURL(const KURL& url)
-{
-    if (m_webBlobRegistry)
-        m_webBlobRegistry->unregisterBlobURL(url);
-}
-
-} // namespace WebCore
diff --git a/Source/core/platform/network/BlobRegistryProxy.h b/Source/core/platform/network/BlobRegistryProxy.h
deleted file mode 100644
index 264a4c3..0000000
--- a/Source/core/platform/network/BlobRegistryProxy.h
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (C) 2010 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are
- * met:
- *
- *     * Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above
- * copyright notice, this list of conditions and the following disclaimer
- * in the documentation and/or other materials provided with the
- * distribution.
- *     * Neither the name of Google Inc. nor the names of its
- * contributors may be used to endorse or promote products derived from
- * this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
- * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
- * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
- * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
- * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
- * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
- * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
- * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef BlobRegistryProxy_h
-#define BlobRegistryProxy_h
-
-#include "core/platform/network/BlobRegistry.h"
-
-namespace WebKit { class WebBlobRegistry; }
-
-namespace WebCore {
-
-class BlobRegistryProxy : public BlobRegistry {
-public:
-    BlobRegistryProxy();
-
-    virtual void registerBlobURL(const KURL&, PassOwnPtr<BlobData>);
-    virtual void registerBlobURL(const KURL&, const KURL& srcURL);
-    virtual void unregisterBlobURL(const KURL&);
-
-private:
-    virtual ~BlobRegistryProxy() { }
-
-    WebKit::WebBlobRegistry* m_webBlobRegistry;
-};
-
-} // namespace WebCore
-
-#endif // BlobRegistryProxy_h
diff --git a/Source/core/platform/network/DNS.cpp b/Source/core/platform/network/DNS.cpp
index fe9c683..7c18e41 100644
--- a/Source/core/platform/network/DNS.cpp
+++ b/Source/core/platform/network/DNS.cpp
@@ -28,12 +28,18 @@
 #include "core/platform/network/DNS.h"
 
 #include "public/platform/Platform.h"
+#include "public/platform/WebPrescientNetworking.h"
 
 namespace WebCore {
 
 void prefetchDNS(const String& hostname)
 {
-    WebKit::Platform::current()->prefetchHostName(hostname);
+    WebKit::WebPrescientNetworking* prescientNetworking = WebKit::Platform::current()->prescientNetworking();
+
+    if (!prescientNetworking)
+        return;
+
+    prescientNetworking->prefetchDNS(hostname);
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/network/FormDataBuilder.cpp b/Source/core/platform/network/FormDataBuilder.cpp
index daa3cc7..002865d 100644
--- a/Source/core/platform/network/FormDataBuilder.cpp
+++ b/Source/core/platform/network/FormDataBuilder.cpp
@@ -162,7 +162,7 @@
     // FIXME: This loses data irreversibly if the filename includes characters you can't encode
     // in the website's character set.
     append(buffer, "; filename=\"");
-    appendQuotedString(buffer, encoding.encode(filename.characters(), filename.length(), WTF::QuestionMarksForUnencodables));
+    appendQuotedString(buffer, encoding.encode(filename, WTF::QuestionMarksForUnencodables));
     append(buffer, '"');
 }
 
diff --git a/Source/core/platform/network/HTTPHeaderMap.cpp b/Source/core/platform/network/HTTPHeaderMap.cpp
index dbe5969..83750ff 100644
--- a/Source/core/platform/network/HTTPHeaderMap.cpp
+++ b/Source/core/platform/network/HTTPHeaderMap.cpp
@@ -97,7 +97,7 @@
 
 AtomicString HTTPHeaderMap::get(const char* name) const
 {
-    const_iterator i = find<const char*, CaseFoldingCStringTranslator>(name);
+    const_iterator i = find<CaseFoldingCStringTranslator>(name);
     if (i == end())
         return nullAtom;
     return i->value;
@@ -105,12 +105,12 @@
 
 bool HTTPHeaderMap::contains(const char* name) const
 {
-    return find<const char*, CaseFoldingCStringTranslator>(name) != end();
+    return find<CaseFoldingCStringTranslator>(name) != end();
 }
 
 HTTPHeaderMap::AddResult HTTPHeaderMap::add(const char* name, const AtomicString& value)
 {
-    return HashMap<AtomicString, AtomicString, CaseFoldingHash>::add<const char*, CaseFoldingCStringTranslator>(name, value);
+    return HashMap<AtomicString, AtomicString, CaseFoldingHash>::add<CaseFoldingCStringTranslator>(name, value);
 }
 
 } // namespace WebCore
diff --git a/Source/core/platform/network/HTTPStatusCodes.h b/Source/core/platform/network/HTTPStatusCodes.h
deleted file mode 100644
index c1ac8dc..0000000
--- a/Source/core/platform/network/HTTPStatusCodes.h
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-    Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies)
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Library General Public
-    License as published by the Free Software Foundation; either
-    version 2 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Library General Public License for more details.
-
-    You should have received a copy of the GNU Library General Public License
-    along with this library; see the file COPYING.LIB.  If not, write to
-    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-    Boston, MA 02110-1301, USA.
-*/
-
-namespace WebCore {
-
-enum HTTPStatusCodes {
-    HTTPNoContent = 204,
-    HTTPResetContent = 205
-};
-
-}
diff --git a/Source/core/platform/network/MIMESniffing.h b/Source/core/platform/network/MIMESniffing.h
deleted file mode 100644
index cd1c52b..0000000
--- a/Source/core/platform/network/MIMESniffing.h
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
-    Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies)
-
-    This library is free software; you can redistribute it and/or
-    modify it under the terms of the GNU Library General Public
-    License as published by the Free Software Foundation; either
-    version 2 of the License, or (at your option) any later version.
-
-    This library is distributed in the hope that it will be useful,
-    but WITHOUT ANY WARRANTY; without even the implied warranty of
-    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-    Library General Public License for more details.
-
-    You should have received a copy of the GNU Library General Public License
-    along with this library; see the file COPYING.LIB.  If not, write to
-    the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
-    Boston, MA 02110-1301, USA.
-*/
-
-#ifndef MIMESniffing_h
-#define MIMESniffing_h
-
-#include <stddef.h>
-
-// MIME type sniffing implementation based on http://tools.ietf.org/html/draft-abarth-mime-sniff-06
-
-class MIMESniffer {
-public:
-    MIMESniffer(const char* advertisedMIMEType, bool isSupportedImageType);
-
-    size_t dataSize() const { return m_dataSize; }
-    const char* sniff(const char* data, size_t size) const { return m_function ?  m_function(data, size) : 0; }
-    bool isValid() const { return m_dataSize > 0; }
-
-private:
-    typedef const char* (*SniffFunction)(const char*, size_t);
-    size_t m_dataSize;
-    SniffFunction m_function;
-};
-
-#endif // MIMESniffing_h
diff --git a/Source/core/platform/sql/SQLiteFileSystem.h b/Source/core/platform/sql/SQLiteFileSystem.h
index 1c61b9b..8864c2d 100644
--- a/Source/core/platform/sql/SQLiteFileSystem.h
+++ b/Source/core/platform/sql/SQLiteFileSystem.h
@@ -49,13 +49,13 @@
 
     // Opens a database file.
     //
-    // fileName - The name of the database file.
+    // filemame - The name of the database file.
     // database - The SQLite structure that represents the database stored
     //            in the given file.
     // forWebSQLDatabase - True, if and only if we're opening a Web SQL Database file.
     //                     Used by Chromium to determine if the DB file needs to be opened
     //                     using a custom VFS.
-    static int openDatabase(const String& fileName, sqlite3** database, bool forWebSQLDatabase);
+    static int openDatabase(const String& filename, sqlite3** database, bool forWebSQLDatabase);
 
     // Returns the file name for a database.
     //
diff --git a/Source/core/platform/sql/SQLiteStatement.cpp b/Source/core/platform/sql/SQLiteStatement.cpp
index 7484e0d..8e1a488 100644
--- a/Source/core/platform/sql/SQLiteStatement.cpp
+++ b/Source/core/platform/sql/SQLiteStatement.cpp
@@ -20,7 +20,7 @@
  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
 #include "config.h"
@@ -32,18 +32,14 @@
 #include <wtf/Assertions.h>
 #include <wtf/text/CString.h>
 
-namespace WebCore {
-
-#if SQLITE_VERSION_NUMBER < 3003009
-
-// FIXME: This overload helps us compile with older versions of SQLite 3, but things like quotas will not work.
-static inline int sqlite3_prepare16_v2(sqlite3* db, const void* zSql, int nBytes, sqlite3_stmt** ppStmt, const void** pzTail)
-{
-    return sqlite3_prepare16(db, zSql, nBytes, ppStmt, pzTail);
-}
-
+// SQLite 3.6.16 makes sqlite3_prepare_v2 automatically retry preparing the statement
+// once if the database scheme has changed. We rely on this behavior.
+#if SQLITE_VERSION_NUMBER < 3006016
+#error SQLite version 3.6.16 or newer is required
 #endif
 
+namespace WebCore {
+
 SQLiteStatement::SQLiteStatement(SQLiteDatabase& db, const String& sql)
     : m_database(db)
     , m_query(sql)
@@ -67,25 +63,23 @@
     if (m_database.isInterrupted())
         return SQLITE_INTERRUPT;
 
-    const void* tail = 0;
-    LOG(SQLDatabase, "SQL - prepare - %s", m_query.ascii().data());
-    String strippedQuery = m_query.stripWhiteSpace();
-    const UChar* nullTermed = strippedQuery.charactersWithNullTermination();
-    int error = sqlite3_prepare16_v2(m_database.sqlite3Handle(), nullTermed, -1, &m_statement, &tail);
+    CString query = m_query.stripWhiteSpace().utf8();
 
-    // Starting with version 3.6.16, sqlite has a patch (http://www.sqlite.org/src/ci/256ec3c6af)
-    // that should make sure sqlite3_prepare16_v2 doesn't return a SQLITE_SCHEMA error.
-    // If we're using an older sqlite version, try to emulate the patch.
-    if (error == SQLITE_SCHEMA) {
-      sqlite3_finalize(m_statement);
-      error = sqlite3_prepare16_v2(m_database.sqlite3Handle(), m_query.charactersWithNullTermination(), -1, &m_statement, &tail);
-    }
+    LOG(SQLDatabase, "SQL - prepare - %s", query.data());
+
+    // Pass the length of the string including the null character to sqlite3_prepare_v2;
+    // this lets SQLite avoid an extra string copy.
+    size_t lengthIncludingNullCharacter = query.length() + 1;
+
+    const char* tail;
+    int error = sqlite3_prepare_v2(m_database.sqlite3Handle(), query.data(), lengthIncludingNullCharacter, &m_statement, &tail);
 
     if (error != SQLITE_OK)
-        LOG(SQLDatabase, "sqlite3_prepare16 failed (%i)\n%s\n%s", error, m_query.ascii().data(), sqlite3_errmsg(m_database.sqlite3Handle()));
-    const UChar* ch = static_cast<const UChar*>(tail);
-    if (ch && *ch)
+        LOG(SQLDatabase, "sqlite3_prepare16 failed (%i)\n%s\n%s", error, query.data(), sqlite3_errmsg(m_database.sqlite3Handle()));
+
+    if (tail && *tail)
         error = SQLITE_ERROR;
+
 #ifndef NDEBUG
     m_isPrepared = error == SQLITE_OK;
 #endif
@@ -109,13 +103,13 @@
     LOG(SQLDatabase, "SQL - step - %s", m_query.ascii().data());
     int error = sqlite3_step(m_statement);
     if (error != SQLITE_DONE && error != SQLITE_ROW) {
-        LOG(SQLDatabase, "sqlite3_step failed (%i)\nQuery - %s\nError - %s", 
+        LOG(SQLDatabase, "sqlite3_step failed (%i)\nQuery - %s\nError - %s",
             error, m_query.ascii().data(), sqlite3_errmsg(m_database.sqlite3Handle()));
     }
 
     return error;
 }
-    
+
 int SQLiteStatement::finalize()
 {
 #ifndef NDEBUG
@@ -129,7 +123,7 @@
     return result;
 }
 
-int SQLiteStatement::reset() 
+int SQLiteStatement::reset()
 {
     ASSERT(m_isPrepared);
     if (!m_statement)
@@ -181,14 +175,14 @@
 
 int SQLiteStatement::bindBlob(int index, const String& text)
 {
-    // String::characters() returns 0 for the empty string, which SQLite
+    // String::bloatedCharacters() returns 0 for the empty string, which SQLite
     // treats as a null, so we supply a non-null pointer for that case.
     UChar anyCharacter = 0;
     const UChar* characters;
     if (text.isEmpty() && !text.isNull())
         characters = &anyCharacter;
     else
-        characters = text.characters();
+        characters = text.bloatedCharacters();
 
     return bindBlob(index, characters, text.length() * sizeof(UChar));
 }
@@ -199,14 +193,14 @@
     ASSERT(index > 0);
     ASSERT(static_cast<unsigned>(index) <= bindParameterCount());
 
-    // String::characters() returns 0 for the empty string, which SQLite
+    // String::bloatedCharacters() returns 0 for the empty string, which SQLite
     // treats as a null, so we supply a non-null pointer for that case.
     UChar anyCharacter = 0;
     const UChar* characters;
     if (text.isEmpty() && !text.isNull())
         characters = &anyCharacter;
     else
-        characters = text.characters();
+        characters = text.bloatedCharacters();
 
     return sqlite3_bind_text16(m_statement, index, characters, sizeof(UChar) * text.length(), SQLITE_TRANSIENT);
 }
@@ -429,7 +423,7 @@
         result.clear();
         return;
     }
-        
+
     int size = sqlite3_column_bytes(m_statement, col);
     result.resize((size_t)size);
     for (int i = 0; i < size; ++i)
@@ -455,7 +449,7 @@
 
     if (columnCount() <= col)
         return 0;
-        
+
     const void* blob = sqlite3_column_blob(m_statement, col);
     if (!blob)
         return 0;
@@ -494,7 +488,7 @@
         finalize();
     if (prepare() != SQLITE_OK)
         return false;
-        
+
     while (step() == SQLITE_ROW)
         v.append(getColumnInt(col));
     bool result = true;
@@ -514,7 +508,7 @@
         finalize();
     if (prepare() != SQLITE_OK)
         return false;
-        
+
     while (step() == SQLITE_ROW)
         v.append(getColumnInt64(col));
     bool result = true;
diff --git a/Source/core/platform/sql/chromium/SQLiteFileSystemChromium.cpp b/Source/core/platform/sql/chromium/SQLiteFileSystemChromium.cpp
index 5e6ad83..d97ba0b 100644
--- a/Source/core/platform/sql/chromium/SQLiteFileSystemChromium.cpp
+++ b/Source/core/platform/sql/chromium/SQLiteFileSystemChromium.cpp
@@ -43,14 +43,12 @@
 {
 }
 
-int SQLiteFileSystem::openDatabase(const String& fileName, sqlite3** database, bool forWebSQLDatabase)
+int SQLiteFileSystem::openDatabase(const String& filename, sqlite3** database, bool forWebSQLDatabase)
 {
-    if (!forWebSQLDatabase) {
-        String path = fileName;
-        return sqlite3_open16(path.charactersWithNullTermination(), database);
-    }
+    if (!forWebSQLDatabase)
+        return sqlite3_open(filename.utf8().data(), database);
 
-    return sqlite3_open_v2(fileName.utf8().data(), database, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, "chromium_vfs");
+    return sqlite3_open_v2(filename.utf8().data(), database, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, "chromium_vfs");
 }
 
 String SQLiteFileSystem::getFileNameForNewDatabase(
diff --git a/Source/core/platform/text/DecodeEscapeSequences.h b/Source/core/platform/text/DecodeEscapeSequences.h
index 5240f7d..40709a0 100644
--- a/Source/core/platform/text/DecodeEscapeSequences.h
+++ b/Source/core/platform/text/DecodeEscapeSequences.h
@@ -134,7 +134,7 @@
             continue;
         }
 
-        String decoded = EscapeSequence::decodeRun(string.characters() + encodedRunPosition, encodedRunEnd - encodedRunPosition, encoding);
+        String decoded = EscapeSequence::decodeRun(string.bloatedCharacters() + encodedRunPosition, encodedRunEnd - encodedRunPosition, encoding);
         if (decoded.isEmpty())
             continue;
 
diff --git a/Source/core/platform/text/LocaleICU.cpp b/Source/core/platform/text/LocaleICU.cpp
index a7edcd1..ca241db 100644
--- a/Source/core/platform/text/LocaleICU.cpp
+++ b/Source/core/platform/text/LocaleICU.cpp
@@ -323,11 +323,11 @@
     if (!patternGenerator)
         return format;
     status = U_ZERO_ERROR;
-    int32_t length = udatpg_getBestPattern(patternGenerator, skeleton.characters(), skeleton.length(), 0, 0, &status);
+    int32_t length = udatpg_getBestPattern(patternGenerator, skeleton.bloatedCharacters(), skeleton.length(), 0, 0, &status);
     if (status == U_BUFFER_OVERFLOW_ERROR && length) {
         Vector<UChar> buffer(length);
         status = U_ZERO_ERROR;
-        udatpg_getBestPattern(patternGenerator, skeleton.characters(), skeleton.length(), buffer.data(), length, &status);
+        udatpg_getBestPattern(patternGenerator, skeleton.bloatedCharacters(), skeleton.length(), buffer.data(), length, &status);
         if (U_SUCCESS(status))
             format = String::adopt(buffer);
     }
diff --git a/Source/core/platform/text/ParserUtilities.h b/Source/core/platform/text/ParserUtilities.h
index ad4f98d..eeff3a9 100644
--- a/Source/core/platform/text/ParserUtilities.h
+++ b/Source/core/platform/text/ParserUtilities.h
@@ -26,28 +26,42 @@
 
 namespace WebCore {
 
-    inline bool skipString(const UChar*& ptr, const UChar* end, const UChar* name, int length)
-    {
-        if (end - ptr < length)
-            return false;
-        if (memcmp(name, ptr, sizeof(UChar) * length))
-            return false;
-        ptr += length;
-        return true;
-    }
+template<typename CharType>
+inline bool skipString(const CharType*& ptr, const CharType* end, const CharType* name, int length)
+{
+    if (end - ptr < length)
+        return false;
+    if (memcmp(name, ptr, sizeof(CharType) * length))
+        return false;
+    ptr += length;
+    return true;
+}
 
-    inline bool skipString(const UChar*& ptr, const UChar* end, const char* str)
-    {
-        int length = strlen(str);
-        if (end - ptr < length)
+inline bool skipString(const UChar*& ptr, const UChar* end, const LChar* name, int length)
+{
+    if (end - ptr < length)
+        return false;
+    for (int i = 0; i < length; ++i) {
+        if (ptr[i] != name[i])
             return false;
-        for (int i = 0; i < length; ++i) {
-            if (ptr[i] != str[i])
-                return false;
-        }
-        ptr += length;
-        return true;
     }
+    ptr += length;
+    return true;
+}
+
+template<typename CharType>
+inline bool skipString(const CharType*& ptr, const CharType* end, const char* str)
+{
+    int length = strlen(str);
+    if (end - ptr < length)
+        return false;
+    for (int i = 0; i < length; ++i) {
+        if (ptr[i] != str[i])
+            return false;
+    }
+    ptr += length;
+    return true;
+}
 
 } // namspace WebCore
 
diff --git a/Source/core/platform/text/TextBreakIterator.cpp b/Source/core/platform/text/TextBreakIterator.cpp
index 064d6bb..7291729 100644
--- a/Source/core/platform/text/TextBreakIterator.cpp
+++ b/Source/core/platform/text/TextBreakIterator.cpp
@@ -35,7 +35,7 @@
     if (s.is8Bit() && !s.contains('\r'))
         return stringLength;
 
-    NonSharedCharacterBreakIterator it(s.characters(), stringLength);
+    NonSharedCharacterBreakIterator it(s.bloatedCharacters(), stringLength);
     if (!it)
         return stringLength;
 
@@ -56,7 +56,7 @@
     if (s.is8Bit() && !s.contains('\r'))
         return std::min(stringLength, numGraphemeClusters);
 
-    NonSharedCharacterBreakIterator it(s.characters(), stringLength);
+    NonSharedCharacterBreakIterator it(s.bloatedCharacters(), stringLength);
     if (!it)
         return std::min(stringLength, numGraphemeClusters);
 
diff --git a/Source/core/platform/text/TextBreakIteratorICU.cpp b/Source/core/platform/text/TextBreakIteratorICU.cpp
index bf7e6e4..7d1733b 100644
--- a/Source/core/platform/text/TextBreakIteratorICU.cpp
+++ b/Source/core/platform/text/TextBreakIteratorICU.cpp
@@ -587,7 +587,7 @@
         UParseError parseStatus;
         UErrorCode openStatus = U_ZERO_ERROR;
         String rules(breakRules);
-        iterator = reinterpret_cast<TextBreakIterator*>(ubrk_openRules(rules.characters(), rules.length(), 0, 0, &parseStatus, &openStatus));
+        iterator = reinterpret_cast<TextBreakIterator*>(ubrk_openRules(rules.bloatedCharacters(), rules.length(), 0, 0, &parseStatus, &openStatus));
         createdIterator = true;
         ASSERT_WITH_MESSAGE(U_SUCCESS(openStatus), "ICU could not open a break iterator: %s (%d)", u_errorName(openStatus), openStatus);
     }
diff --git a/Source/core/platform/text/cf/HyphenationCF.cpp b/Source/core/platform/text/cf/HyphenationCF.cpp
index 16ca003..821dbc8 100644
--- a/Source/core/platform/text/cf/HyphenationCF.cpp
+++ b/Source/core/platform/text/cf/HyphenationCF.cpp
@@ -25,6 +25,7 @@
 
 #include "config.h"
 #include "core/platform/text/Hyphenation.h"
+#include <AvailabilityMacros.h>
 
 #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1070
 
diff --git a/Source/core/platform/text/win/LocaleWin.cpp b/Source/core/platform/text/win/LocaleWin.cpp
index ba3ff74..575741c 100644
--- a/Source/core/platform/text/win/LocaleWin.cpp
+++ b/Source/core/platform/text/win/LocaleWin.cpp
@@ -125,7 +125,7 @@
     String localeLanguageCode = extractLanguageCode(locale);
     if (equalIgnoringCase(localeLanguageCode, userDefaultLanguageCode))
         return userDefaultLCID;
-    return localeNameToLCID(locale.charactersWithNullTermination(), 0);
+    return localeNameToLCID(locale.charactersWithNullTermination().data(), 0);
 }
 
 static LCID LCIDFromLocale(const AtomicString& locale)
diff --git a/Source/core/plugins/PluginView.h b/Source/core/plugins/PluginView.h
index 6ccf69b..2a4a1ee 100644
--- a/Source/core/plugins/PluginView.h
+++ b/Source/core/plugins/PluginView.h
@@ -28,14 +28,15 @@
 
 #include "core/platform/ScrollTypes.h"
 #include "core/platform/Widget.h"
+#include <bindings/npruntime.h>
 #include <wtf/text/WTFString.h>
 
-struct NPObject;
-
 namespace WebKit { class WebLayer; }
 
 namespace WebCore {
 
+class ResourceError;
+class ResourceResponse;
 class Scrollbar;
 
 class PluginView : public Widget {
@@ -44,11 +45,18 @@
 
     virtual WebKit::WebLayer* platformLayer() const { return 0; }
     virtual NPObject* scriptableObject() { return 0; }
+    virtual NPP pluginNPP() = 0;
+
     virtual bool getFormValue(String&) { return false; }
     virtual bool wantsWheelEvents() { return false; }
     virtual bool supportsKeyboardFocus() const { return false; }
     virtual bool canProcessDrag() const { return false; }
 
+    virtual void didReceiveResponse(const ResourceResponse&) { }
+    virtual void didReceiveData(const char*, int) { }
+    virtual void didFinishLoading() { }
+    virtual void didFailLoading(const ResourceError&) { }
+
 protected:
     PluginView() : Widget() { }
 };
diff --git a/Source/core/rendering/AutoTableLayout.cpp b/Source/core/rendering/AutoTableLayout.cpp
index 52172d2..fe43249 100644
--- a/Source/core/rendering/AutoTableLayout.cpp
+++ b/Source/core/rendering/AutoTableLayout.cpp
@@ -113,11 +113,6 @@
                         if (cellLogicalWidth.isPositive() && (!columnLayout.logicalWidth.isPercent() || cellLogicalWidth.value() > columnLayout.logicalWidth.value()))
                             columnLayout.logicalWidth = cellLogicalWidth;
                         break;
-                    case Relative:
-                        // FIXME: Need to understand this case and whether it makes sense to compare values
-                        // which are not necessarily of the same type.
-                        if (cellLogicalWidth.value() > columnLayout.logicalWidth.value())
-                            columnLayout.logicalWidth = cellLogicalWidth;
                     default:
                         break;
                     }
@@ -281,7 +276,7 @@
         unsigned span = cell->colSpan();
 
         Length cellLogicalWidth = cell->styleOrColLogicalWidth();
-        if (!cellLogicalWidth.isRelative() && cellLogicalWidth.isZero())
+        if (cellLogicalWidth.isZero())
             cellLogicalWidth = Length(); // make it Auto
 
         unsigned effCol = m_table->colToEffCol(cell->col());
@@ -496,7 +491,6 @@
         calcEffectiveLogicalWidth();
 
     bool havePercent = false;
-    int totalRelative = 0;
     int numAuto = 0;
     int numFixed = 0;
     float totalAuto = 0;
@@ -516,9 +510,6 @@
             havePercent = true;
             totalPercent += logicalWidth.percent();
             break;
-        case Relative:
-            totalRelative += logicalWidth.value();
-            break;
         case Fixed:
             numFixed++;
             totalFixed += m_layoutStruct[i].effectiveMaxLogicalWidth;
@@ -577,19 +568,6 @@
         }
     }
 
-    // now satisfy relative
-    if (available > 0) {
-        for (size_t i = 0; i < nEffCols; ++i) {
-            Length& logicalWidth = m_layoutStruct[i].effectiveLogicalWidth;
-            if (logicalWidth.isRelative() && logicalWidth.value() != 0) {
-                // width=0* gets effMinWidth.
-                int cellLogicalWidth = logicalWidth.value() * tableLogicalWidth / totalRelative;
-                available += m_layoutStruct[i].computedLogicalWidth - cellLogicalWidth;
-                m_layoutStruct[i].computedLogicalWidth = cellLogicalWidth;
-            }
-        }
-    }
-
     // now satisfy variable
     if (available > 0 && numAuto) {
         available += allocAuto; // this gets redistributed
@@ -653,9 +631,8 @@
     if (available < 0) {
         // Need to reduce cells with the following prioritization:
         // (1) Auto
-        // (2) Relative
-        // (3) Fixed
-        // (4) Percent
+        // (2) Fixed
+        // (3) Percent
         // This is basically the reverse of how we grew the cells.
         if (available < 0) {
             int logicalWidthBeyondMin = 0;
@@ -686,30 +663,6 @@
             for (unsigned i = nEffCols; i; ) {
                 --i;
                 Length& logicalWidth = m_layoutStruct[i].effectiveLogicalWidth;
-                if (logicalWidth.isRelative())
-                    logicalWidthBeyondMin += m_layoutStruct[i].computedLogicalWidth - m_layoutStruct[i].effectiveMinLogicalWidth;
-            }
-            
-            for (unsigned i = nEffCols; i && logicalWidthBeyondMin > 0; ) {
-                --i;
-                Length& logicalWidth = m_layoutStruct[i].effectiveLogicalWidth;
-                if (logicalWidth.isRelative()) {
-                    int minMaxDiff = m_layoutStruct[i].computedLogicalWidth - m_layoutStruct[i].effectiveMinLogicalWidth;
-                    int reduce = available * minMaxDiff / logicalWidthBeyondMin;
-                    m_layoutStruct[i].computedLogicalWidth += reduce;
-                    available -= reduce;
-                    logicalWidthBeyondMin -= minMaxDiff;
-                    if (available >= 0)
-                        break;
-                }
-            }
-        }
-
-        if (available < 0) {
-            int logicalWidthBeyondMin = 0;
-            for (unsigned i = nEffCols; i; ) {
-                --i;
-                Length& logicalWidth = m_layoutStruct[i].effectiveLogicalWidth;
                 if (logicalWidth.isFixed())
                     logicalWidthBeyondMin += m_layoutStruct[i].computedLogicalWidth - m_layoutStruct[i].effectiveMinLogicalWidth;
             }
diff --git a/Source/core/rendering/CompositingReasons.h b/Source/core/rendering/CompositingReasons.h
new file mode 100644
index 0000000..0e35e82
--- /dev/null
+++ b/Source/core/rendering/CompositingReasons.h
@@ -0,0 +1,63 @@
+// Copyright 2013 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef CompositingReasons_h
+#define CompositingReasons_h
+
+#include "wtf/MathExtras.h"
+
+namespace WebCore {
+
+const uint64_t CompositingReasonNone                                   = 0;
+
+// Intrinsic reasons that can be known right away by the layer
+const uint64_t CompositingReason3DTransform                            = UINT64_C(1) << 0;
+const uint64_t CompositingReasonVideo                                  = UINT64_C(1) << 1;
+const uint64_t CompositingReasonCanvas                                 = UINT64_C(1) << 2;
+const uint64_t CompositingReasonPlugin                                 = UINT64_C(1) << 3;
+const uint64_t CompositingReasonIFrame                                 = UINT64_C(1) << 4;
+const uint64_t CompositingReasonBackfaceVisibilityHidden               = UINT64_C(1) << 5;
+const uint64_t CompositingReasonAnimation                              = UINT64_C(1) << 6;
+const uint64_t CompositingReasonFilters                                = UINT64_C(1) << 7;
+const uint64_t CompositingReasonPositionFixed                          = UINT64_C(1) << 8;
+const uint64_t CompositingReasonPositionSticky                         = UINT64_C(1) << 9;
+const uint64_t CompositingReasonOverflowScrollingTouch                 = UINT64_C(1) << 10;
+const uint64_t CompositingReasonBlending                               = UINT64_C(1) << 11;
+
+// Overlap reasons that require knowing what's behind you in paint-order before knowing the answer
+const uint64_t CompositingReasonAssumedOverlap                         = UINT64_C(1) << 12;
+const uint64_t CompositingReasonOverlap                                = UINT64_C(1) << 13;
+const uint64_t CompositingReasonNegativeZIndexChildren                 = UINT64_C(1) << 14;
+
+// Subtree reasons that require knowing what the status of your subtree is before knowing the answer
+const uint64_t CompositingReasonTransformWithCompositedDescendants     = UINT64_C(1) << 15;
+const uint64_t CompositingReasonOpacityWithCompositedDescendants       = UINT64_C(1) << 16;
+const uint64_t CompositingReasonMaskWithCompositedDescendants          = UINT64_C(1) << 17;
+const uint64_t CompositingReasonReflectionWithCompositedDescendants    = UINT64_C(1) << 18;
+const uint64_t CompositingReasonFilterWithCompositedDescendants        = UINT64_C(1) << 19;
+const uint64_t CompositingReasonBlendingWithCompositedDescendants      = UINT64_C(1) << 20;
+const uint64_t CompositingReasonClipsCompositingDescendants            = UINT64_C(1) << 21;
+const uint64_t CompositingReasonPerspective                            = UINT64_C(1) << 22;
+const uint64_t CompositingReasonPreserve3D                             = UINT64_C(1) << 23;
+const uint64_t CompositingReasonReflectionOfCompositedParent           = UINT64_C(1) << 24;
+
+// The root layer is a special case that may be forced to be a layer, but also it needs to be
+// a layer if anything else in the subtree is composited.
+const uint64_t CompositingReasonRoot                                   = UINT64_C(1) << 25;
+
+// RenderLayerBacking internal hierarchy reasons
+const uint64_t CompositingReasonLayerForClip                           = UINT64_C(1) << 26;
+const uint64_t CompositingReasonLayerForScrollbar                      = UINT64_C(1) << 27;
+const uint64_t CompositingReasonLayerForScrollingContainer             = UINT64_C(1) << 28;
+const uint64_t CompositingReasonLayerForForeground                     = UINT64_C(1) << 29;
+const uint64_t CompositingReasonLayerForBackground                     = UINT64_C(1) << 30;
+const uint64_t CompositingReasonLayerForMask                           = UINT64_C(1) << 31;
+
+// Note: if you add more reasons here, you will need to update WebCompositingReasons as well.
+typedef uint64_t CompositingReasons;
+
+
+} // namespace WebCore
+
+#endif // CompositingReasons_h
diff --git a/Source/core/rendering/FilterEffectRenderer.cpp b/Source/core/rendering/FilterEffectRenderer.cpp
index 38a8fe0..dc57d05 100644
--- a/Source/core/rendering/FilterEffectRenderer.cpp
+++ b/Source/core/rendering/FilterEffectRenderer.cpp
@@ -229,6 +229,15 @@
     FilterEffectList oldEffects;
     m_effects.swap(oldEffects);
 
+    // Inverse zoom the pre-zoomed CSS shorthand filters, so that they are in the zoom as the unzoomed reference filters
+    const RenderStyle* style = renderer->style();
+    float zoom = style ? style->effectiveZoom() : 1.0f;
+    float invZoom = 1.0f / zoom;
+    // Apply zoom to filter region here so that applyHorizontalScale/applyVerticalScale will
+    // work while create hardware filters through FE<some filter effect>::createImageFilter()
+    setFilterRegion(FloatRect(0, 0, 1, 1));
+    setAbsoluteFilterRegion(FloatRect(0, 0, zoom, zoom));
+
     RefPtr<FilterEffect> previousEffect = m_sourceGraphic;
     for (size_t i = 0; i < operations.operations().size(); ++i) {
         RefPtr<FilterEffect> effect;
@@ -361,14 +370,16 @@
         }
         case FilterOperation::BLUR: {
             BlurFilterOperation* blurOperation = static_cast<BlurFilterOperation*>(filterOperation);
-            float stdDeviation = floatValueForLength(blurOperation->stdDeviation(), 0);
+            float stdDeviation = floatValueForLength(blurOperation->stdDeviation(), 0) * invZoom;
             effect = FEGaussianBlur::create(this, stdDeviation, stdDeviation);
             break;
         }
         case FilterOperation::DROP_SHADOW: {
             DropShadowFilterOperation* dropShadowOperation = static_cast<DropShadowFilterOperation*>(filterOperation);
-            effect = FEDropShadow::create(this, dropShadowOperation->stdDeviation(), dropShadowOperation->stdDeviation(),
-                                                dropShadowOperation->x(), dropShadowOperation->y(), dropShadowOperation->color(), 1);
+            float stdDeviation = dropShadowOperation->stdDeviation() * invZoom;
+            float x = dropShadowOperation->x() * invZoom;
+            float y = dropShadowOperation->y() * invZoom;
+            effect = FEDropShadow::create(this, stdDeviation, stdDeviation, x, y, dropShadowOperation->color(), 1);
             break;
         }
         case FilterOperation::CUSTOM:
@@ -479,10 +490,15 @@
         return false;
     }
 
+    // Get the zoom factor to scale the filterSourceRect input
+    const RenderLayerModelObject* renderer = renderLayer->renderer();
+    const RenderStyle* style = renderer ? renderer->style() : 0;
+    float zoom = style ? style->effectiveZoom() : 1.0f;
+
     AffineTransform absoluteTransform;
     absoluteTransform.translate(filterBoxRect.x(), filterBoxRect.y());
     filter->setAbsoluteTransform(absoluteTransform);
-    filter->setAbsoluteFilterRegion(filterSourceRect);
+    filter->setAbsoluteFilterRegion(AffineTransform().scale(zoom).mapRect(filterSourceRect));
     filter->setFilterRegion(absoluteTransform.inverse().mapRect(filterSourceRect));
     filter->lastEffect()->determineFilterPrimitiveSubregion();
     
diff --git a/Source/core/rendering/FlowThreadController.cpp b/Source/core/rendering/FlowThreadController.cpp
index fed0559..7ba712b 100644
--- a/Source/core/rendering/FlowThreadController.cpp
+++ b/Source/core/rendering/FlowThreadController.cpp
@@ -116,7 +116,7 @@
 void FlowThreadController::unregisterNamedFlowContentNode(Node* contentNode)
 {
     ASSERT(contentNode && contentNode->isElementNode());
-    HashMap<Node*, RenderNamedFlowThread*>::iterator it = m_mapNamedFlowContentNodes.find(contentNode);
+    HashMap<const Node*, RenderNamedFlowThread*>::iterator it = m_mapNamedFlowContentNodes.find(contentNode);
     ASSERT(it != m_mapNamedFlowContentNodes.end());
     ASSERT(it->value);
     ASSERT(it->value->hasContentNode(contentNode));
@@ -225,6 +225,11 @@
     }
 }
 
+bool FlowThreadController::isContentNodeRegisteredWithAnyNamedFlow(const Node* contentNode) const
+{
+    return m_mapNamedFlowContentNodes.contains(contentNode);
+}
+
 #ifndef NDEBUG
 bool FlowThreadController::isAutoLogicalHeightRegionsCountConsistent() const
 {
diff --git a/Source/core/rendering/FlowThreadController.h b/Source/core/rendering/FlowThreadController.h
index c0b6a1b..0f014cd 100644
--- a/Source/core/rendering/FlowThreadController.h
+++ b/Source/core/rendering/FlowThreadController.h
@@ -66,6 +66,7 @@
 
     void registerNamedFlowContentNode(Node*, RenderNamedFlowThread*);
     void unregisterNamedFlowContentNode(Node*);
+    bool isContentNodeRegisteredWithAnyNamedFlow(const Node*) const;
 
     bool hasFlowThreadsWithAutoLogicalHeightRegions() const { return m_flowThreadsWithAutoLogicalHeightRegions; }
     void incrementFlowThreadsWithAutoLogicalHeightRegions() { ++m_flowThreadsWithAutoLogicalHeightRegions; }
@@ -91,7 +92,7 @@
     unsigned m_flowThreadsWithAutoLogicalHeightRegions;
     OwnPtr<RenderNamedFlowThreadList> m_renderNamedFlowThreadList;
     // maps a content node to its render flow thread.
-    HashMap<Node*, RenderNamedFlowThread*> m_mapNamedFlowContentNodes;
+    HashMap<const Node*, RenderNamedFlowThread*> m_mapNamedFlowContentNodes;
 };
 
 }
diff --git a/Source/core/rendering/LayoutState.cpp b/Source/core/rendering/LayoutState.cpp
index 8dd2d0c..7573e4e 100644
--- a/Source/core/rendering/LayoutState.cpp
+++ b/Source/core/rendering/LayoutState.cpp
@@ -38,7 +38,7 @@
     : m_columnInfo(columnInfo)
     , m_lineGrid(0)
     , m_next(prev)
-    , m_exclusionShapeInsideInfo(0)
+    , m_shapeInsideInfo(0)
 #ifndef NDEBUG
     , m_renderer(renderer)
 #endif
@@ -109,9 +109,9 @@
 
     if (renderer->isRenderBlock()) {
         const RenderBlock* renderBlock = toRenderBlock(renderer);
-        m_exclusionShapeInsideInfo = renderBlock->exclusionShapeInsideInfo();
-        if (!m_exclusionShapeInsideInfo && m_next->m_exclusionShapeInsideInfo && renderBlock->allowsExclusionShapeInsideInfoSharing())
-            m_exclusionShapeInsideInfo = m_next->m_exclusionShapeInsideInfo;
+        m_shapeInsideInfo = renderBlock->shapeInsideInfo();
+        if (!m_shapeInsideInfo && m_next->m_shapeInsideInfo && renderBlock->allowsShapeInsideInfoSharing())
+            m_shapeInsideInfo = m_next->m_shapeInsideInfo;
     }
 
     m_layoutDelta = m_next->m_layoutDelta;
@@ -143,7 +143,7 @@
     , m_columnInfo(0)
     , m_lineGrid(0)
     , m_next(0)
-    , m_exclusionShapeInsideInfo(0)
+    , m_shapeInsideInfo(0)
     , m_pageLogicalHeight(0)
 #ifndef NDEBUG
     , m_renderer(root)
diff --git a/Source/core/rendering/LayoutState.h b/Source/core/rendering/LayoutState.h
index 3f2fe56..eac3822 100644
--- a/Source/core/rendering/LayoutState.h
+++ b/Source/core/rendering/LayoutState.h
@@ -38,7 +38,7 @@
 class RenderBox;
 class RenderObject;
 class RenderFlowThread;
-class ExclusionShapeInsideInfo;
+class ShapeInsideInfo;
 
 class LayoutState {
     WTF_MAKE_NONCOPYABLE(LayoutState);
@@ -54,7 +54,7 @@
         , m_columnInfo(0)
         , m_lineGrid(0)
         , m_next(0)
-        , m_exclusionShapeInsideInfo(0)
+        , m_shapeInsideInfo(0)
         , m_pageLogicalHeight(0)
 #ifndef NDEBUG
         , m_renderer(0)
@@ -94,7 +94,7 @@
 
     bool needsBlockDirectionLocationSetBeforeLayout() const { return m_lineGrid || (m_isPaginated && m_pageLogicalHeight); }
 
-    ExclusionShapeInsideInfo* exclusionShapeInsideInfo() const { return m_exclusionShapeInsideInfo; }
+    ShapeInsideInfo* shapeInsideInfo() const { return m_shapeInsideInfo; }
 private:
     // The normal operator new is disallowed.
     void* operator new(size_t) throw();
@@ -119,7 +119,7 @@
     // The current line grid that we're snapping to and the offset of the start of the grid.
     RenderBlock* m_lineGrid;
     LayoutState* m_next;
-    ExclusionShapeInsideInfo* m_exclusionShapeInsideInfo;
+    ShapeInsideInfo* m_shapeInsideInfo;
 
     // FIXME: Distinguish between the layout clip rect and the paint clip rect which may be larger,
     // e.g., because of composited scrolling.
diff --git a/Source/core/rendering/OrderIterator.cpp b/Source/core/rendering/OrderIterator.cpp
new file mode 100644
index 0000000..b11cd58
--- /dev/null
+++ b/Source/core/rendering/OrderIterator.cpp
@@ -0,0 +1,109 @@
+/*
+ * Copyright (C) 2011 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#include "config.h"
+#include "core/rendering/OrderIterator.h"
+
+#include "core/rendering/RenderFlexibleBox.h"
+
+namespace WebCore {
+
+OrderIterator::OrderIterator(const RenderFlexibleBox* flexibleBox)
+    : m_flexibleBox(flexibleBox)
+    , m_currentChild(0)
+    , m_orderValuesIterator(0)
+{
+}
+
+void OrderIterator::setOrderValues(Vector<int>& orderValues)
+{
+    reset();
+    m_orderValues.clear();
+
+    if (orderValues.isEmpty())
+        return;
+
+    std::sort(orderValues.begin(), orderValues.end());
+
+
+    // This is inefficient if there are many repeated values, but
+    // saves a lot of allocations when the values are unique. By far,
+    // the common case is that there's exactly one item in the list
+    // (the default order value of 0).
+    m_orderValues.reserveInitialCapacity(orderValues.size());
+
+    int previous = orderValues[0];
+    m_orderValues.append(previous);
+    for (size_t i = 1; i < orderValues.size(); ++i) {
+        int current = orderValues[i];
+        if (current == previous)
+            continue;
+        m_orderValues.append(current);
+        previous = current;
+    }
+    m_orderValues.shrinkToFit();
+}
+
+RenderBox* OrderIterator::first()
+{
+    reset();
+    return next();
+}
+
+RenderBox* OrderIterator::next()
+{
+    do {
+        if (!m_currentChild) {
+            if (m_orderValuesIterator == m_orderValues.end())
+                return 0;
+            if (m_orderValuesIterator) {
+                ++m_orderValuesIterator;
+                if (m_orderValuesIterator == m_orderValues.end())
+                    return 0;
+            } else {
+                m_orderValuesIterator = m_orderValues.begin();
+            }
+
+            m_currentChild = m_flexibleBox->firstChildBox();
+        } else {
+            m_currentChild = m_currentChild->nextSiblingBox();
+        }
+    } while (!m_currentChild || m_currentChild->style()->order() != *m_orderValuesIterator);
+
+    return m_currentChild;
+}
+
+void OrderIterator::reset()
+{
+    m_currentChild = 0;
+    m_orderValuesIterator = 0;
+}
+
+} // namespace WebCore
diff --git a/Source/core/fileapi/ThreadableBlobRegistry.h b/Source/core/rendering/OrderIterator.h
similarity index 69%
copy from Source/core/fileapi/ThreadableBlobRegistry.h
copy to Source/core/rendering/OrderIterator.h
index a72b202..9c36d7f 100644
--- a/Source/core/fileapi/ThreadableBlobRegistry.h
+++ b/Source/core/rendering/OrderIterator.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2010 Google Inc. All rights reserved.
+ * Copyright (C) 2011 Google Inc. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,25 +28,34 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ThreadableBlobRegistry_h
-#define ThreadableBlobRegistry_h
+#ifndef OrderIterator_h
+#define OrderIterator_h
 
-#include "wtf/PassOwnPtr.h"
-#include "wtf/PassRefPtr.h"
+#include "wtf/Noncopyable.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
-class BlobData;
-class KURL;
-class SecurityOrigin;
+class RenderBox;
+class RenderFlexibleBox;
 
-class ThreadableBlobRegistry {
+class OrderIterator {
+    WTF_MAKE_NONCOPYABLE(OrderIterator);
 public:
-    static void registerBlobURL(const KURL&, PassOwnPtr<BlobData>);
-    static void registerBlobURL(SecurityOrigin*, const KURL&, const KURL& srcURL);
-    static void unregisterBlobURL(const KURL&);
+    OrderIterator(const RenderFlexibleBox*);
+    void setOrderValues(Vector<int>&);
+    RenderBox* currentChild() const { return m_currentChild; }
+    RenderBox* first();
+    RenderBox* next();
+    void reset();
+
+private:
+    const RenderFlexibleBox* m_flexibleBox;
+    RenderBox* m_currentChild;
+    Vector<int> m_orderValues;
+    Vector<int>::const_iterator m_orderValuesIterator;
 };
 
 } // namespace WebCore
 
-#endif // ThreadableBlobRegistry_h
+#endif //  OrderIterator_h
diff --git a/Source/core/dom/RegisteredEventListener.cpp b/Source/core/rendering/RegionOversetState.h
similarity index 69%
rename from Source/core/dom/RegisteredEventListener.cpp
rename to Source/core/rendering/RegionOversetState.h
index 6153b5c..e29e370 100644
--- a/Source/core/dom/RegisteredEventListener.cpp
+++ b/Source/core/rendering/RegionOversetState.h
@@ -1,9 +1,4 @@
 /*
- * Copyright (C) 2001 Peter Kelly (pmk@post.com)
- * Copyright (C) 2001 Tobias Anton (anton@stud.fbi.fh-darmstadt.de)
- * Copyright (C) 2006 Samuel Weinig (sam.weinig@gmail.com)
- * Copyright (C) 2003, 2005, 2006, 2008 Apple Inc. All rights reserved.
- *
  * This library is free software; you can redistribute it and/or
  * modify it under the terms of the GNU Library General Public
  * License as published by the Free Software Foundation; either
@@ -18,13 +13,21 @@
  * along with this library; see the file COPYING.LIB.  If not, write to
  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  * Boston, MA 02110-1301, USA.
+ *
  */
 
-#include "config.h"
-#include "core/dom/RegisteredEventListener.h"
-
-#include "core/dom/EventListener.h"
+#ifndef RegionOversetState_h
+#define RegionOversetState_h
 
 namespace WebCore {
 
+enum RegionOversetState {
+    RegionUndefined,
+    RegionEmpty,
+    RegionFit,
+    RegionOverset
+};
+
 } // namespace WebCore
+
+#endif // RegionOversetState_h
diff --git a/Source/core/rendering/RenderBlock.cpp b/Source/core/rendering/RenderBlock.cpp
index be6d902..099adda 100644
--- a/Source/core/rendering/RenderBlock.cpp
+++ b/Source/core/rendering/RenderBlock.cpp
@@ -42,8 +42,6 @@
 #include "core/platform/graphics/GraphicsContextStateSaver.h"
 #include "core/platform/graphics/transforms/TransformState.h"
 #include "core/rendering/ColumnInfo.h"
-#include "core/rendering/exclusions/ExclusionShapeInsideInfo.h"
-#include "core/rendering/exclusions/ExclusionShapeOutsideInfo.h"
 #include "core/rendering/HitTestLocation.h"
 #include "core/rendering/HitTestResult.h"
 #include "core/rendering/InlineIterator.h"
@@ -62,6 +60,8 @@
 #include "core/rendering/RenderTextFragment.h"
 #include "core/rendering/RenderTheme.h"
 #include "core/rendering/RenderView.h"
+#include "core/rendering/shapes/ShapeInsideInfo.h"
+#include "core/rendering/shapes/ShapeOutsideInfo.h"
 #include "core/rendering/svg/SVGTextRunRenderingContext.h"
 #include <wtf/StdLibExtras.h>
 #include <wtf/MemoryInstrumentationHashMap.h>
@@ -353,9 +353,7 @@
     
     RenderStyle* newStyle = style();
 
-    // FIXME: Bug 89993: Style changes should affect the ExclusionShapeInsideInfos for other render blocks that
-    // share the same ExclusionShapeInsideInfo
-    updateExclusionShapeInsideInfoAfterStyleChange(newStyle->resolvedShapeInside(), oldStyle ? oldStyle->resolvedShapeInside() : 0);
+    updateShapeInsideInfoAfterStyleChange(newStyle->resolvedShapeInside(), oldStyle ? oldStyle->resolvedShapeInside() : 0);
 
     if (!isAnonymousBlock()) {
         // Ensure that all of our continuation blocks pick up the new style.
@@ -572,7 +570,7 @@
         cloneBlock->setChildrenInline(childrenInline());
     }
     else {
-        RenderObject* cloneRenderer = toElement(node())->createRenderer(renderArena(), style());
+        RenderObject* cloneRenderer = toElement(node())->createRenderer(style());
         cloneBlock = toRenderBlock(cloneRenderer);
         cloneBlock->setStyle(style());
 
@@ -1427,35 +1425,35 @@
     invalidateBackgroundObscurationStatus();
 }
 
-void RenderBlock::updateExclusionShapeInsideInfoAfterStyleChange(const ExclusionShapeValue* shapeInside, const ExclusionShapeValue* oldShapeInside)
+void RenderBlock::updateShapeInsideInfoAfterStyleChange(const ShapeValue* shapeInside, const ShapeValue* oldShapeInside)
 {
     // FIXME: A future optimization would do a deep comparison for equality.
     if (shapeInside == oldShapeInside)
         return;
 
     if (shapeInside) {
-        ExclusionShapeInsideInfo* exclusionShapeInsideInfo = ensureExclusionShapeInsideInfo();
-        exclusionShapeInsideInfo->dirtyShapeSize();
+        ShapeInsideInfo* shapeInsideInfo = ensureShapeInsideInfo();
+        shapeInsideInfo->dirtyShapeSize();
     } else {
-        setExclusionShapeInsideInfo(nullptr);
+        setShapeInsideInfo(nullptr);
         markShapeInsideDescendantsForLayout();
     }
 }
 
-static inline bool exclusionInfoRequiresRelayout(const RenderBlock* block)
+static inline bool shapeInfoRequiresRelayout(const RenderBlock* block)
 {
-    ExclusionShapeInsideInfo* info = block->exclusionShapeInsideInfo();
+    ShapeInsideInfo* info = block->shapeInsideInfo();
     if (info)
         info->setNeedsLayout(info->shapeSizeDirty());
     else
-        info = block->layoutExclusionShapeInsideInfo();
+        info = block->layoutShapeInsideInfo();
     return info && info->needsLayout();
 }
 
-bool RenderBlock::updateRegionsAndExclusionsLogicalSize(RenderFlowThread* flowThread)
+bool RenderBlock::updateRegionsAndShapesLogicalSize(RenderFlowThread* flowThread)
 {
-    if (!flowThread && !exclusionShapeInsideInfo())
-        return exclusionInfoRequiresRelayout(this);
+    if (!flowThread && !shapeInsideInfo())
+        return shapeInfoRequiresRelayout(this);
 
     LayoutUnit oldHeight = logicalHeight();
     LayoutUnit oldTop = logicalTop();
@@ -1465,7 +1463,7 @@
     setLogicalHeight(LayoutUnit::max() / 2);
     updateLogicalHeight();
 
-    computeExclusionShapeSize();
+    computeShapeSize();
 
     // Set our start and end regions. No regions above or below us will be considered by our children. They are
     // effectively clamped to our region range.
@@ -1474,22 +1472,22 @@
     setLogicalHeight(oldHeight);
     setLogicalTop(oldTop);
     
-    return exclusionInfoRequiresRelayout(this);
+    return shapeInfoRequiresRelayout(this);
 }
 
-void RenderBlock::computeExclusionShapeSize()
+void RenderBlock::computeShapeSize()
 {
-    ExclusionShapeInsideInfo* exclusionShapeInsideInfo = this->exclusionShapeInsideInfo();
-    if (exclusionShapeInsideInfo) {
+    ShapeInsideInfo* shapeInsideInfo = this->shapeInsideInfo();
+    if (shapeInsideInfo) {
         bool percentageLogicalHeightResolvable = percentageLogicalHeightIsResolvableFromBlock(this, false);
-        exclusionShapeInsideInfo->setShapeSize(logicalWidth(), percentageLogicalHeightResolvable ? logicalHeight() : LayoutUnit());
+        shapeInsideInfo->setShapeSize(logicalWidth(), percentageLogicalHeightResolvable ? logicalHeight() : LayoutUnit());
     }
 }
 
-void RenderBlock::updateRegionsAndExclusionsAfterChildLayout(RenderFlowThread* flowThread, bool heightChanged)
+void RenderBlock::updateRegionsAndShapesAfterChildLayout(RenderFlowThread* flowThread, bool heightChanged)
 {
     // A previous sibling has changed dimension, so we need to relayout the shape with the content
-    ExclusionShapeInsideInfo* shapeInsideInfo = layoutExclusionShapeInsideInfo();
+    ShapeInsideInfo* shapeInsideInfo = layoutShapeInsideInfo();
     if (heightChanged && shapeInsideInfo)
         shapeInsideInfo->dirtyShapeSize();
 
@@ -1580,7 +1578,7 @@
     RenderFlowThread* flowThread = flowThreadContainingBlock();
     if (logicalWidthChangedInRegions(flowThread))
         relayoutChildren = true;
-    if (updateRegionsAndExclusionsLogicalSize(flowThread))
+    if (updateRegionsAndShapesLogicalSize(flowThread))
         relayoutChildren = true;
 
     // We use four values, maxTopPos, maxTopNeg, maxBottomPos, and maxBottomNeg, to track
@@ -1650,7 +1648,7 @@
 
     layoutPositionedObjects(relayoutChildren || isRoot());
 
-    updateRegionsAndExclusionsAfterChildLayout(flowThread, heightChanged);
+    updateRegionsAndShapesAfterChildLayout(flowThread, heightChanged);
 
     // Add overflow from children (unless we're multi-column, since in that case all our child overflow is clipped anyway).
     computeOverflow(oldClientAfterEdge);
@@ -1774,8 +1772,8 @@
     // Add visual overflow from theme.
     addVisualOverflowFromTheme();
 
-    if (isRenderFlowThread())
-        toRenderFlowThread(this)->computeOverflowStateForRegions(oldClientAfterEdge);
+    if (isRenderNamedFlowThread())
+        toRenderNamedFlowThread(this)->computeOversetStateForRegions(oldClientAfterEdge);
 }
 
 void RenderBlock::addOverflowFromBlockChildren()
@@ -3910,10 +3908,10 @@
         o->computeAndSetBlockDirectionMargins(this);
     }
 
-    ExclusionShapeOutsideInfo* shapeOutside = o->exclusionShapeOutsideInfo();
+    ShapeOutsideInfo* shapeOutside = o->shapeOutsideInfo();
     if (shapeOutside) {
         shapeOutside->setShapeSize(o->logicalWidth(), o->logicalHeight());
-        // The CSS Exclusions specification says that the margins are ignored
+        // The CSS Shapes specification says that the margins are ignored
         // when a float has a shape outside.
         setLogicalWidthForFloat(newObj, shapeOutside->shapeLogicalWidth());
     } else
@@ -3989,7 +3987,7 @@
     LayoutUnit logicalLeftOffset = logicalLeftOffsetForContent(logicalTopOffset); // Constant part of left offset.
     LayoutUnit logicalRightOffset; // Constant part of right offset.
     // FIXME Bug 102948: This only works for shape outside directly set on this block.
-    ExclusionShapeInsideInfo* shapeInsideInfo = exclusionShapeInsideInfo();
+    ShapeInsideInfo* shapeInsideInfo = this->shapeInsideInfo();
     // FIXME Bug 102846: Take into account the height of the content. The offset should be
     // equal to the maximum segment length.
     if (shapeInsideInfo && shapeInsideInfo->hasSegments() && shapeInsideInfo->segments().size() == 1) {
@@ -4142,8 +4140,8 @@
         }
 
         setLogicalTopForFloat(floatingObject, floatLogicalLocation.y());
-        if (childBox->exclusionShapeOutsideInfo())
-            setLogicalHeightForFloat(floatingObject, childBox->exclusionShapeOutsideInfo()->shapeLogicalHeight());
+        if (childBox->shapeOutsideInfo())
+            setLogicalHeightForFloat(floatingObject, childBox->shapeOutsideInfo()->shapeLogicalHeight());
         else
             setLogicalHeightForFloat(floatingObject, logicalHeightForChild(childBox) + marginBeforeForChild(childBox) + marginAfterForChild(childBox));
 
@@ -4324,7 +4322,7 @@
         m_floatingObjects->placedFloatsTree().allOverlapsWithAdapter(adapter);
 
         if (const FloatingObject* lastFloat = adapter.lastFloat()) {
-            if (ExclusionShapeOutsideInfo* shapeOutside = lastFloat->renderer()->exclusionShapeOutsideInfo()) {
+            if (ShapeOutsideInfo* shapeOutside = lastFloat->renderer()->shapeOutsideInfo()) {
                 shapeOutside->computeSegmentsForLine(logicalTop - logicalTopForFloat(lastFloat) + shapeOutside->shapeLogicalTop(), logicalHeight);
                 left += shapeOutside->rightSegmentShapeBoundingBoxDelta();
             }
@@ -4377,7 +4375,7 @@
         m_floatingObjects->placedFloatsTree().allOverlapsWithAdapter(adapter);
 
         if (const FloatingObject* lastFloat = adapter.lastFloat()) {
-            if (ExclusionShapeOutsideInfo* shapeOutside = lastFloat->renderer()->exclusionShapeOutsideInfo()) {
+            if (ShapeOutsideInfo* shapeOutside = lastFloat->renderer()->shapeOutsideInfo()) {
                 shapeOutside->computeSegmentsForLine(logicalTop - logicalTopForFloat(lastFloat) + shapeOutside->shapeLogicalTop(), logicalHeight);
                 rightFloatOffset += shapeOutside->leftSegmentShapeBoundingBoxDelta();
             }
@@ -5773,12 +5771,9 @@
 
     maxLogicalWidth = max(minLogicalWidth, maxLogicalWidth);
 
-    if (!style()->autoWrap() && childrenInline()) {
-        minLogicalWidth = maxLogicalWidth;
-        // A horizontal marquee with inline children has no minimum width.
-        if (isMarquee() && toRenderMarquee(this)->isHorizontal())
-            minLogicalWidth = 0;
-    }
+    // A horizontal marquee with inline children has no minimum width.
+    if (childrenInline() && isMarquee() && toRenderMarquee(this)->isHorizontal())
+        minLogicalWidth = 0;
 
     if (isTableCell()) {
         Length tableCellWidth = toRenderTableCell(this)->styleOrColLogicalWidth();
@@ -6134,16 +6129,17 @@
                 // then they shouldn't be considered in the breakable char
                 // check.
                 bool hasBreakableChar, hasBreak;
-                float beginMin, endMin;
-                bool beginWS, endWS;
-                float beginMax, endMax;
-                t->trimmedPrefWidths(inlineMax, beginMin, beginWS, endMin, endWS,
-                                     hasBreakableChar, hasBreak, beginMax, endMax,
-                                     childMin, childMax, stripFrontSpaces);
+                float firstLineMinWidth, lastLineMinWidth;
+                bool hasBreakableStart, hasBreakableEnd;
+                float firstLineMaxWidth, lastLineMaxWidth;
+                t->trimmedPrefWidths(inlineMax,
+                    firstLineMinWidth, hasBreakableStart, lastLineMinWidth, hasBreakableEnd,
+                    hasBreakableChar, hasBreak, firstLineMaxWidth, lastLineMaxWidth,
+                    childMin, childMax, stripFrontSpaces);
 
                 // This text object will not be rendered, but it may still provide a breaking opportunity.
                 if (!hasBreak && childMax == 0) {
-                    if (autoWrap && (beginWS || endWS)) {
+                    if (autoWrap && (hasBreakableStart || hasBreakableEnd)) {
                         updatePreferredWidth(minLogicalWidth, inlineMin);
                         inlineMin = 0;
                     }
@@ -6160,14 +6156,14 @@
                 if (!addedTextIndent || hasRemainingNegativeTextIndent) {
                     ti = textIndent.ceilToFloat();
                     childMin += ti;
-                    beginMin += ti;
+                    firstLineMinWidth += ti;
                     
                     // It the text indent negative and larger than the child minimum, we re-use the remainder
                     // in future minimum calculations, but using the negative value again on the maximum
                     // will lead to under-counting the max pref width.
                     if (!addedTextIndent) {
                         childMax += ti;
-                        beginMax += ti;
+                        firstLineMaxWidth += ti;
                         addedTextIndent = true;
                     }
                     
@@ -6183,40 +6179,36 @@
                 if (!hasBreakableChar) {
                     inlineMin += childMin;
                 } else {
-                    // We have a breakable character.  Now we need to know if
-                    // we start and end with whitespace.
-                    if (beginWS)
-                        // Go ahead and end the current line.
+                    if (hasBreakableStart) {
                         updatePreferredWidth(minLogicalWidth, inlineMin);
-                    else {
-                        inlineMin += beginMin;
+                    } else {
+                        inlineMin += firstLineMinWidth;
                         updatePreferredWidth(minLogicalWidth, inlineMin);
                         childMin -= ti;
                     }
 
                     inlineMin = childMin;
 
-                    if (endWS) {
-                        // We end in whitespace, which means we can go ahead
-                        // and end our current line.
+                    if (hasBreakableEnd) {
                         updatePreferredWidth(minLogicalWidth, inlineMin);
                         inlineMin = 0;
                         shouldBreakLineAfterText = false;
                     } else {
                         updatePreferredWidth(minLogicalWidth, inlineMin);
-                        inlineMin = endMin;
+                        inlineMin = lastLineMinWidth;
                         shouldBreakLineAfterText = true;
                     }
                 }
 
                 if (hasBreak) {
-                    inlineMax += beginMax;
+                    inlineMax += firstLineMaxWidth;
                     updatePreferredWidth(maxLogicalWidth, inlineMax);
                     updatePreferredWidth(maxLogicalWidth, childMax);
-                    inlineMax = endMax;
+                    inlineMax = lastLineMaxWidth;
                     addedTextIndent = true;
-                } else
+                } else {
                     inlineMax += max<float>(0, childMax);
+                }
             }
 
             // Ignore spaces after a list marker.
@@ -7394,11 +7386,9 @@
     if (!isUnsplittable)
         return logicalOffset;
     LayoutUnit childLogicalHeight = logicalHeightForChild(child) + (includeMargins ? marginBeforeForChild(child) + marginAfterForChild(child) : LayoutUnit());
-    LayoutState* layoutState = view()->layoutState();
-    if (layoutState->m_columnInfo)
-        layoutState->m_columnInfo->updateMinimumColumnHeight(childLogicalHeight);
     LayoutUnit pageLogicalHeight = pageLogicalHeightForOffset(logicalOffset);
     bool hasUniformPageLogicalHeight = !flowThread || flowThread->regionsHaveUniformLogicalHeight();
+    updateMinimumPageHeight(logicalOffset, childLogicalHeight);
     if (!pageLogicalHeight || (hasUniformPageLogicalHeight && childLogicalHeight > pageLogicalHeight)
         || !hasNextPage(logicalOffset))
         return logicalOffset;
@@ -7426,6 +7416,38 @@
     return !checkRegion;
 }
 
+void RenderBlock::setPageBreak(LayoutUnit offset, LayoutUnit spaceShortage)
+{
+    if (RenderFlowThread* flowThread = flowThreadContainingBlock())
+        flowThread->setPageBreak(offsetFromLogicalTopOfFirstPage() + offset, spaceShortage);
+}
+
+void RenderBlock::updateMinimumPageHeight(LayoutUnit offset, LayoutUnit minHeight)
+{
+    if (RenderFlowThread* flowThread = flowThreadContainingBlock())
+        flowThread->updateMinimumPageHeight(offsetFromLogicalTopOfFirstPage() + offset, minHeight);
+    else if (ColumnInfo* colInfo = view()->layoutState()->m_columnInfo)
+        colInfo->updateMinimumColumnHeight(minHeight);
+}
+
+static inline LayoutUnit calculateMinimumPageHeight(RenderStyle* renderStyle, RootInlineBox* lastLine, LayoutUnit lineTop, LayoutUnit lineBottom)
+{
+    // We may require a certain minimum number of lines per page in order to satisfy
+    // orphans and widows, and that may affect the minimum page height.
+    unsigned lineCount = max<unsigned>(renderStyle->hasAutoOrphans() ? 1 : renderStyle->orphans(), renderStyle->hasAutoWidows() ? 1 : renderStyle->widows());
+    if (lineCount > 1) {
+        RootInlineBox* line = lastLine;
+        for (unsigned i = 1; i < lineCount && line->prevRootBox(); i++)
+            line = line->prevRootBox();
+
+        // FIXME: Paginating using line overflow isn't all fine. See FIXME in
+        // adjustLinePositionForPagination() for more details.
+        LayoutRect overflow = line->logicalVisualOverflowRect(line->lineTop(), line->lineBottom());
+        lineTop = min(line->lineTopWithLeading(), overflow.y());
+    }
+    return lineBottom - lineTop;
+}
+
 void RenderBlock::adjustLinePositionForPagination(RootInlineBox* lineBox, LayoutUnit& delta, RenderFlowThread* flowThread)
 {
     // FIXME: For now we paginate using line overflow.  This ensures that lines don't overlap at all when we
@@ -7449,11 +7471,9 @@
     // line and all following lines.
     LayoutRect logicalVisualOverflow = lineBox->logicalVisualOverflowRect(lineBox->lineTop(), lineBox->lineBottom());
     LayoutUnit logicalOffset = min(lineBox->lineTopWithLeading(), logicalVisualOverflow.y());
-    LayoutUnit lineHeight = max(lineBox->lineBottomWithLeading(), logicalVisualOverflow.maxY()) - logicalOffset;
-    RenderView* renderView = view();
-    LayoutState* layoutState = renderView->layoutState();
-    if (layoutState->m_columnInfo)
-        layoutState->m_columnInfo->updateMinimumColumnHeight(lineHeight);
+    LayoutUnit logicalBottom = max(lineBox->lineBottomWithLeading(), logicalVisualOverflow.maxY());
+    LayoutUnit lineHeight = logicalBottom - logicalOffset;
+    updateMinimumPageHeight(logicalOffset, calculateMinimumPageHeight(style(), lineBox, logicalOffset, logicalBottom));
     logicalOffset += delta;
     lineBox->setPaginationStrut(0);
     lineBox->setIsFirstAfterPageBreak(false);
@@ -7478,6 +7498,7 @@
         }
         LayoutUnit totalLogicalHeight = lineHeight + max<LayoutUnit>(0, logicalOffset);
         LayoutUnit pageLogicalHeightAtNewOffset = hasUniformPageLogicalHeight ? pageLogicalHeight : pageLogicalHeightForOffset(logicalOffset + remainingLogicalHeight);
+        setPageBreak(logicalOffset, lineHeight - remainingLogicalHeight);
         if (((lineBox == firstRootBox() && totalLogicalHeight < pageLogicalHeightAtNewOffset) || (!style()->hasAutoOrphans() && style()->orphans() >= lineCount(lineBox)))
             && !isOutOfFlowPositioned() && !isTableCell())
             setPaginationStrut(remainingLogicalHeight + max<LayoutUnit>(0, logicalOffset));
@@ -7524,6 +7545,21 @@
     // If the object has a page or column break value of "before", then we should shift to the top of the next page.
     LayoutUnit result = applyBeforeBreak(child, logicalTopAfterClear);
 
+    if (pageLogicalHeightForOffset(result)) {
+        LayoutUnit remainingLogicalHeight = pageRemainingLogicalHeightForOffset(result, ExcludePageBoundary);
+        LayoutUnit spaceShortage = child->logicalHeight() - remainingLogicalHeight;
+        if (spaceShortage > 0) {
+            // If the child crosses a column boundary, report a break, in case nothing inside it has already
+            // done so. The column balancer needs to know how much it has to stretch the columns to make more
+            // content fit. If no breaks are reported (but do occur), the balancer will have no clue. FIXME:
+            // This should be improved, though, because here we just pretend that the child is
+            // unsplittable. A splittable child, on the other hand, has break opportunities at every position
+            // where there's no child content, border or padding. In other words, we risk stretching more
+            // than necessary.
+            setPageBreak(result, spaceShortage);
+        }
+    }
+
     // For replaced elements and scrolled elements, we want to shift them to the next page if they don't fit on the current one.
     LayoutUnit logicalTopBeforeUnsplittableAdjustment = result;
     LayoutUnit logicalTopAfterUnsplittableAdjustment = adjustForUnsplittableChild(child, result);
@@ -8015,9 +8051,9 @@
 #if ENABLE(8BIT_TEXTRUN)
     if (length && string.is8Bit())
         return constructTextRunInternal(context, font, string.characters8(), length, style, expansion, flags);
-    return constructTextRunInternal(context, font, string.characters(), length, style, expansion, flags);
+    return constructTextRunInternal(context, font, string.bloatedCharacters(), length, style, expansion, flags);
 #else
-    return constructTextRunInternal(context, font, string.characters(), length, style, expansion, flags);
+    return constructTextRunInternal(context, font, string.bloatedCharacters(), length, style, expansion, flags);
 #endif
 }
 
diff --git a/Source/core/rendering/RenderBlock.h b/Source/core/rendering/RenderBlock.h
index ac22f29..3a92dae 100644
--- a/Source/core/rendering/RenderBlock.h
+++ b/Source/core/rendering/RenderBlock.h
@@ -27,12 +27,12 @@
 #include "core/platform/graphics/TextRun.h"
 #include "core/platform/text/TextBreakIterator.h"
 #include "core/rendering/ColumnInfo.h"
-#include "core/rendering/exclusions/ExclusionShapeInsideInfo.h"
 #include "core/rendering/GapRects.h"
 #include "core/rendering/RenderBox.h"
 #include "core/rendering/RenderLineBoxList.h"
 #include "core/rendering/RootInlineBox.h"
-#include "core/rendering/style/ExclusionShapeValue.h"
+#include "core/rendering/shapes/ShapeInsideInfo.h"
+#include "core/rendering/style/ShapeValue.h"
 #include <wtf/ListHashSet.h>
 #include <wtf/OwnPtr.h>
 
@@ -439,24 +439,24 @@
     void showLineTreeAndMark(const InlineBox* = 0, const char* = 0, const InlineBox* = 0, const char* = 0, const RenderObject* = 0) const;
 #endif
 
-    ExclusionShapeInsideInfo* ensureExclusionShapeInsideInfo()
+    ShapeInsideInfo* ensureShapeInsideInfo()
     {
         if (!m_rareData || !m_rareData->m_shapeInsideInfo)
-            setExclusionShapeInsideInfo(ExclusionShapeInsideInfo::createInfo(this));
+            setShapeInsideInfo(ShapeInsideInfo::createInfo(this));
         return m_rareData->m_shapeInsideInfo.get();
     }
-    ExclusionShapeInsideInfo* exclusionShapeInsideInfo() const
+    ShapeInsideInfo* shapeInsideInfo() const
     {
-        return m_rareData && m_rareData->m_shapeInsideInfo && ExclusionShapeInsideInfo::isEnabledFor(this) ? m_rareData->m_shapeInsideInfo.get() : 0;
+        return m_rareData && m_rareData->m_shapeInsideInfo && ShapeInsideInfo::isEnabledFor(this) ? m_rareData->m_shapeInsideInfo.get() : 0;
     }
-    void setExclusionShapeInsideInfo(PassOwnPtr<ExclusionShapeInsideInfo> value)
+    void setShapeInsideInfo(PassOwnPtr<ShapeInsideInfo> value)
     {
         if (!m_rareData)
             m_rareData = adoptPtr(new RenderBlockRareData(this));
         m_rareData->m_shapeInsideInfo = value;
     }
-    ExclusionShapeInsideInfo* layoutExclusionShapeInsideInfo() const;
-    bool allowsExclusionShapeInsideInfoSharing() const { return !isInline() && !isFloating(); }
+    ShapeInsideInfo* layoutShapeInsideInfo() const;
+    bool allowsShapeInsideInfoSharing() const { return !isInline() && !isFloating(); }
 
     virtual void reportMemoryUsage(MemoryObjectInfo*) const OVERRIDE;
     static void reportStaticMembersMemoryUsage(MemoryInstrumentation*);
@@ -564,7 +564,7 @@
         layoutInlineChildren(true, repaintLogicalTop, repaintLogicalBottom);
     }
 
-    bool updateRegionsAndExclusionsLogicalSize(RenderFlowThread*);
+    bool updateRegionsAndShapesLogicalSize(RenderFlowThread*);
     void computeRegionRangeForBlock(RenderFlowThread*);
 
     void updateBlockChildDirtyBitsBeforeLayout(bool relayoutChildren, RenderBox*);
@@ -572,9 +572,9 @@
     virtual void checkForPaginationLogicalHeightChange(LayoutUnit& pageLogicalHeight, bool& pageLogicalHeightChanged, bool& hasSpecifiedPageLogicalHeight);
 
 private:
-    void computeExclusionShapeSize();
-    void updateRegionsAndExclusionsAfterChildLayout(RenderFlowThread*, bool);
-    void updateExclusionShapeInsideInfoAfterStyleChange(const ExclusionShapeValue*, const ExclusionShapeValue* oldExclusionShape);
+    void computeShapeSize();
+    void updateRegionsAndShapesAfterChildLayout(RenderFlowThread*, bool);
+    void updateShapeInsideInfoAfterStyleChange(const ShapeValue*, const ShapeValue* oldShape);
 
     virtual RenderObjectChildList* virtualChildren() OVERRIDE FINAL { return children(); }
     virtual const RenderObjectChildList* virtualChildren() const OVERRIDE FINAL { return children(); }
@@ -777,7 +777,7 @@
 
     LayoutUnit xPositionForFloatIncludingMargin(const FloatingObject* child) const
     {
-        ExclusionShapeOutsideInfo *shapeOutside = child->renderer()->exclusionShapeOutsideInfo();
+        ShapeOutsideInfo *shapeOutside = child->renderer()->shapeOutsideInfo();
         if (shapeOutside)
             return child->x();
 
@@ -789,7 +789,7 @@
         
     LayoutUnit yPositionForFloatIncludingMargin(const FloatingObject* child) const
     {
-        ExclusionShapeOutsideInfo *shapeOutside = child->renderer()->exclusionShapeOutsideInfo();
+        ShapeOutsideInfo *shapeOutside = child->renderer()->shapeOutsideInfo();
         if (shapeOutside)
             return child->y();
 
@@ -1098,6 +1098,14 @@
 protected:
     bool pushToNextPageWithMinimumLogicalHeight(LayoutUnit& adjustment, LayoutUnit logicalOffset, LayoutUnit minimumLogicalHeight) const;
 
+    // A page break is required at some offset due to space shortage in the current fragmentainer.
+    void setPageBreak(LayoutUnit offset, LayoutUnit spaceShortage);
+
+    // Update minimum page height required to avoid fragmentation where it shouldn't occur (inside
+    // unbreakable content, between orphans and widows, etc.). This will be used as a hint to the
+    // column balancer to help set a good minimum column height.
+    void updateMinimumPageHeight(LayoutUnit offset, LayoutUnit minHeight);
+
     LayoutUnit adjustForUnsplittableChild(RenderBox* child, LayoutUnit logicalOffset, bool includeMargins = false); // If the child is unsplittable and can't fit on the current page, return the top of the next page/column.
     void adjustLinePositionForPagination(RootInlineBox*, LayoutUnit& deltaOffset, RenderFlowThread*); // Computes a deltaOffset value that put a line at the top of the next page if it doesn't fit on the current page.
     LayoutUnit adjustBlockChildForPagination(LayoutUnit logicalTopAfterClear, LayoutUnit estimateWithoutPagination, RenderBox* child, bool atBeforeSideOfBlock);
@@ -1264,7 +1272,7 @@
         RootInlineBox* m_lineGridBox;
 
         RootInlineBox* m_lineBreakToAvoidWidow;
-        OwnPtr<ExclusionShapeInsideInfo> m_shapeInsideInfo;
+        OwnPtr<ShapeInsideInfo> m_shapeInsideInfo;
         bool m_shouldBreakAtLineToAvoidWidow : 1;
         bool m_discardMarginBefore : 1;
         bool m_discardMarginAfter : 1;
diff --git a/Source/core/rendering/RenderBlockLineLayout.cpp b/Source/core/rendering/RenderBlockLineLayout.cpp
index 3f7af22..a645d5c 100644
--- a/Source/core/rendering/RenderBlockLineLayout.cpp
+++ b/Source/core/rendering/RenderBlockLineLayout.cpp
@@ -24,7 +24,6 @@
 
 #include "core/platform/text/BidiResolver.h"
 #include "core/platform/text/Hyphenation.h"
-#include "core/rendering/exclusions/ExclusionShapeInsideInfo.h"
 #include "core/rendering/InlineIterator.h"
 #include "core/rendering/InlineTextBox.h"
 #include "core/rendering/RenderCombineText.h"
@@ -39,6 +38,7 @@
 #include "core/rendering/TrailingFloatsRootInlineBox.h"
 #include "core/rendering/VerticalPositionCache.h"
 #include "core/rendering/break_lines.h"
+#include "core/rendering/shapes/ShapeInsideInfo.h"
 #include "core/rendering/svg/RenderSVGInlineText.h"
 #include "core/rendering/svg/SVGRootInlineBox.h"
 #include <wtf/RefCountedLeakCounter.h>
@@ -66,13 +66,13 @@
     return max<LayoutUnit>(replacedHeight, block->lineHeight(isFirstLine, block->isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
 }
 
-ExclusionShapeInsideInfo* RenderBlock::layoutExclusionShapeInsideInfo() const
+ShapeInsideInfo* RenderBlock::layoutShapeInsideInfo() const
 {
-    ExclusionShapeInsideInfo* shapeInsideInfo = view()->layoutState()->exclusionShapeInsideInfo();
-    if (!shapeInsideInfo && flowThreadContainingBlock() && allowsExclusionShapeInsideInfoSharing()) {
+    ShapeInsideInfo* shapeInsideInfo = view()->layoutState()->shapeInsideInfo();
+    if (!shapeInsideInfo && flowThreadContainingBlock() && allowsShapeInsideInfoSharing()) {
         LayoutUnit offset = logicalHeight() + logicalHeightForLine(this, false);
         RenderRegion* region = regionAtBlockOffset(offset);
-        return region ? region->exclusionShapeInsideInfo() : 0;
+        return region ? region->shapeInsideInfo() : 0;
     }
     return shapeInsideInfo;
 }
@@ -94,9 +94,9 @@
         , m_shouldIndentText(shouldIndentText)
     {
         ASSERT(block);
-        ExclusionShapeInsideInfo* exclusionShapeInsideInfo = m_block->layoutExclusionShapeInsideInfo();
-        if (exclusionShapeInsideInfo)
-            m_segment = exclusionShapeInsideInfo->currentSegment();
+        ShapeInsideInfo* shapeInsideInfo = m_block->layoutShapeInsideInfo();
+        if (shapeInsideInfo)
+            m_segment = shapeInsideInfo->currentSegment();
         updateAvailableWidth();
     }
     bool fitsOnLine() const { return currentWidth() <= m_availableWidth; }
@@ -161,7 +161,7 @@
     if (height < m_block->logicalTopForFloat(newFloat) || height >= m_block->logicalBottomForFloat(newFloat))
         return;
 
-    ExclusionShapeOutsideInfo* shapeOutsideInfo = newFloat->renderer()->exclusionShapeOutsideInfo();
+    ShapeOutsideInfo* shapeOutsideInfo = newFloat->renderer()->shapeOutsideInfo();
     if (shapeOutsideInfo)
         shapeOutsideInfo->computeSegmentsForLine(m_block->logicalHeight() - m_block->logicalTopForFloat(newFloat) + shapeOutsideInfo->shapeLogicalTop(), logicalHeightForLine(m_block, m_isFirstLine));
 
@@ -965,10 +965,10 @@
     float availableLogicalWidth;
     updateLogicalInlinePositions(this, lineLogicalLeft, lineLogicalRight, availableLogicalWidth, isFirstLine, shouldIndentText, 0);
     bool needsWordSpacing;
-    ExclusionShapeInsideInfo* exclusionShapeInsideInfo = layoutExclusionShapeInsideInfo();
-    if (exclusionShapeInsideInfo && exclusionShapeInsideInfo->hasSegments()) {
+    ShapeInsideInfo* shapeInsideInfo = layoutShapeInsideInfo();
+    if (shapeInsideInfo && shapeInsideInfo->hasSegments()) {
         BidiRun* segmentStart = firstRun;
-        const SegmentList& segments = exclusionShapeInsideInfo->segments();
+        const SegmentList& segments = shapeInsideInfo->segments();
         float logicalLeft = max<float>(roundToInt(segments[0].logicalLeft), lineLogicalLeft);
         float logicalRight = min<float>(floorToInt(segments[0].logicalRight), lineLogicalRight);
         float startLogicalLeft = logicalLeft;
@@ -1228,6 +1228,7 @@
     // FIXME: We should pass a BidiRunList into createBidiRunsForLine instead
     // of the resolver owning the runs.
     ASSERT(&topResolver.runs() == &bidiRuns);
+    ASSERT(topResolver.position() != endOfRuns);
     RenderObject* currentRoot = topResolver.position().root();
     topResolver.createBidiRunsForLine(endOfRuns, override, previousLineBrokeCleanly);
 
@@ -1284,15 +1285,20 @@
     }
 }
 
+static inline bool segmentIsEmpty(const InlineIterator& segmentStart, const InlineIterator& segmentEnd)
+{
+    return segmentStart == segmentEnd;
+}
+
 static inline void constructBidiRunsForLine(const RenderBlock* block, InlineBidiResolver& topResolver, BidiRunList<BidiRun>& bidiRuns, const InlineIterator& endOfLine, VisualDirectionOverride override, bool previousLineBrokeCleanly)
 {
-    ExclusionShapeInsideInfo* exclusionShapeInsideInfo = block->layoutExclusionShapeInsideInfo();
-    if (!exclusionShapeInsideInfo || !exclusionShapeInsideInfo->hasSegments()) {
+    ShapeInsideInfo* shapeInsideInfo = block->layoutShapeInsideInfo();
+    if (!shapeInsideInfo || !shapeInsideInfo->hasSegments()) {
         constructBidiRunsForSegment(topResolver, bidiRuns, endOfLine, override, previousLineBrokeCleanly);
         return;
     }
 
-    const SegmentRangeList& segmentRanges = exclusionShapeInsideInfo->segmentRanges();
+    const SegmentRangeList& segmentRanges = shapeInsideInfo->segmentRanges();
     ASSERT(segmentRanges.size());
 
     for (size_t i = 0; i < segmentRanges.size(); i++) {
@@ -1308,8 +1314,10 @@
             // Do not collapse midpoints between segments
             topResolver.midpointState().betweenMidpoints = false;
         }
-        topResolver.setPosition(segmentStart, numberOfIsolateAncestors(segmentStart));
-        constructBidiRunsForSegment(topResolver, bidiRuns, segmentEnd, override, previousLineBrokeCleanly);
+        if (!segmentIsEmpty(segmentStart, segmentEnd)) {
+            topResolver.setPosition(segmentStart, numberOfIsolateAncestors(segmentStart));
+            constructBidiRunsForSegment(topResolver, bidiRuns, segmentEnd, override, previousLineBrokeCleanly);
+        }
     }
 }
 
@@ -1534,6 +1542,28 @@
     return oldEnd;
 }
 
+static inline float firstPositiveWidth(const WordMeasurements& wordMeasurements)
+{
+    for (size_t i = 0; i < wordMeasurements.size(); ++i) {
+        if (wordMeasurements[i].width > 0)
+            return wordMeasurements[i].width;
+    }
+    return 0;
+}
+
+static inline LayoutUnit adjustLogicalLineTop(ShapeInsideInfo* shapeInsideInfo, const InlineIterator& start, const InlineIterator& end, const WordMeasurements& wordMeasurements)
+{
+    if (!shapeInsideInfo || !segmentIsEmpty(start, end))
+        return 0;
+
+    float minWidth = firstPositiveWidth(wordMeasurements);
+    ASSERT(minWidth || wordMeasurements.isEmpty());
+    if (minWidth > 0 && shapeInsideInfo->adjustLogicalLineTop(minWidth))
+        return shapeInsideInfo->logicalLineTop();
+
+    return shapeInsideInfo->shapeLogicalBottom();
+}
+
 void RenderBlock::layoutRunsAndFloatsInRange(LineLayoutState& layoutState, InlineBidiResolver& resolver, const InlineIterator& cleanLineStart, const BidiStatus& cleanLineBidiStatus, unsigned consecutiveHyphenatedLines)
 {
     RenderStyle* styleToUse = style();
@@ -1547,17 +1577,17 @@
     LineBreaker lineBreaker(this);
 
     LayoutUnit absoluteLogicalTop;
-    ExclusionShapeInsideInfo* exclusionShapeInsideInfo = layoutExclusionShapeInsideInfo();
-    if (exclusionShapeInsideInfo) {
-        ASSERT(exclusionShapeInsideInfo->owner() == this || allowsExclusionShapeInsideInfoSharing());
-        if (exclusionShapeInsideInfo != this->exclusionShapeInsideInfo()) {
+    ShapeInsideInfo* shapeInsideInfo = layoutShapeInsideInfo();
+    if (shapeInsideInfo) {
+        ASSERT(shapeInsideInfo->owner() == this || allowsShapeInsideInfoSharing());
+        if (shapeInsideInfo != this->shapeInsideInfo()) {
             // FIXME Bug 100284: If subsequent LayoutStates are pushed, we will have to add
             // their offsets from the original shape-inside container.
             absoluteLogicalTop = logicalTop();
         }
         // Begin layout at the logical top of our shape inside.
-        if (logicalHeight() + absoluteLogicalTop < exclusionShapeInsideInfo->shapeLogicalTop())
-            setLogicalHeight(exclusionShapeInsideInfo->shapeLogicalTop() - absoluteLogicalTop);
+        if (logicalHeight() + absoluteLogicalTop < shapeInsideInfo->shapeLogicalTop())
+            setLogicalHeight(shapeInsideInfo->shapeLogicalTop() - absoluteLogicalTop);
     }
 
     if (layoutState.flowThread()) {
@@ -1587,10 +1617,10 @@
         // FIXME: Bug 95361: It is possible for a line to grow beyond lineHeight, in which
         // case these segments may be incorrect.
         if (layoutState.flowThread())
-            exclusionShapeInsideInfo = layoutExclusionShapeInsideInfo();
-        if (exclusionShapeInsideInfo) {
+            shapeInsideInfo = layoutShapeInsideInfo();
+        if (shapeInsideInfo) {
             LayoutUnit lineTop = logicalHeight() + absoluteLogicalTop;
-            exclusionShapeInsideInfo->computeSegmentsForLine(lineTop, lineHeight(layoutState.lineInfo().isFirstLine(), isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
+            shapeInsideInfo->computeSegmentsForLine(lineTop, lineHeight(layoutState.lineInfo().isFirstLine(), isHorizontalWritingMode() ? HorizontalLine : VerticalLine, PositionOfInteriorLineBoxes));
         }
         WordMeasurements wordMeasurements;
         end = lineBreaker.nextLineBreak(resolver, layoutState.lineInfo(), renderTextInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines, wordMeasurements);
@@ -1604,13 +1634,14 @@
             resolver.setPosition(InlineIterator(resolver.position().root(), 0, 0), 0);
             break;
         }
-        ASSERT(end != resolver.position());
 
-        if (exclusionShapeInsideInfo && wordMeasurements.size() && exclusionShapeInsideInfo->adjustLogicalLineTop(wordMeasurements[0].width)) {
-            end = restartLayoutRunsAndFloatsInRange(logicalHeight(), exclusionShapeInsideInfo->logicalLineTop() - absoluteLogicalTop, lastFloatFromPreviousLine, resolver, oldEnd);
+        if (LayoutUnit adjustedLogicalLineTop = adjustLogicalLineTop(shapeInsideInfo, resolver.position(), end, wordMeasurements)) {
+            end = restartLayoutRunsAndFloatsInRange(logicalHeight(), adjustedLogicalLineTop - absoluteLogicalTop, lastFloatFromPreviousLine, resolver, oldEnd);
             continue;
         }
 
+        ASSERT(end != resolver.position());
+
         // This is a short-cut for empty lines.
         if (layoutState.lineInfo().isEmpty()) {
             if (lastRootBox())
@@ -2534,15 +2565,21 @@
 
 InlineIterator RenderBlock::LineBreaker::nextLineBreak(InlineBidiResolver& resolver, LineInfo& lineInfo, RenderTextInfo& renderTextInfo, FloatingObject* lastFloatFromPreviousLine, unsigned consecutiveHyphenatedLines, WordMeasurements& wordMeasurements)
 {
-    ExclusionShapeInsideInfo* exclusionShapeInsideInfo = m_block->layoutExclusionShapeInsideInfo();
-    if (!exclusionShapeInsideInfo || !exclusionShapeInsideInfo->hasSegments())
+    ShapeInsideInfo* shapeInsideInfo = m_block->layoutShapeInsideInfo();
+    if (!shapeInsideInfo || !shapeInsideInfo->lineOverlapsShapeBounds())
         return nextSegmentBreak(resolver, lineInfo, renderTextInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines, wordMeasurements);
 
     InlineIterator end = resolver.position();
     InlineIterator oldEnd = end;
 
-    const SegmentList& segments = exclusionShapeInsideInfo->segments();
-    SegmentRangeList& segmentRanges = exclusionShapeInsideInfo->segmentRanges();
+    if (!shapeInsideInfo->hasSegments()) {
+        end = nextSegmentBreak(resolver, lineInfo, renderTextInfo, lastFloatFromPreviousLine, consecutiveHyphenatedLines, wordMeasurements);
+        resolver.setPositionIgnoringNestedIsolates(oldEnd);
+        return oldEnd;
+    }
+
+    const SegmentList& segments = shapeInsideInfo->segments();
+    SegmentRangeList& segmentRanges = shapeInsideInfo->segmentRanges();
 
     for (unsigned i = 0; i < segments.size() && !end.atEnd(); i++) {
         InlineIterator segmentStart = resolver.position();
@@ -2555,6 +2592,7 @@
         }
         if (resolver.position() == end) {
             // Nothing fit this segment
+            end = segmentStart;
             segmentRanges.append(LineSegmentRange(segmentStart, segmentStart));
             resolver.setPositionIgnoringNestedIsolates(segmentStart);
         } else {
@@ -2605,6 +2643,7 @@
     // this to detect when we encounter a second space so we know we have to terminate
     // a run.
     bool currentCharacterIsSpace = false;
+    bool currentCharacterShouldCollapseIfPreWap = false;
     TrailingObjects trailingObjects;
 
     InlineIterator lBreak = resolver.position();
@@ -2736,7 +2775,7 @@
                     && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) {
                     // Like with list markers, we start ignoring spaces to make sure that any
                     // additional spaces we see will be discarded.
-                    currentCharacterIsSpace = true;
+                    currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = true;
                     ignoringSpaces = true;
                 }
             }
@@ -2759,7 +2798,7 @@
 
             lineInfo.setEmpty(false, m_block, &width);
             ignoringSpaces = false;
-            currentCharacterIsSpace = false;
+            currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = false;
             trailingObjects.clear();
 
             // Optimize for a common case. If we can't find whitespace after the list
@@ -2769,7 +2808,7 @@
                 if (blockStyle->collapseWhiteSpace() && shouldSkipWhitespaceAfterStartObject(m_block, current.m_obj, lineMidpointState)) {
                     // Like with inline flows, we start ignoring spaces to make sure that any
                     // additional spaces we see will be discarded.
-                    currentCharacterIsSpace = true;
+                    currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = true;
                     ignoringSpaces = true;
                 }
                 if (toRenderListMarker(current.m_obj)->isInside())
@@ -2850,8 +2889,9 @@
             UChar secondToLastCharacter = renderTextInfo.m_lineBreakIterator.secondToLastCharacter();
             for (; current.m_pos < t->textLength(); current.fastIncrementInTextNode()) {
                 bool previousCharacterIsSpace = currentCharacterIsSpace;
+                bool previousCharacterShouldCollapseIfPreWap = currentCharacterShouldCollapseIfPreWap;
                 UChar c = current.current();
-                currentCharacterIsSpace = c == ' ' || c == '\t' || (!preserveNewline && (c == '\n'));
+                currentCharacterShouldCollapseIfPreWap = currentCharacterIsSpace = c == ' ' || c == '\t' || (!preserveNewline && (c == '\n'));
 
                 if (!collapseWhiteSpace || !currentCharacterIsSpace)
                     lineInfo.setEmpty(false, m_block, &width);
@@ -3035,7 +3075,7 @@
                     ignoreStart.m_pos = current.m_pos;
                 }
 
-                if (!currentCharacterIsSpace && previousCharacterIsSpace) {
+                if (!currentCharacterIsSpace && previousCharacterShouldCollapseIfPreWap) {
                     if (autoWrap && currentStyle->breakOnlyAfterWhiteSpace())
                         lBreak.moveTo(current.m_obj, current.m_pos, current.m_nextBreakablePosition);
                 }
@@ -3149,7 +3189,10 @@
         lBreak.clear();
 
  end:
-    if (lBreak == resolver.position() && (!lBreak.m_obj || !lBreak.m_obj->isBR())) {
+    ShapeInsideInfo* shapeInfo = m_block->layoutShapeInsideInfo();
+    bool segmentAllowsOverflow = !shapeInfo || !shapeInfo->hasSegments();
+
+    if (lBreak == resolver.position() && (!lBreak.m_obj || !lBreak.m_obj->isBR()) && segmentAllowsOverflow) {
         // we just add as much as possible
         if (blockStyle->whiteSpace() == PRE && !current.m_pos) {
             lBreak.moveTo(last, last->isText() ? last->length() : 0);
@@ -3164,7 +3207,7 @@
     // FIXME Bug 100049: We do not need to consume input in a multi-segment line
     // unless no segment will.
     // make sure we consume at least one char/object.
-    if (lBreak == resolver.position())
+    if (lBreak == resolver.position() && segmentAllowsOverflow)
         lBreak.increment();
 
     // Sanity check our midpoints.
diff --git a/Source/core/rendering/RenderBox.cpp b/Source/core/rendering/RenderBox.cpp
index 1659f97..276141d 100644
--- a/Source/core/rendering/RenderBox.cpp
+++ b/Source/core/rendering/RenderBox.cpp
@@ -163,7 +163,7 @@
 
     RenderBlock::removePercentHeightDescendantIfNeeded(this);
 
-    ExclusionShapeOutsideInfo::removeInfo(this);
+    ShapeOutsideInfo::removeInfo(this);
 
     RenderBoxModelObject::willBeDestroyed();
 }
@@ -311,20 +311,21 @@
         frame()->view()->recalculateScrollbarOverlayStyle();
     }
 
-    updateExclusionShapeOutsideInfoAfterStyleChange(style()->shapeOutside(), oldStyle ? oldStyle->shapeOutside() : 0);
+    updateShapeOutsideInfoAfterStyleChange(style()->shapeOutside(), oldStyle ? oldStyle->shapeOutside() : 0);
 }
 
-void RenderBox::updateExclusionShapeOutsideInfoAfterStyleChange(const ExclusionShapeValue* shapeOutside, const ExclusionShapeValue* oldShapeOutside)
+void RenderBox::updateShapeOutsideInfoAfterStyleChange(const ShapeValue* shapeOutside, const ShapeValue* oldShapeOutside)
 {
     // FIXME: A future optimization would do a deep comparison for equality. (bug 100811)
     if (shapeOutside == oldShapeOutside)
         return;
 
     if (shapeOutside) {
-        ExclusionShapeOutsideInfo* exclusionShapeOutsideInfo = ExclusionShapeOutsideInfo::ensureInfo(this);
-        exclusionShapeOutsideInfo->dirtyShapeSize();
-    } else
-        ExclusionShapeOutsideInfo::removeInfo(this);
+        ShapeOutsideInfo* shapeOutsideInfo = ShapeOutsideInfo::ensureInfo(this);
+        shapeOutsideInfo->dirtyShapeSize();
+    } else {
+        ShapeOutsideInfo::removeInfo(this);
+    }
 }
 
 void RenderBox::updateFromStyle()
@@ -423,6 +424,37 @@
     return snapSizeToPixel(offsetHeight(), y() + clientTop());
 }
 
+bool RenderBox::requiresLayoutToDetermineWidth() const
+{
+    RenderStyle* style = this->style();
+    return !style->width().isFixed()
+        || !style->minWidth().isFixed()
+        || (!style->maxWidth().isUndefined() && !style->maxWidth().isFixed())
+        || !style->paddingLeft().isFixed()
+        || !style->paddingRight().isFixed()
+        || style->resize() != RESIZE_NONE
+        || style->boxSizing() == BORDER_BOX
+        || !isRenderBlock()
+        || !isBlockFlow()
+        || isFlexItemIncludingDeprecated();
+}
+
+LayoutUnit RenderBox::fixedOffsetWidth() const
+{
+    ASSERT(!requiresLayoutToDetermineWidth());
+
+    RenderStyle* style = this->style();
+
+    LayoutUnit width = std::max(LayoutUnit(style->minWidth().value()), LayoutUnit(style->width().value()));
+    if (style->maxWidth().isFixed())
+        width = std::min(LayoutUnit(style->maxWidth().value()), width);
+
+    LayoutUnit borderLeft = style->borderLeft().nonZero() ? style->borderLeft().width() : 0;
+    LayoutUnit borderRight = style->borderRight().nonZero() ? style->borderRight().width() : 0;
+
+    return width + borderLeft + borderRight + style->paddingLeft().value() + style->paddingRight().value();
+}
+
 int RenderBox::scrollWidth() const
 {
     if (hasOverflowClip())
@@ -2520,8 +2552,11 @@
 {
     // FIXME(cbiesinger): The css-sizing spec is considering changing what min-content/max-content should resolve to.
     // If that happens, this code will have to change.
-    if (height.isIntrinsic())
+    if (height.isIntrinsic()) {
+        if (intrinsicContentHeight == -1)
+            return -1; // Intrinsic height isn't available.
         return computeIntrinsicLogicalContentHeightUsing(height, intrinsicContentHeight, borderAndPaddingLogicalHeight());
+    }
     if (height.isFixed())
         return height.value();
     if (height.isPercent())
diff --git a/Source/core/rendering/RenderBox.h b/Source/core/rendering/RenderBox.h
index df632b1..6046045 100644
--- a/Source/core/rendering/RenderBox.h
+++ b/Source/core/rendering/RenderBox.h
@@ -24,9 +24,9 @@
 #define RenderBox_h
 
 #include "core/platform/ScrollTypes.h"
-#include "core/rendering/exclusions/ExclusionShapeOutsideInfo.h"
 #include "core/rendering/RenderBoxModelObject.h"
 #include "core/rendering/RenderOverflow.h"
+#include "core/rendering/shapes/ShapeOutsideInfo.h"
 
 namespace WebCore {
 
@@ -208,6 +208,9 @@
     virtual int pixelSnappedOffsetWidth() const OVERRIDE FINAL;
     virtual int pixelSnappedOffsetHeight() const OVERRIDE FINAL;
 
+    bool requiresLayoutToDetermineWidth() const;
+    LayoutUnit fixedOffsetWidth() const;
+
     // More IE extensions.  clientWidth and clientHeight represent the interior of an object
     // excluding border and scrollbar.  clientLeft/Top are just the borderLeftWidth and borderTopWidth.
     LayoutUnit clientLeft() const { return borderLeft(); }
@@ -532,7 +535,7 @@
     LayoutRect logicalLayoutOverflowRectForPropagation(RenderStyle*) const;
     LayoutRect layoutOverflowRectForPropagation(RenderStyle*) const;
 
-    RenderOverflow* hasRenderOverflow() const { return m_overflow.get(); }    
+    bool hasRenderOverflow() const { return m_overflow; }
     bool hasVisualOverflow() const { return m_overflow && !borderBoxRect().contains(m_overflow->visualOverflowRect()); }
 
     virtual bool needsPreferredWidthsRecalculation() const;
@@ -547,24 +550,22 @@
 
     bool hasHorizontalLayoutOverflow() const
     {
-        if (RenderOverflow* overflow = hasRenderOverflow()) {
-            LayoutRect layoutOverflowRect = overflow->layoutOverflowRect();
-            flipForWritingMode(layoutOverflowRect);
-            return layoutOverflowRect.x() < x() || layoutOverflowRect.maxX() > x() + logicalWidth();
-        }
+        if (!m_overflow)
+            return false;
 
-        return false;
+        LayoutRect layoutOverflowRect = m_overflow->layoutOverflowRect();
+        flipForWritingMode(layoutOverflowRect);
+        return layoutOverflowRect.x() < x() || layoutOverflowRect.maxX() > x() + logicalWidth();
     }
 
     bool hasVerticalLayoutOverflow() const
     {
-        if (RenderOverflow* overflow = hasRenderOverflow()) {
-            LayoutRect layoutOverflowRect = overflow->layoutOverflowRect();
-            flipForWritingMode(layoutOverflowRect);
-            return layoutOverflowRect.y() < y() || layoutOverflowRect.maxY() > y() + logicalHeight();
-        }
+        if (!m_overflow)
+            return false;
 
-        return false;
+        LayoutRect layoutOverflowRect = m_overflow->layoutOverflowRect();
+        flipForWritingMode(layoutOverflowRect);
+        return layoutOverflowRect.y() < y() || layoutOverflowRect.maxY() > y() + logicalHeight();
     }
 
     virtual RenderBox* createAnonymousBoxWithSameTypeAs(const RenderObject*) const
@@ -578,9 +579,9 @@
     virtual void reportMemoryUsage(MemoryObjectInfo*) const OVERRIDE;
     static void reportStaticMembersMemoryUsage(MemoryInstrumentation*);
 
-    ExclusionShapeOutsideInfo* exclusionShapeOutsideInfo() const
+    ShapeOutsideInfo* shapeOutsideInfo() const
     {
-        return isFloatingWithShapeOutside() && ExclusionShapeOutsideInfo::isEnabledFor(this) ? ExclusionShapeOutsideInfo::info(this) : 0;
+        return isFloatingWithShapeOutside() && ShapeOutsideInfo::isEnabledFor(this) ? ShapeOutsideInfo::info(this) : 0;
     }
 
 protected:
@@ -619,7 +620,7 @@
     RenderObject* splitAnonymousBoxesAroundChild(RenderObject* beforeChild);
  
 private:
-    void updateExclusionShapeOutsideInfoAfterStyleChange(const ExclusionShapeValue* shapeOutside, const ExclusionShapeValue* oldShapeOutside);
+    void updateShapeOutsideInfoAfterStyleChange(const ShapeValue* shapeOutside, const ShapeValue* oldShapeOutside);
 
     bool includeVerticalScrollbarSize() const;
     bool includeHorizontalScrollbarSize() const;
diff --git a/Source/core/rendering/RenderBoxModelObject.cpp b/Source/core/rendering/RenderBoxModelObject.cpp
index 7bc385f..491343b 100644
--- a/Source/core/rendering/RenderBoxModelObject.cpp
+++ b/Source/core/rendering/RenderBoxModelObject.cpp
@@ -407,7 +407,7 @@
     LayoutSize offset = offsetForInFlowPosition();
 
     if (isBox() && isFloating())
-        if (ExclusionShapeOutsideInfo* shapeOutside = toRenderBox(this)->exclusionShapeOutsideInfo())
+        if (ShapeOutsideInfo* shapeOutside = toRenderBox(this)->shapeOutsideInfo())
             offset -= shapeOutside->shapeLogicalOffset();
 
     return offset;
@@ -527,7 +527,8 @@
         boxShadow = boxShadow->next();
 
     FloatSize shadowOffset(boxShadow->x(), boxShadow->y());
-    context->setShadow(shadowOffset, boxShadow->blur(), boxShadow->color(), DrawLooper::ShadowIgnoresAlpha);
+    context->setShadow(shadowOffset, boxShadow->blur(), boxShadow->color(),
+        DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
 }
 
 void RenderBoxModelObject::paintFillLayerExtended(const PaintInfo& paintInfo, const Color& color, const FillLayer* bgLayer, const LayoutRect& rect,
@@ -1993,21 +1994,6 @@
     graphicsContext->drawRect(pixelSnappedIntRect(borderRect));
 }
 
-static void findInnerVertex(const FloatPoint& outerCorner, const FloatPoint& innerCorner, const FloatPoint& centerPoint, FloatPoint& result)
-{
-    // If the line between outer and inner corner is towards the horizontal, intersect with a vertical line through the center,
-    // otherwise with a horizontal line through the center. The points that form this line are arbitrary (we use 0, 100).
-    // Note that if findIntersection fails, it will leave result untouched.
-    float diffInnerOuterX = fabs(innerCorner.x() - outerCorner.x());
-    float diffInnerOuterY = fabs(innerCorner.y() - outerCorner.y());
-    float diffCenterOuterX = fabs(centerPoint.x() - outerCorner.x());
-    float diffCenterOuterY = fabs(centerPoint.y() - outerCorner.y());
-    if (diffInnerOuterY * diffCenterOuterX < diffCenterOuterY * diffInnerOuterX)
-        findIntersection(outerCorner, innerCorner, FloatPoint(centerPoint.x(), 0), FloatPoint(centerPoint.x(), 100), result);
-    else
-        findIntersection(outerCorner, innerCorner, FloatPoint(0, centerPoint.y()), FloatPoint(100, centerPoint.y()), result);
-}
-
 void RenderBoxModelObject::clipBorderSidePolygon(GraphicsContext* graphicsContext, const RoundedRect& outerBorder, const RoundedRect& innerBorder,
                                                  BoxSide side, bool firstEdgeMatches, bool secondEdgeMatches)
 {
@@ -2039,11 +2025,27 @@
         quad[2] = innerRect.maxXMinYCorner();
         quad[3] = outerRect.maxXMinYCorner();
 
-        if (!innerBorder.radii().topLeft().isZero())
-            findInnerVertex(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), centerPoint, quad[1]);
+        if (!innerBorder.radii().topLeft().isZero()) {
+            findIntersection(quad[0], quad[1],
+                FloatPoint(
+                    quad[1].x() + innerBorder.radii().topLeft().width(),
+                    quad[1].y()),
+                FloatPoint(
+                    quad[1].x(),
+                    quad[1].y() + innerBorder.radii().topLeft().height()),
+                quad[1]);
+        }
 
-        if (!innerBorder.radii().topRight().isZero())
-            findInnerVertex(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), centerPoint, quad[2]);
+        if (!innerBorder.radii().topRight().isZero()) {
+            findIntersection(quad[3], quad[2],
+                FloatPoint(
+                    quad[2].x() - innerBorder.radii().topRight().width(),
+                    quad[2].y()),
+                FloatPoint(
+                    quad[2].x(),
+                    quad[2].y() + innerBorder.radii().topRight().height()),
+                quad[2]);
+        }
         break;
 
     case BSLeft:
@@ -2052,11 +2054,27 @@
         quad[2] = innerRect.minXMaxYCorner();
         quad[3] = outerRect.minXMaxYCorner();
 
-        if (!innerBorder.radii().topLeft().isZero())
-            findInnerVertex(outerRect.minXMinYCorner(), innerRect.minXMinYCorner(), centerPoint, quad[1]);
+        if (!innerBorder.radii().topLeft().isZero()) {
+            findIntersection(quad[0], quad[1],
+                FloatPoint(
+                    quad[1].x() + innerBorder.radii().topLeft().width(),
+                    quad[1].y()),
+                FloatPoint(
+                    quad[1].x(),
+                    quad[1].y() + innerBorder.radii().topLeft().height()),
+                quad[1]);
+        }
 
-        if (!innerBorder.radii().bottomLeft().isZero())
-            findInnerVertex(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), centerPoint, quad[2]);
+        if (!innerBorder.radii().bottomLeft().isZero()) {
+            findIntersection(quad[3], quad[2],
+                FloatPoint(
+                    quad[2].x() + innerBorder.radii().bottomLeft().width(),
+                    quad[2].y()),
+                FloatPoint(
+                    quad[2].x(),
+                    quad[2].y() - innerBorder.radii().bottomLeft().height()),
+                quad[2]);
+        }
         break;
 
     case BSBottom:
@@ -2065,11 +2083,27 @@
         quad[2] = innerRect.maxXMaxYCorner();
         quad[3] = outerRect.maxXMaxYCorner();
 
-        if (!innerBorder.radii().bottomLeft().isZero())
-            findInnerVertex(outerRect.minXMaxYCorner(), innerRect.minXMaxYCorner(), centerPoint, quad[1]);
+        if (!innerBorder.radii().bottomLeft().isZero()) {
+            findIntersection(quad[0], quad[1],
+                FloatPoint(
+                    quad[1].x() + innerBorder.radii().bottomLeft().width(),
+                    quad[1].y()),
+                FloatPoint(
+                    quad[1].x(),
+                    quad[1].y() - innerBorder.radii().bottomLeft().height()),
+                quad[1]);
+        }
 
-        if (!innerBorder.radii().bottomRight().isZero())
-            findInnerVertex(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), centerPoint, quad[2]);
+        if (!innerBorder.radii().bottomRight().isZero()) {
+            findIntersection(quad[3], quad[2],
+                FloatPoint(
+                    quad[2].x() - innerBorder.radii().bottomRight().width(),
+                    quad[2].y()),
+                FloatPoint(
+                    quad[2].x(),
+                    quad[2].y() - innerBorder.radii().bottomRight().height()),
+                quad[2]);
+        }
         break;
 
     case BSRight:
@@ -2078,11 +2112,27 @@
         quad[2] = innerRect.maxXMaxYCorner();
         quad[3] = outerRect.maxXMaxYCorner();
 
-        if (!innerBorder.radii().topRight().isZero())
-            findInnerVertex(outerRect.maxXMinYCorner(), innerRect.maxXMinYCorner(), centerPoint, quad[1]);
+        if (!innerBorder.radii().topRight().isZero()) {
+            findIntersection(quad[0], quad[1],
+                FloatPoint(
+                    quad[1].x() - innerBorder.radii().topRight().width(),
+                    quad[1].y()),
+                FloatPoint(
+                    quad[1].x(),
+                    quad[1].y() + innerBorder.radii().topRight().height()),
+                quad[1]);
+        }
 
-        if (!innerBorder.radii().bottomRight().isZero())
-            findInnerVertex(outerRect.maxXMaxYCorner(), innerRect.maxXMaxYCorner(), centerPoint, quad[2]);
+        if (!innerBorder.radii().bottomRight().isZero()) {
+            findIntersection(quad[3], quad[2],
+                FloatPoint(
+                    quad[2].x() - innerBorder.radii().bottomRight().width(),
+                    quad[2].y()),
+                FloatPoint(
+                    quad[2].x(),
+                    quad[2].y() - innerBorder.radii().bottomRight().height()),
+                quad[2]);
+        }
         break;
     }
 
@@ -2093,22 +2143,41 @@
         return;
     }
 
-    // Square off the end which shouldn't be affected by antialiasing, and clip.
+    // If antialiasing settings for the first edge and second edge is different,
+    // they have to be addressed separately. We do this by breaking the quad into
+    // two parallelograms, made by moving quad[1] and quad[2].
+    float ax = quad[1].x() - quad[0].x();
+    float ay = quad[1].y() - quad[0].y();
+    float bx = quad[2].x() - quad[1].x();
+    float by = quad[2].y() - quad[1].y();
+    float cx = quad[3].x() - quad[2].x();
+    float cy = quad[3].y() - quad[2].y();
+
+    const static float kEpsilon = 1e-2f;
+    float r1, r2;
+    if (fabsf(bx) < kEpsilon && fabsf(by) < kEpsilon) {
+        // The quad was actually a triangle.
+        r1 = r2 = 1.0f;
+    } else {
+        // Extend parallelogram a bit to hide calculation error
+        const static float kExtendFill = 1e-2f;
+
+        r1 = (-ax * by + ay * bx) / (cx * by - cy * bx) + kExtendFill;
+        r2 = (-cx * by + cy * bx) / (ax * by - ay * bx) + kExtendFill;
+    }
+
     FloatPoint firstQuad[4];
     firstQuad[0] = quad[0];
     firstQuad[1] = quad[1];
-    firstQuad[2] = side == BSTop || side == BSBottom ? FloatPoint(quad[3].x(), quad[2].y())
-        : FloatPoint(quad[2].x(), quad[3].y());
+    firstQuad[2] = FloatPoint(quad[3].x() + r2 * ax, quad[3].y() + r2 * ay);
     firstQuad[3] = quad[3];
     graphicsContext->clipConvexPolygon(4, firstQuad, !firstEdgeMatches);
 
     FloatPoint secondQuad[4];
     secondQuad[0] = quad[0];
-    secondQuad[1] = side == BSTop || side == BSBottom ? FloatPoint(quad[0].x(), quad[1].y())
-        : FloatPoint(quad[1].x(), quad[0].y());
+    secondQuad[1] = FloatPoint(quad[0].x() - r1 * cx, quad[0].y() - r1 * cy);
     secondQuad[2] = quad[2];
     secondQuad[3] = quad[3];
-    // Antialiasing affects the second side.
     graphicsContext->clipConvexPolygon(4, secondQuad, !secondEdgeMatches);
 }
 
@@ -2367,7 +2436,6 @@
     bool isHorizontal = s->isHorizontalWritingMode();
     
     bool hasOpaqueBackground = s->visitedDependentColor(CSSPropertyBackgroundColor).isValid() && s->visitedDependentColor(CSSPropertyBackgroundColor).alpha() == 255;
-    bool contextWasClipped = false;
     for (const ShadowData* shadow = s->boxShadow(); shadow; shadow = shadow->next()) {
         if (shadow->style() != shadowStyle)
             continue;
@@ -2397,21 +2465,18 @@
                 DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
             context->setDrawLooper(drawLooper);
 
+            context->save();
             if (hasBorderRadius) {
-                if (!contextWasClipped) {
-                    RoundedRect rectToClipOut = border;
+                RoundedRect rectToClipOut = border;
 
-                    // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
-                    // when painting the shadow. On the other hand, it introduces subpixel gaps along the
-                    // corners. Those are avoided by insetting the clipping path by one pixel.
-                    if (hasOpaqueBackground)
-                        rectToClipOut.inflateWithRadii(-1);
+                // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
+                // when painting the shadow. On the other hand, it introduces subpixel gaps along the
+                // corners. Those are avoided by insetting the clipping path by one pixel.
+                if (hasOpaqueBackground)
+                    rectToClipOut.inflateWithRadii(-1);
 
-                    if (!rectToClipOut.isEmpty()) {
-                        context->save();
-                        context->clipOutRoundedRect(rectToClipOut);
-                        contextWasClipped = true;
-                    }
+                if (!rectToClipOut.isEmpty()) {
+                    context->clipOutRoundedRect(rectToClipOut);
                 }
 
                 RoundedRect influenceRect(shadowRect, border.radii());
@@ -2425,88 +2490,44 @@
                     context->fillRoundedRect(fillRect, Color::black);
                 }
             } else {
-                if (!contextWasClipped) {
-                    IntRect rectToClipOut = border.rect();
+                IntRect rectToClipOut = border.rect();
 
-                    // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
-                    // when painting the shadow. On the other hand, it introduces subpixel gaps along the
-                    // edges if they are not pixel-aligned. Those are avoided by insetting the clipping path
-                    // by one pixel.
-                    if (hasOpaqueBackground) {
-                        // FIXME: The function to decide on the policy based on the transform should be a named function.
-                        // FIXME: It's not clear if this check is right. What about integral scale factors?
-                        AffineTransform transform = context->getCTM();
-                        if (transform.a() != 1 || (transform.d() != 1 && transform.d() != -1) || transform.b() || transform.c())
-                            rectToClipOut.inflate(-1);
-                    }
+                // If the box is opaque, it is unnecessary to clip it out. However, doing so saves time
+                // when painting the shadow. On the other hand, it introduces subpixel gaps along the
+                // edges if they are not pixel-aligned. Those are avoided by insetting the clipping path
+                // by one pixel.
+                if (hasOpaqueBackground) {
+                    // FIXME: The function to decide on the policy based on the transform should be a named function.
+                    // FIXME: It's not clear if this check is right. What about integral scale factors?
+                    AffineTransform transform = context->getCTM();
+                    if (transform.a() != 1 || (transform.d() != 1 && transform.d() != -1) || transform.b() || transform.c())
+                        rectToClipOut.inflate(-1);
+                }
 
-                    if (!rectToClipOut.isEmpty()) {
-                        context->save();
-                        context->clipOut(rectToClipOut);
-                        contextWasClipped = true;
-                    }
+                if (!rectToClipOut.isEmpty()) {
+                    context->clipOut(rectToClipOut);
                 }
                 context->fillRect(fillRect.rect(), Color::black);
             }
+            context->restore();
+            context->clearDrawLooper();
         } else {
-            // Inset shadow.
-            IntRect holeRect(border.rect());
-            holeRect.inflate(-shadowSpread);
-
-            if (holeRect.isEmpty()) {
-                if (hasBorderRadius)
-                    context->fillRoundedRect(border, shadowColor);
-                else
-                    context->fillRect(border.rect(), shadowColor);
-                continue;
-            }
-
+            GraphicsContext::Edges clippedEdges = GraphicsContext::NoEdge;
             if (!includeLogicalLeftEdge) {
-                if (isHorizontal) {
-                    holeRect.move(-max(shadowOffset.width(), 0) - shadowBlur, 0);
-                    holeRect.setWidth(holeRect.width() + max(shadowOffset.width(), 0) + shadowBlur);
-                } else {
-                    holeRect.move(0, -max(shadowOffset.height(), 0) - shadowBlur);
-                    holeRect.setHeight(holeRect.height() + max(shadowOffset.height(), 0) + shadowBlur);
-                }
+                if (isHorizontal)
+                    clippedEdges |= GraphicsContext::LeftEdge;
+                else
+                    clippedEdges |= GraphicsContext::TopEdge;
             }
             if (!includeLogicalRightEdge) {
                 if (isHorizontal)
-                    holeRect.setWidth(holeRect.width() - min(shadowOffset.width(), 0) + shadowBlur);
+                    clippedEdges |= GraphicsContext::RightEdge;
                 else
-                    holeRect.setHeight(holeRect.height() - min(shadowOffset.height(), 0) + shadowBlur);
+                    clippedEdges |= GraphicsContext::BottomEdge;
             }
-
-            Color fillColor(shadowColor.red(), shadowColor.green(), shadowColor.blue(), 255);
-
-            IntRect outerRect = areaCastingShadowInHole(border.rect(), shadowBlur, shadowSpread, shadowOffset);
-            RoundedRect roundedHole(holeRect, border.radii());
-            if (hasBorderRadius)
-                roundedHole.shrinkRadii(shadowSpread);
-
-            if (!contextWasClipped) {
-                context->save();
-                if (hasBorderRadius) {
-                    Path path;
-                    path.addRoundedRect(border);
-                    context->clipPath(path);
-                } else {
-                    context->clip(border.rect());
-                }
-                contextWasClipped = true;
-            }
-
-            DrawLooper drawLooper;
-            drawLooper.addShadow(shadowOffset, shadowBlur, shadowColor,
-                DrawLooper::ShadowRespectsTransforms, DrawLooper::ShadowIgnoresAlpha);
-            context->setDrawLooper(drawLooper);
-            context->fillRectWithRoundedHole(outerRect, roundedHole, fillColor);
+            context->drawInnerShadow(border, shadowColor, shadowOffset, shadowBlur, shadowSpread, clippedEdges);
         }
     }
-
-    if (contextWasClipped)
-        context->restore();
-    context->clearDrawLooper();
 }
 
 LayoutUnit RenderBoxModelObject::containingBlockLogicalWidthForContent() const
diff --git a/Source/core/rendering/RenderBoxModelObject.h b/Source/core/rendering/RenderBoxModelObject.h
index 2eefa59..747dc9c 100644
--- a/Source/core/rendering/RenderBoxModelObject.h
+++ b/Source/core/rendering/RenderBoxModelObject.h
@@ -173,7 +173,7 @@
 
     virtual void setSelectionState(SelectionState s);
 
-    bool canHaveBoxInfoInRegion() const { return !isFloating() && !isReplaced() && !isInline() && !hasColumns() && !isTableCell() && isBlockFlow(); }
+    bool canHaveBoxInfoInRegion() const { return !isFloating() && !isReplaced() && !isInline() && !hasColumns() && !isTableCell() && isBlockFlow() && !isRenderSVGBlock(); }
 
     void contentChanged(ContentChangeType);
     bool hasAcceleratedCompositing() const;
diff --git a/Source/core/rendering/RenderButton.cpp b/Source/core/rendering/RenderButton.cpp
index 5398661..b596c54 100644
--- a/Source/core/rendering/RenderButton.cpp
+++ b/Source/core/rendering/RenderButton.cpp
@@ -23,8 +23,6 @@
 
 #include "HTMLNames.h"
 #include "core/dom/Document.h"
-#include "core/html/HTMLInputElement.h"
-#include "core/rendering/RenderTextFragment.h"
 
 namespace WebCore {
 
@@ -32,7 +30,6 @@
 
 RenderButton::RenderButton(Element* element)
     : RenderFlexibleBox(element)
-    , m_buttonText(0)
     , m_inner(0)
 {
 }
@@ -86,8 +83,6 @@
 {
     RenderBlock::styleDidChange(diff, oldStyle);
 
-    if (m_buttonText)
-        m_buttonText->setStyle(style());
     if (m_inner) // RenderBlock handled updating the anonymous block's style.
         setupInnerStyle(m_inner->style());
 }
@@ -105,39 +100,6 @@
     innerStyle->setFlexDirection(style()->flexDirection());
 }
 
-void RenderButton::updateFromElement()
-{
-    // If we're an input element, we may need to change our button text.
-    if (node()->hasTagName(inputTag)) {
-        HTMLInputElement* input = toHTMLInputElement(node());
-        String value = input->valueWithDefault();
-        setText(value);
-    }
-}
-
-void RenderButton::setText(const String& str)
-{
-    if (str.isEmpty()) {
-        if (m_buttonText) {
-            m_buttonText->destroy();
-            m_buttonText = 0;
-        }
-    } else {
-        if (m_buttonText)
-            m_buttonText->setText(str.impl());
-        else {
-            m_buttonText = new (renderArena()) RenderTextFragment(document(), str.impl());
-            m_buttonText->setStyle(style());
-            addChild(m_buttonText);
-        }
-    }
-}
-
-String RenderButton::text() const
-{
-    return m_buttonText ? m_buttonText->text() : 0;
-}
-
 bool RenderButton::canHaveGeneratedChildren() const
 {
     // Input elements can't have generated children, but button elements can. We'll
diff --git a/Source/core/rendering/RenderButton.h b/Source/core/rendering/RenderButton.h
index d500afe..036cfb5 100644
--- a/Source/core/rendering/RenderButton.h
+++ b/Source/core/rendering/RenderButton.h
@@ -47,15 +47,11 @@
     virtual bool createsAnonymousWrapper() const { return true; }
 
     void setupInnerStyle(RenderStyle*);
-    virtual void updateFromElement();
 
     virtual bool canHaveGeneratedChildren() const OVERRIDE;
     virtual bool hasControlClip() const { return true; }
     virtual LayoutRect controlClipRect(const LayoutPoint&) const;
 
-    void setText(const String&);
-    String text() const;
-
     virtual int baselinePosition(FontBaseline, bool firstLine, LineDirectionMode, LinePositionMode) const OVERRIDE;
 
 private:
@@ -66,7 +62,6 @@
 
     virtual bool requiresForcedStyleRecalcPropagation() const { return true; }
 
-    RenderTextFragment* m_buttonText;
     RenderBlock* m_inner;
 };
 
diff --git a/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp b/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
index 248a192..ef55739 100644
--- a/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
+++ b/Source/core/rendering/RenderDeprecatedFlexibleBox.cpp
@@ -264,7 +264,7 @@
     RenderFlowThread* flowThread = flowThreadContainingBlock();
     if (logicalWidthChangedInRegions(flowThread))
         relayoutChildren = true;
-    if (updateRegionsAndExclusionsLogicalSize(flowThread))
+    if (updateRegionsAndShapesLogicalSize(flowThread))
         relayoutChildren = true;
 
     LayoutSize previousSize = size();
diff --git a/Source/core/rendering/RenderFlexibleBox.cpp b/Source/core/rendering/RenderFlexibleBox.cpp
index c3085d0..032a76d 100644
--- a/Source/core/rendering/RenderFlexibleBox.cpp
+++ b/Source/core/rendering/RenderFlexibleBox.cpp
@@ -39,63 +39,6 @@
 
 namespace WebCore {
 
-// Normally, -1 and 0 are not valid in a HashSet, but these are relatively likely order: values. Instead,
-// we make the two smallest int values invalid order: values (in the css parser code we clamp them to
-// int min + 2).
-struct RenderFlexibleBox::OrderHashTraits : WTF::GenericHashTraits<int> {
-    static const bool emptyValueIsZero = false;
-    static int emptyValue() { return std::numeric_limits<int>::min(); }
-    static void constructDeletedValue(int& slot) { slot = std::numeric_limits<int>::min() + 1; }
-    static bool isDeletedValue(int value) { return value == std::numeric_limits<int>::min() + 1; }
-};
-
-RenderFlexibleBox::OrderIterator::OrderIterator(const RenderFlexibleBox* flexibleBox)
-    : m_flexibleBox(flexibleBox)
-    , m_currentChild(0)
-    , m_orderValuesIterator(0)
-{
-}
-
-void RenderFlexibleBox::OrderIterator::setOrderValues(const OrderHashSet& orderValues)
-{
-    reset();
-    copyToVector(orderValues, m_orderValues);
-    std::sort(m_orderValues.begin(), m_orderValues.end());
-}
-
-RenderBox* RenderFlexibleBox::OrderIterator::first()
-{
-    reset();
-    return next();
-}
-
-RenderBox* RenderFlexibleBox::OrderIterator::next()
-{
-    do {
-        if (!m_currentChild) {
-            if (m_orderValuesIterator == m_orderValues.end())
-                return 0;
-            if (m_orderValuesIterator) {
-                ++m_orderValuesIterator;
-                if (m_orderValuesIterator == m_orderValues.end())
-                    return 0;
-            } else
-                m_orderValuesIterator = m_orderValues.begin();
-
-            m_currentChild = m_flexibleBox->firstChildBox();
-        } else
-            m_currentChild = m_currentChild->nextSiblingBox();
-    } while (!m_currentChild || m_currentChild->style()->order() != *m_orderValuesIterator);
-
-    return m_currentChild;
-}
-
-void RenderFlexibleBox::OrderIterator::reset()
-{
-    m_currentChild = 0;
-    m_orderValuesIterator = 0;
-}
-
 struct RenderFlexibleBox::LineContext {
     LineContext(LayoutUnit crossAxisOffset, LayoutUnit crossAxisExtent, size_t numberOfChildren, LayoutUnit maxAscent)
         : crossAxisOffset(crossAxisOffset)
@@ -343,7 +286,7 @@
     RenderFlowThread* flowThread = flowThreadContainingBlock();
     if (logicalWidthChangedInRegions(flowThread))
         relayoutChildren = true;
-    if (updateRegionsAndExclusionsLogicalSize(flowThread))
+    if (updateRegionsAndShapesLogicalSize(flowThread))
         relayoutChildren = true;
 
     m_numberOfInFlowChildrenOnFirstLine = -1;
@@ -351,7 +294,7 @@
     RenderBlock::startDelayUpdateScrollInfo();
 
     Vector<LineContext> lineContexts;
-    OrderHashSet orderValues;
+    Vector<int> orderValues;
     computeMainAxisPreferredSizes(orderValues);
     m_orderIterator.setOrderValues(orderValues);
 
@@ -762,17 +705,18 @@
 void RenderFlexibleBox::layoutFlexItems(bool relayoutChildren, Vector<LineContext>& lineContexts)
 {
     OrderedFlexItemList orderedChildren;
-    LayoutUnit preferredMainAxisExtent;
+    LayoutUnit sumFlexBaseSize;
     double totalFlexGrow;
     double totalWeightedFlexShrink;
-    LayoutUnit minMaxAppliedMainAxisExtent;
+    LayoutUnit sumHypotheticalMainSize;
 
     m_orderIterator.first();
     LayoutUnit crossAxisOffset = flowAwareBorderBefore() + flowAwarePaddingBefore();
     bool hasInfiniteLineLength = false;
-    while (computeNextFlexLine(orderedChildren, preferredMainAxisExtent, totalFlexGrow, totalWeightedFlexShrink, minMaxAppliedMainAxisExtent, hasInfiniteLineLength)) {
-        LayoutUnit availableFreeSpace = mainAxisContentExtent(preferredMainAxisExtent) - preferredMainAxisExtent;
-        FlexSign flexSign = (minMaxAppliedMainAxisExtent < preferredMainAxisExtent + availableFreeSpace) ? PositiveFlexibility : NegativeFlexibility;
+    while (computeNextFlexLine(orderedChildren, sumFlexBaseSize, totalFlexGrow, totalWeightedFlexShrink, sumHypotheticalMainSize, hasInfiniteLineLength)) {
+        LayoutUnit containerMainInnerSize = mainAxisContentExtent(sumHypotheticalMainSize);
+        LayoutUnit availableFreeSpace = containerMainInnerSize - sumFlexBaseSize;
+        FlexSign flexSign = (sumHypotheticalMainSize < containerMainInnerSize) ? PositiveFlexibility : NegativeFlexibility;
         InflexibleFlexItemSize inflexibleItems;
         Vector<LayoutUnit> childSizes;
         while (!resolveFlexibleLengths(flexSign, orderedChildren, availableFreeSpace, totalFlexGrow, totalWeightedFlexShrink, inflexibleItems, childSizes, hasInfiniteLineLength)) {
@@ -927,11 +871,17 @@
     return minimumValueForLength(margin, availableSize, view);
 }
 
-void RenderFlexibleBox::computeMainAxisPreferredSizes(OrderHashSet& orderValues)
+void RenderFlexibleBox::computeMainAxisPreferredSizes(Vector<int>& orderValues)
 {
     RenderView* renderView = view();
+    bool anyChildHasDefaultOrderValue = false;
+
     for (RenderBox* child = firstChildBox(); child; child = child->nextSiblingBox()) {
-        orderValues.add(child->style()->order());
+        // Avoid growing the vector for the common-case default value of 0.
+        if (int order = child->style()->order())
+            orderValues.append(child->style()->order());
+        else
+            anyChildHasDefaultOrderValue = true;
 
         if (child->isOutOfFlowPositioned())
             continue;
@@ -946,6 +896,13 @@
             child->setMarginBottom(computeChildMarginValue(child->style()->marginBottom(), renderView));
         }
     }
+
+    if (anyChildHasDefaultOrderValue) {
+        // Avoid growing the vector to the default capacity of 16 if we're only going to put one item in it.
+        if (orderValues.isEmpty())
+            orderValues.reserveInitialCapacity(1);
+        orderValues.append(0);
+    }
 }
 
 LayoutUnit RenderFlexibleBox::adjustChildSizeForMinAndMax(RenderBox* child, LayoutUnit childSize)
@@ -964,12 +921,12 @@
     return std::max(childSize, minExtent);
 }
 
-bool RenderFlexibleBox::computeNextFlexLine(OrderedFlexItemList& orderedChildren, LayoutUnit& preferredMainAxisExtent, double& totalFlexGrow, double& totalWeightedFlexShrink, LayoutUnit& minMaxAppliedMainAxisExtent, bool& hasInfiniteLineLength)
+bool RenderFlexibleBox::computeNextFlexLine(OrderedFlexItemList& orderedChildren, LayoutUnit& sumFlexBaseSize, double& totalFlexGrow, double& totalWeightedFlexShrink, LayoutUnit& sumHypotheticalMainSize, bool& hasInfiniteLineLength)
 {
     orderedChildren.clear();
-    preferredMainAxisExtent = 0;
+    sumFlexBaseSize = 0;
     totalFlexGrow = totalWeightedFlexShrink = 0;
-    minMaxAppliedMainAxisExtent = 0;
+    sumHypotheticalMainSize = 0;
 
     if (!m_orderIterator.currentChild())
         return false;
@@ -986,19 +943,20 @@
         }
 
         LayoutUnit childMainAxisExtent = preferredMainAxisContentExtentForChild(child, hasInfiniteLineLength);
-        LayoutUnit childMainAxisMarginBoxExtent = mainAxisBorderAndPaddingExtentForChild(child) + childMainAxisExtent;
-        childMainAxisMarginBoxExtent += isHorizontalFlow() ? child->marginWidth() : child->marginHeight();
+        LayoutUnit childMainAxisMarginBorderPadding = mainAxisBorderAndPaddingExtentForChild(child)
+            + (isHorizontalFlow() ? child->marginWidth() : child->marginHeight());
+        LayoutUnit childMainAxisMarginBoxExtent = childMainAxisExtent + childMainAxisMarginBorderPadding;
 
-        if (isMultiline() && preferredMainAxisExtent + childMainAxisMarginBoxExtent > lineBreakLength && lineHasInFlowItem)
+        if (isMultiline() && sumFlexBaseSize + childMainAxisMarginBoxExtent > lineBreakLength && lineHasInFlowItem)
             break;
         orderedChildren.append(child);
         lineHasInFlowItem  = true;
-        preferredMainAxisExtent += childMainAxisMarginBoxExtent;
+        sumFlexBaseSize += childMainAxisMarginBoxExtent;
         totalFlexGrow += child->style()->flexGrow();
         totalWeightedFlexShrink += child->style()->flexShrink() * childMainAxisExtent;
 
         LayoutUnit childMinMaxAppliedMainAxisExtent = adjustChildSizeForMinAndMax(child, childMainAxisExtent);
-        minMaxAppliedMainAxisExtent += childMinMaxAppliedMainAxisExtent - childMainAxisExtent + childMainAxisMarginBoxExtent;
+        sumHypotheticalMainSize += childMinMaxAppliedMainAxisExtent + childMainAxisMarginBorderPadding;
     }
     return true;
 }
diff --git a/Source/core/rendering/RenderFlexibleBox.h b/Source/core/rendering/RenderFlexibleBox.h
index 3bd1648..415d449 100644
--- a/Source/core/rendering/RenderFlexibleBox.h
+++ b/Source/core/rendering/RenderFlexibleBox.h
@@ -31,6 +31,7 @@
 #ifndef RenderFlexibleBox_h
 #define RenderFlexibleBox_h
 
+#include "core/rendering/OrderIterator.h"
 #include "core/rendering/RenderBlock.h"
 
 namespace WebCore {
@@ -74,26 +75,6 @@
         NoFlipForRowReverse,
     };
 
-    struct OrderHashTraits;
-    typedef HashSet<int, DefaultHash<int>::Hash, OrderHashTraits> OrderHashSet;
-
-    class OrderIterator {
-        WTF_MAKE_NONCOPYABLE(OrderIterator);
-    public:
-        OrderIterator(const RenderFlexibleBox*);
-        void setOrderValues(const OrderHashSet&);
-        RenderBox* currentChild() const { return m_currentChild; }
-        RenderBox* first();
-        RenderBox* next();
-        void reset();
-
-    private:
-        const RenderFlexibleBox* m_flexibleBox;
-        RenderBox* m_currentChild;
-        Vector<int> m_orderValues;
-        Vector<int>::const_iterator m_orderValuesIterator;
-    };
-
     typedef HashMap<const RenderBox*, LayoutUnit> InflexibleFlexItemSize;
     typedef Vector<RenderBox*> OrderedFlexItemList;
 
@@ -154,9 +135,10 @@
     LayoutUnit marginBoxAscentForChild(RenderBox*);
 
     LayoutUnit computeChildMarginValue(Length margin, RenderView*);
-    void computeMainAxisPreferredSizes(OrderHashSet&);
+    void computeMainAxisPreferredSizes(Vector<int>&);
     LayoutUnit adjustChildSizeForMinAndMax(RenderBox*, LayoutUnit childSize);
-    bool computeNextFlexLine(OrderedFlexItemList& orderedChildren, LayoutUnit& preferredMainAxisExtent, double& totalFlexGrow, double& totalWeightedFlexShrink, LayoutUnit& minMaxAppliedMainAxisExtent, bool& hasInfiniteLineLength);
+    // The hypothetical main size of an item is the flex base size clamped according to its min and max main size properties
+    bool computeNextFlexLine(OrderedFlexItemList& orderedChildren, LayoutUnit& sumFlexBaseSize, double& totalFlexGrow, double& totalWeightedFlexShrink, LayoutUnit& sumHypotheticalMainSize, bool& hasInfiniteLineLength);
 
     bool resolveFlexibleLengths(FlexSign, const OrderedFlexItemList&, LayoutUnit& availableFreeSpace, double& totalFlexGrow, double& totalWeightedFlexShrink, InflexibleFlexItemSize&, Vector<LayoutUnit>& childSizes, bool hasInfiniteLineLength);
     void freezeViolations(const Vector<Violation>&, LayoutUnit& availableFreeSpace, double& totalFlexGrow, double& totalWeightedFlexShrink, InflexibleFlexItemSize&, bool hasInfiniteLineLength);
diff --git a/Source/core/rendering/RenderFlowThread.cpp b/Source/core/rendering/RenderFlowThread.cpp
index f8148f4..9abce2f 100644
--- a/Source/core/rendering/RenderFlowThread.cpp
+++ b/Source/core/rendering/RenderFlowThread.cpp
@@ -48,13 +48,14 @@
 
 RenderFlowThread::RenderFlowThread()
     : RenderBlock(0)
+    , m_previousRegionCount(0)
     , m_autoLogicalHeightRegionsCount(0)
     , m_regionsInvalidated(false)
     , m_regionsHaveUniformLogicalWidth(true)
     , m_regionsHaveUniformLogicalHeight(true)
-    , m_overset(true)
     , m_hasRegionsWithStyling(false)
     , m_dispatchRegionLayoutUpdateEvent(false)
+    , m_dispatchRegionOversetChangeEvent(false)
     , m_pageLogicalSizeChanged(false)
     , m_inConstrainedLayoutPhase(false)
     , m_needsTwoPhasesLayout(false)
@@ -217,6 +218,9 @@
 
     if (shouldDispatchRegionLayoutUpdateEvent())
         dispatchRegionLayoutUpdateEvent();
+
+    if (shouldDispatchRegionOversetChangeEvent())
+        dispatchRegionOversetChangeEvent();
 }
 
 void RenderFlowThread::updateLogicalWidth()
@@ -729,45 +733,6 @@
     addForcedRegionBreak(clientHeight, this, false);
 }
 
-void RenderFlowThread::computeOverflowStateForRegions(LayoutUnit oldClientAfterEdge)
-{
-    LayoutUnit height = oldClientAfterEdge;
-
-    // FIXME: the visual overflow of middle region (if it is the last one to contain any content in a render flow thread)
-    // might not be taken into account because the render flow thread height is greater that that regions height + its visual overflow
-    // because of how computeLogicalHeight is implemented for RenderFlowThread (as a sum of all regions height).
-    // This means that the middle region will be marked as fit (even if it has visual overflow flowing into the next region)
-    if (hasRenderOverflow()
-        && ( (isHorizontalWritingMode() && visualOverflowRect().maxY() > clientBoxRect().maxY())
-            || (!isHorizontalWritingMode() && visualOverflowRect().maxX() > clientBoxRect().maxX())))
-        height = isHorizontalWritingMode() ? visualOverflowRect().maxY() : visualOverflowRect().maxX();
-
-    RenderRegion* lastReg = lastRegion();
-    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
-        RenderRegion* region = *iter;
-        LayoutUnit flowMin = height - (isHorizontalWritingMode() ? region->flowThreadPortionRect().y() : region->flowThreadPortionRect().x());
-        LayoutUnit flowMax = height - (isHorizontalWritingMode() ? region->flowThreadPortionRect().maxY() : region->flowThreadPortionRect().maxX());
-        RenderRegion::RegionState previousState = region->regionState();
-        RenderRegion::RegionState state = RenderRegion::RegionFit;
-        if (flowMin <= 0)
-            state = RenderRegion::RegionEmpty;
-        if (flowMax > 0 && region == lastReg)
-            state = RenderRegion::RegionOverset;
-        region->setRegionState(state);
-        // determine whether the NamedFlow object should dispatch a regionLayoutUpdate event
-        // FIXME: currently it cannot determine whether a region whose regionOverset state remained either "fit" or "overset" has actually
-        // changed, so it just assumes that the NamedFlow should dispatch the event
-        if (previousState != state
-            || state == RenderRegion::RegionFit
-            || state == RenderRegion::RegionOverset)
-            setDispatchRegionLayoutUpdateEvent(true);
-    }
-
-    // With the regions overflow state computed we can also set the overset flag for the named flow.
-    // If there are no valid regions in the chain, overset is true.
-    m_overset = lastReg ? lastReg->regionState() == RenderRegion::RegionOverset : true;
-}
-
 bool RenderFlowThread::regionInRange(const RenderRegion* targetRegion, const RenderRegion* startRegion, const RenderRegion* endRegion) const
 {
     ASSERT(targetRegion);
diff --git a/Source/core/rendering/RenderFlowThread.h b/Source/core/rendering/RenderFlowThread.h
index ac740f7..4ed0c66 100644
--- a/Source/core/rendering/RenderFlowThread.h
+++ b/Source/core/rendering/RenderFlowThread.h
@@ -104,7 +104,10 @@
     LayoutUnit pageLogicalWidthForOffset(LayoutUnit);
     LayoutUnit pageLogicalHeightForOffset(LayoutUnit);
     LayoutUnit pageRemainingLogicalHeightForOffset(LayoutUnit, PageBoundaryRule = IncludePageBoundary);
-    
+
+    virtual void setPageBreak(LayoutUnit /*offset*/, LayoutUnit /*spaceShortage*/) { }
+    virtual void updateMinimumPageHeight(LayoutUnit /*offset*/, LayoutUnit /*minHeight*/) { }
+
     enum RegionAutoGenerationPolicy {
         AllowRegionAutoGeneration,
         DisallowRegionAutoGeneration,
@@ -126,16 +129,15 @@
     RenderRegion* firstRegion() const;
     RenderRegion* lastRegion() const;
 
+    bool previousRegionCountChanged() const { return m_previousRegionCount != m_regionList.size(); }
+    void updatePreviousRegionCount() { m_previousRegionCount = m_regionList.size(); }
+
     void setRegionRangeForBox(const RenderBox*, LayoutUnit offsetFromLogicalTopOfFirstPage);
     void getRegionRangeForBox(const RenderBox*, RenderRegion*& startRegion, RenderRegion*& endRegion) const;
 
     void clearRenderObjectCustomStyle(const RenderObject*,
         const RenderRegion* oldStartRegion = 0, const RenderRegion* oldEndRegion = 0,
         const RenderRegion* newStartRegion = 0, const RenderRegion* newEndRegion = 0);
-    
-    void computeOverflowStateForRegions(LayoutUnit oldClientAfterEdge);
-
-    bool overset() const { return m_overset; }
 
     // Check if the object is in region and the region is part of this flow thread.
     bool objectInFlowRegion(const RenderObject*, const RenderRegion*) const;
@@ -181,15 +183,20 @@
 
     void setDispatchRegionLayoutUpdateEvent(bool value) { m_dispatchRegionLayoutUpdateEvent = value; }
     bool shouldDispatchRegionLayoutUpdateEvent() { return m_dispatchRegionLayoutUpdateEvent; }
+
+    void setDispatchRegionOversetChangeEvent(bool value) { m_dispatchRegionOversetChangeEvent = value; }
+    bool shouldDispatchRegionOversetChangeEvent() const { return m_dispatchRegionOversetChangeEvent; }
     
     // Override if the flow thread implementation supports dispatching events when the flow layout is updated (e.g. for named flows)
     virtual void dispatchRegionLayoutUpdateEvent() { m_dispatchRegionLayoutUpdateEvent = false; }
+    virtual void dispatchRegionOversetChangeEvent() { m_dispatchRegionOversetChangeEvent = false; }
 
     void initializeRegionsOverrideLogicalContentHeight(RenderRegion* = 0);
 
     virtual void autoGenerateRegionsToBlockOffset(LayoutUnit) { };
 
     RenderRegionList m_regionList;
+    unsigned short m_previousRegionCount;
 
     class RenderRegionRange {
     public:
@@ -254,9 +261,9 @@
     bool m_regionsInvalidated : 1;
     bool m_regionsHaveUniformLogicalWidth : 1;
     bool m_regionsHaveUniformLogicalHeight : 1;
-    bool m_overset : 1;
     bool m_hasRegionsWithStyling : 1;
     bool m_dispatchRegionLayoutUpdateEvent : 1;
+    bool m_dispatchRegionOversetChangeEvent : 1;
     bool m_pageLogicalSizeChanged : 1;
     bool m_inConstrainedLayoutPhase : 1;
     bool m_needsTwoPhasesLayout : 1;
diff --git a/Source/core/rendering/RenderFrameSet.cpp b/Source/core/rendering/RenderFrameSet.cpp
index 150922a..8b6acf9 100644
--- a/Source/core/rendering/RenderFrameSet.cpp
+++ b/Source/core/rendering/RenderFrameSet.cpp
@@ -166,13 +166,13 @@
     m_allowBorder.resize(size + 1);
 }
 
-void RenderFrameSet::layOutAxis(GridAxis& axis, const Length* grid, int availableLen)
+void RenderFrameSet::layOutAxis(GridAxis& axis, const Vector<Length>& grid, int availableLen)
 {
     availableLen = max(availableLen, 0);
 
     int* gridLayout = axis.m_sizes.data();
 
-    if (!grid) {
+    if (grid.isEmpty()) {
         gridLayout[0] = availableLen;
         return;
     }
diff --git a/Source/core/rendering/RenderFrameSet.h b/Source/core/rendering/RenderFrameSet.h
index 65701dd..99c39ef 100644
--- a/Source/core/rendering/RenderFrameSet.h
+++ b/Source/core/rendering/RenderFrameSet.h
@@ -112,7 +112,7 @@
 
     void setIsResizing(bool);
 
-    void layOutAxis(GridAxis&, const Length*, int availableSpace);
+    void layOutAxis(GridAxis&, const Vector<Length>&, int availableSpace);
     void computeEdgeInfo();
     void fillFromEdgeInfo(const FrameEdgeInfo& edgeInfo, int r, int c);
     void positionFrames();
diff --git a/Source/core/rendering/RenderGrid.cpp b/Source/core/rendering/RenderGrid.cpp
index 6cf84f3..cfbd888 100644
--- a/Source/core/rendering/RenderGrid.cpp
+++ b/Source/core/rendering/RenderGrid.cpp
@@ -29,6 +29,7 @@
 #include "core/rendering/LayoutRepainter.h"
 #include "core/rendering/RenderLayer.h"
 #include "core/rendering/RenderView.h"
+#include "core/rendering/style/GridCoordinate.h"
 
 namespace WebCore {
 
@@ -174,7 +175,7 @@
     RenderFlowThread* flowThread = flowThreadContainingBlock();
     if (logicalWidthChangedInRegions(flowThread))
         relayoutChildren = true;
-    if (updateRegionsAndExclusionsLogicalSize(flowThread))
+    if (updateRegionsAndShapesLogicalSize(flowThread))
         relayoutChildren = true;
 
     LayoutSize previousSize = size();
@@ -421,7 +422,7 @@
 
 const GridTrackSize& RenderGrid::gridTrackSize(TrackSizingDirection direction, size_t i) const
 {
-    const Vector<GridTrackSize>& trackStyles = (direction == ForColumns) ? style()->gridColumns() : style()->gridRows();
+    const Vector<GridTrackSize>& trackStyles = (direction == ForColumns) ? style()->gridDefinitionColumns() : style()->gridDefinitionRows();
     if (i >= trackStyles.size())
         return (direction == ForColumns) ? style()->gridAutoColumns() : style()->gridAutoRows();
 
@@ -430,12 +431,17 @@
 
 size_t RenderGrid::explicitGridColumnCount() const
 {
-    return style()->gridColumns().size();
+    return style()->gridDefinitionColumns().size();
 }
 
 size_t RenderGrid::explicitGridRowCount() const
 {
-    return style()->gridRows().size();
+    return style()->gridDefinitionRows().size();
+}
+
+size_t RenderGrid::explicitGridSizeForSide(GridPositionSide side) const
+{
+    return (side == ColumnStartSide || side == ColumnEndSide) ? explicitGridColumnCount() : explicitGridRowCount();
 }
 
 size_t RenderGrid::maximumIndexInDirection(TrackSizingDirection direction) const
@@ -661,8 +667,8 @@
         insertItemIntoGrid(child, GridCoordinate(*rowPositions, *columnPositions));
     }
 
-    ASSERT(gridRowCount() >= style()->gridRows().size());
-    ASSERT(gridColumnCount() >= style()->gridColumns().size());
+    ASSERT(gridRowCount() >= style()->gridDefinitionRows().size());
+    ASSERT(gridColumnCount() >= style()->gridDefinitionColumns().size());
 
     if (autoFlow == AutoFlowNone) {
         // If we did collect some grid items, they won't be placed thus never laid out.
@@ -803,25 +809,25 @@
     clearGrid();
 }
 
-RenderGrid::GridCoordinate RenderGrid::cachedGridCoordinate(const RenderBox* gridItem) const
+GridCoordinate RenderGrid::cachedGridCoordinate(const RenderBox* gridItem) const
 {
     ASSERT(m_gridItemCoordinate.contains(gridItem));
     return m_gridItemCoordinate.get(gridItem);
 }
 
-RenderGrid::GridSpan RenderGrid::resolveGridPositionsFromAutoPlacementPosition(const RenderBox*, TrackSizingDirection, size_t initialPosition) const
+GridSpan RenderGrid::resolveGridPositionsFromAutoPlacementPosition(const RenderBox*, TrackSizingDirection, size_t initialPosition) const
 {
     // FIXME: We don't support spanning with auto positions yet. Once we do, this is wrong. Also we should make
     // sure the grid can accomodate the new item as we only grow 1 position in a given direction.
     return GridSpan(initialPosition, initialPosition);
 }
 
-PassOwnPtr<RenderGrid::GridSpan> RenderGrid::resolveGridPositionsFromStyle(const RenderBox* gridItem, TrackSizingDirection direction) const
+PassOwnPtr<GridSpan> RenderGrid::resolveGridPositionsFromStyle(const RenderBox* gridItem, TrackSizingDirection direction) const
 {
-    const GridPosition& initialPosition = (direction == ForColumns) ? gridItem->style()->gridStart() : gridItem->style()->gridBefore();
-    const GridPositionSide initialPositionSide = (direction == ForColumns) ? StartSide : BeforeSide;
-    const GridPosition& finalPosition = (direction == ForColumns) ? gridItem->style()->gridEnd() : gridItem->style()->gridAfter();
-    const GridPositionSide finalPositionSide = (direction == ForColumns) ? EndSide : AfterSide;
+    const GridPosition& initialPosition = (direction == ForColumns) ? gridItem->style()->gridColumnStart() : gridItem->style()->gridRowStart();
+    const GridPositionSide initialPositionSide = (direction == ForColumns) ? ColumnStartSide : RowStartSide;
+    const GridPosition& finalPosition = (direction == ForColumns) ? gridItem->style()->gridColumnEnd() : gridItem->style()->gridRowEnd();
+    const GridPositionSide finalPositionSide = (direction == ForColumns) ? ColumnEndSide : RowEndSide;
 
     // We should NEVER see both spans as they should have been handled during style resolve.
     ASSERT(!initialPosition.isSpan() || !finalPosition.isSpan());
@@ -859,23 +865,49 @@
 static size_t adjustGridPositionForSide(size_t resolvedPosition, GridPositionSide side)
 {
     // An item finishing on the N-th line belongs to the N-1-th cell.
-    if (side == EndSide || side == AfterSide)
+    if (side == ColumnEndSide || side == RowEndSide)
         return resolvedPosition ? resolvedPosition - 1 : 0;
 
     return resolvedPosition;
 }
 
+size_t RenderGrid::resolveNamedGridLinePositionFromStyle(const GridPosition& position, GridPositionSide side) const
+{
+    ASSERT(!position.namedGridLine().isNull());
+
+    const NamedGridLinesMap& gridLinesNames = (side == ColumnStartSide || side == ColumnEndSide) ? style()->namedGridColumnLines() : style()->namedGridRowLines();
+    NamedGridLinesMap::const_iterator it = gridLinesNames.find(position.namedGridLine());
+    if (it == gridLinesNames.end()) {
+        if (position.isPositive())
+            return 0;
+        const size_t lastLine = explicitGridSizeForSide(side);
+        return adjustGridPositionForSide(lastLine, side);
+    }
+
+    size_t namedGridLineIndex;
+    if (position.isPositive())
+        namedGridLineIndex = std::min<size_t>(position.integerPosition(), it->value.size()) - 1;
+    else
+        namedGridLineIndex = std::max<int>(it->value.size() - abs(position.integerPosition()), 0);
+    return adjustGridPositionForSide(it->value[namedGridLineIndex], side);
+}
+
 size_t RenderGrid::resolveGridPositionFromStyle(const GridPosition& position, GridPositionSide side) const
 {
     // FIXME: Handle other values for grid-{row,column} like ranges or line names.
     switch (position.type()) {
     case ExplicitPosition: {
         ASSERT(position.integerPosition());
+
+        if (!position.namedGridLine().isNull())
+            return resolveNamedGridLinePositionFromStyle(position, side);
+
+        // Handle <integer> explicit position.
         if (position.isPositive())
             return adjustGridPositionForSide(position.integerPosition() - 1, side);
 
         size_t resolvedPosition = abs(position.integerPosition()) - 1;
-        const size_t endOfTrack = (side == StartSide || side == EndSide) ? explicitGridColumnCount() : explicitGridRowCount();
+        const size_t endOfTrack = explicitGridSizeForSide(side);
 
         // Per http://lists.w3.org/Archives/Public/www-style/2013Mar/0589.html, we clamp negative value to the first line.
         if (endOfTrack < resolvedPosition)
@@ -896,7 +928,7 @@
     return 0;
 }
 
-PassOwnPtr<RenderGrid::GridSpan> RenderGrid::resolveGridPositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, GridPositionSide side) const
+PassOwnPtr<GridSpan> RenderGrid::resolveGridPositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition& position, GridPositionSide side) const
 {
     if (position.isAuto())
         return GridSpan::create(resolvedOppositePosition, resolvedOppositePosition);
@@ -907,7 +939,7 @@
     // 'span 1' is contained inside a single grid track regardless of the direction.
     // That's why the CSS span value is one more than the offset we apply.
     size_t positionOffset = position.spanPosition() - 1;
-    if (side == StartSide || side == BeforeSide) {
+    if (side == ColumnStartSide || side == RowStartSide) {
         size_t initialResolvedPosition = std::max<int>(0, resolvedOppositePosition - positionOffset);
         return GridSpan::create(initialResolvedPosition, resolvedOppositePosition);
     }
diff --git a/Source/core/rendering/RenderGrid.h b/Source/core/rendering/RenderGrid.h
index 1ee30de..074f859 100644
--- a/Source/core/rendering/RenderGrid.h
+++ b/Source/core/rendering/RenderGrid.h
@@ -30,13 +30,15 @@
 
 namespace WebCore {
 
+class GridCoordinate;
+class GridSpan;
 class GridTrack;
 
 enum GridPositionSide {
-    StartSide,
-    EndSide,
-    BeforeSide,
-    AfterSide
+    ColumnStartSide,
+    ColumnEndSide,
+    RowStartSide,
+    RowEndSide
 };
 
 class RenderGrid FINAL : public RenderBlock {
@@ -58,41 +60,6 @@
 
     LayoutUnit computePreferredTrackWidth(const GridLength&, size_t) const;
 
-    struct GridSpan {
-        static PassOwnPtr<GridSpan> create(size_t initialPosition, size_t finalPosition)
-        {
-            return adoptPtr(new GridSpan(initialPosition, finalPosition));
-        }
-
-        GridSpan(size_t initialPosition, size_t finalPosition)
-            : initialPositionIndex(initialPosition)
-            , finalPositionIndex(finalPosition)
-        {
-            ASSERT(initialPositionIndex <= finalPositionIndex);
-        }
-
-        size_t initialPositionIndex;
-        size_t finalPositionIndex;
-    };
-
-    struct GridCoordinate {
-        // HashMap requires a default constuctor.
-        GridCoordinate()
-            : columns(0, 0)
-            , rows(0, 0)
-        {
-        }
-
-        GridCoordinate(const GridSpan& r, const GridSpan& c)
-            : columns(c)
-            , rows(r)
-        {
-        }
-
-        GridSpan columns;
-        GridSpan rows;
-    };
-
     class GridIterator;
     enum TrackSizingDirection { ForColumns, ForRows };
     void computedUsedBreadthOfGridTracks(TrackSizingDirection, Vector<GridTrack>& columnTracks, Vector<GridTrack>& rowTracks);
@@ -126,6 +93,7 @@
     const GridTrackSize& gridTrackSize(TrackSizingDirection, size_t) const;
     size_t explicitGridColumnCount() const;
     size_t explicitGridRowCount() const;
+    size_t explicitGridSizeForSide(GridPositionSide) const;
     size_t maximumIndexInDirection(TrackSizingDirection) const;
 
     LayoutUnit logicalContentHeightForChild(RenderBox*, Vector<GridTrack>&);
@@ -136,6 +104,7 @@
 
     GridSpan resolveGridPositionsFromAutoPlacementPosition(const RenderBox*, TrackSizingDirection, size_t) const;
     PassOwnPtr<GridSpan> resolveGridPositionsFromStyle(const RenderBox*, TrackSizingDirection) const;
+    size_t resolveNamedGridLinePositionFromStyle(const GridPosition&, GridPositionSide) const;
     size_t resolveGridPositionFromStyle(const GridPosition&, GridPositionSide) const;
     PassOwnPtr<GridSpan> resolveGridPositionAgainstOppositePosition(size_t resolvedOppositePosition, const GridPosition&, GridPositionSide) const;
 
diff --git a/Source/core/rendering/RenderImage.cpp b/Source/core/rendering/RenderImage.cpp
index ea1df7a..6eb89bb 100644
--- a/Source/core/rendering/RenderImage.cpp
+++ b/Source/core/rendering/RenderImage.cpp
@@ -381,7 +381,7 @@
 void RenderImage::paint(PaintInfo& paintInfo, const LayoutPoint& paintOffset)
 {
     RenderReplaced::paint(paintInfo, paintOffset);
-    
+
     if (paintInfo.phase == PaintPhaseOutline)
         paintAreaElementFocusRing(paintInfo);
 }
@@ -411,26 +411,35 @@
     if (path.isEmpty())
         return;
 
-    // FIXME: Do we need additional code to clip the path to the image's bounding box?
-
     RenderStyle* areaElementStyle = areaElement->computedStyle();
     unsigned short outlineWidth = areaElementStyle->outlineWidth();
     if (!outlineWidth)
         return;
 
+    // FIXME: Clip path instead of context when Skia pathops is ready.
+    // https://crbug.com/251206
+    paintInfo.context->clip(absoluteContentBox());
     paintInfo.context->drawFocusRing(path, outlineWidth,
         areaElementStyle->outlineOffset(),
         areaElementStyle->visitedDependentColor(CSSPropertyOutlineColor));
 }
 
-void RenderImage::areaElementFocusChanged(HTMLAreaElement* element)
+void RenderImage::areaElementFocusChanged(HTMLAreaElement* areaElement)
 {
-    ASSERT_UNUSED(element, element->imageElement() == node());
+    ASSERT(areaElement->imageElement() == node());
 
-    // It would be more efficient to only repaint the focus ring rectangle
-    // for the passed-in area element. That would require adding functions
-    // to the area element class.
-    repaint();
+    Path path = areaElement->computePath(this);
+    if (path.isEmpty())
+        return;
+
+    RenderStyle* areaElementStyle = areaElement->computedStyle();
+    unsigned short outlineWidth = areaElementStyle->outlineWidth();
+
+    IntRect repaintRect = enclosingIntRect(path.boundingRect());
+    repaintRect.moveBy(-absoluteContentBox().location());
+    repaintRect.inflate(outlineWidth);
+
+    repaintRectangle(repaintRect);
 }
 
 void RenderImage::paintIntoRect(GraphicsContext* context, const LayoutRect& rect)
diff --git a/Source/core/rendering/RenderInline.cpp b/Source/core/rendering/RenderInline.cpp
index af8708a..3752c45 100644
--- a/Source/core/rendering/RenderInline.cpp
+++ b/Source/core/rendering/RenderInline.cpp
@@ -1391,7 +1391,7 @@
     
     RenderStyle* styleToUse = style();
     if (styleToUse->outlineStyleIsAuto() || hasOutlineAnnotation()) {
-        if (!theme()->supportsFocusRing(styleToUse)) {
+        if (theme()->shouldDrawDefaultFocusRing(this)) {
             // Only paint the focus ring by hand if the theme isn't able to draw the focus ring.
             paintFocusRing(paintInfo, paintOffset, styleToUse);
         }
diff --git a/Source/core/rendering/RenderLayer.cpp b/Source/core/rendering/RenderLayer.cpp
index 70f6a3e..568ec43 100644
--- a/Source/core/rendering/RenderLayer.cpp
+++ b/Source/core/rendering/RenderLayer.cpp
@@ -95,7 +95,6 @@
 #include "core/rendering/RenderInline.h"
 #include "core/rendering/RenderLayerBacking.h"
 #include "core/rendering/RenderLayerCompositor.h"
-#include "core/rendering/RenderMarquee.h"
 #include "core/rendering/RenderReplica.h"
 #include "core/rendering/RenderScrollbar.h"
 #include "core/rendering/RenderScrollbarPart.h"
@@ -149,7 +148,6 @@
     , m_3DTransformedDescendantStatusDirty(true)
     , m_has3DTransformedDescendant(false)
     , m_containsDirtyOverlayScrollbars(false)
-    , m_updatingMarqueePosition(false)
 #if !ASSERT_DISABLED
     , m_layerListMutationAllowed(true)
 #endif
@@ -420,16 +418,6 @@
         backing()->updateAfterLayout(updateFlags);
     }
 
-    // With all our children positioned, now update our marquee if we need to.
-    if (renderer()->isMarquee()) {
-        RenderMarquee* marquee = toRenderMarquee(renderer());
-        // FIXME: would like to use TemporaryChange<> but it doesn't work with bitfields.
-        bool oldUpdatingMarqueePosition = m_updatingMarqueePosition;
-        m_updatingMarqueePosition = true;
-        marquee->updateMarqueePosition();
-        m_updatingMarqueePosition = oldUpdatingMarqueePosition;
-    }
-
     if (geometryMap)
         geometryMap->popMappingsToAncestor(parent());
 }
@@ -506,6 +494,14 @@
     return settings && settings->acceleratedCompositingForOverflowScrollEnabled();
 }
 
+// FIXME: This is a temporary flag and should be removed once accelerated
+// overflow scroll is ready (crbug.com/254111).
+bool RenderLayer::compositorDrivenAcceleratedScrollingEnabled() const
+{
+    const Settings* settings = renderer()->document()->settings();
+    return settings && settings->isCompositorDrivenAcceleratedScrollingEnabled();
+}
+
 // Determine whether the current layer can be promoted to a stacking container.
 // We do this by computing what positive and negative z-order lists would look
 // like before and after promotion, and ensuring that proper stacking order is
@@ -765,14 +761,6 @@
     // of an object, thus RenderReplica will still repaint itself properly as the layer position was
     // updated above.
 
-    if (renderer()->isMarquee()) {
-        RenderMarquee* marquee = toRenderMarquee(renderer());
-        bool oldUpdatingMarqueePosition = m_updatingMarqueePosition;
-        m_updatingMarqueePosition = true;
-        marquee->updateMarqueePosition();
-        m_updatingMarqueePosition = oldUpdatingMarqueePosition;
-    }
-
     if (geometryMap)
         geometryMap->popMappingsToAncestor(parent());
 }
@@ -1874,8 +1862,10 @@
             ancestorLayer->convertToLayerCoords(fixedPositionContainerLayer, ancestorCoords);
 
             location += (fixedContainerCoords - ancestorCoords);
-            return ancestorLayer;
+        } else {
+            location += toSize(layer->location());
         }
+        return ancestorLayer;
     }
     
     RenderLayer* parentLayer;
@@ -2159,13 +2149,7 @@
             view->markLazyBlocksForLayout();
         }
 
-        if (!m_updatingMarqueePosition) {
-            // Avoid updating compositing layers if, higher on the stack, we're already updating layer
-            // positions. Updating layer positions requires a full walk of up-to-date RenderLayers, and
-            // in this case we're still updating their positions; we'll update compositing layers later
-            // when that completes.
-            updateCompositingLayersAfterScroll();
-        }
+        updateCompositingLayersAfterScroll();
     }
 
     RenderLayerModelObject* repaintContainer = renderer()->containerForRepaint();
@@ -2455,31 +2439,29 @@
     
     LayoutSize difference = (currentSize + newOffset - adjustedOldOffset).expandedTo(minimumSize) - currentSize;
 
-    ASSERT_WITH_SECURITY_IMPLICATION(element->isStyledElement());
-    StyledElement* styledElement = static_cast<StyledElement*>(element);
     bool isBoxSizingBorder = renderer->style()->boxSizing() == BORDER_BOX;
 
     EResize resize = renderer->style()->resize();
     if (resize != RESIZE_VERTICAL && difference.width()) {
         if (element->isFormControlElement()) {
             // Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
-            styledElement->setInlineStyleProperty(CSSPropertyMarginLeft, String::number(renderer->marginLeft() / zoomFactor) + "px", false);
-            styledElement->setInlineStyleProperty(CSSPropertyMarginRight, String::number(renderer->marginRight() / zoomFactor) + "px", false);
+            element->setInlineStyleProperty(CSSPropertyMarginLeft, String::number(renderer->marginLeft() / zoomFactor) + "px", false);
+            element->setInlineStyleProperty(CSSPropertyMarginRight, String::number(renderer->marginRight() / zoomFactor) + "px", false);
         }
         LayoutUnit baseWidth = renderer->width() - (isBoxSizingBorder ? LayoutUnit() : renderer->borderAndPaddingWidth());
         baseWidth = baseWidth / zoomFactor;
-        styledElement->setInlineStyleProperty(CSSPropertyWidth, String::number(roundToInt(baseWidth + difference.width())) + "px", false);
+        element->setInlineStyleProperty(CSSPropertyWidth, String::number(roundToInt(baseWidth + difference.width())) + "px", false);
     }
 
     if (resize != RESIZE_HORIZONTAL && difference.height()) {
         if (element->isFormControlElement()) {
             // Make implicit margins from the theme explicit (see <http://bugs.webkit.org/show_bug.cgi?id=9547>).
-            styledElement->setInlineStyleProperty(CSSPropertyMarginTop, String::number(renderer->marginTop() / zoomFactor) + "px", false);
-            styledElement->setInlineStyleProperty(CSSPropertyMarginBottom, String::number(renderer->marginBottom() / zoomFactor) + "px", false);
+            element->setInlineStyleProperty(CSSPropertyMarginTop, String::number(renderer->marginTop() / zoomFactor) + "px", false);
+            element->setInlineStyleProperty(CSSPropertyMarginBottom, String::number(renderer->marginBottom() / zoomFactor) + "px", false);
         }
         LayoutUnit baseHeight = renderer->height() - (isBoxSizingBorder ? LayoutUnit() : renderer->borderAndPaddingHeight());
         baseHeight = baseHeight / zoomFactor;
-        styledElement->setInlineStyleProperty(CSSPropertyHeight, String::number(roundToInt(baseHeight + difference.height())) + "px", false);
+        element->setInlineStyleProperty(CSSPropertyHeight, String::number(roundToInt(baseHeight + difference.height())) + "px", false);
     }
 
     document->updateLayout();
@@ -5002,26 +4984,20 @@
     layerBounds = LayoutRect(offset, size());
 
     // Update the clip rects that will be passed to child layers.
-    if (renderer()->hasClipOrOverflowClip()) {
+    if (renderer()->hasOverflowClip()) {
         // This layer establishes a clip of some kind.
-        if (renderer()->hasOverflowClip() && (this != clipRectsContext.rootLayer || clipRectsContext.respectOverflowClip == RespectOverflowClip)) {
+        if (this != clipRectsContext.rootLayer || clipRectsContext.respectOverflowClip == RespectOverflowClip) {
             foregroundRect.intersect(toRenderBox(renderer())->overflowClipRect(offset, clipRectsContext.region, clipRectsContext.overlayScrollbarSizeRelevancy));
             if (renderer()->style()->hasBorderRadius())
                 foregroundRect.setHasRadius(true);
         }
 
-        if (renderer()->hasClip()) {
-            // Clip applies to *us* as well, so go ahead and update the damageRect.
-            LayoutRect newPosClip = toRenderBox(renderer())->clipRect(offset, clipRectsContext.region);
-            backgroundRect.intersect(newPosClip);
-            foregroundRect.intersect(newPosClip);
-            outlineRect.intersect(newPosClip);
-        }
-
-        // If we establish a clip at all, then go ahead and make sure our background
+        // If we establish an overflow clip at all, then go ahead and make sure our background
         // rect is intersected with our layer's bounds including our visual overflow,
         // since any visual overflow like box-shadow or border-outset is not clipped by overflow:auto/hidden.
         if (renderBox()->hasVisualOverflow()) {
+            // FIXME: Perhaps we should be propagating the borderbox as the clip rect for children, even though
+            //        we may need to inflate our clip specifically for shadows or outsets.
             // FIXME: Does not do the right thing with CSS regions yet, since we don't yet factor in the
             // individual region boxes as overflow.
             LayoutRect layerBoundsWithVisualOverflow = renderBox()->visualOverflowRect();
@@ -5037,6 +5013,15 @@
                 backgroundRect.intersect(bounds);
         }
     }
+
+    // CSS clip (different than clipping due to overflow) can clip to any box, even if it falls outside of the border box.
+    if (renderer()->hasClip()) {
+        // Clip applies to *us* as well, so go ahead and update the damageRect.
+        LayoutRect newPosClip = toRenderBox(renderer())->clipRect(offset, clipRectsContext.region);
+        backgroundRect.intersect(newPosClip);
+        foregroundRect.intersect(newPosClip);
+        outlineRect.intersect(newPosClip);
+    }
 }
 
 LayoutRect RenderLayer::childrenClipRect() const
diff --git a/Source/core/rendering/RenderLayer.h b/Source/core/rendering/RenderLayer.h
index 89c41e6..fea79f4 100644
--- a/Source/core/rendering/RenderLayer.h
+++ b/Source/core/rendering/RenderLayer.h
@@ -45,6 +45,7 @@
 #define RenderLayer_h
 
 #include "core/platform/ScrollableArea.h"
+#include "core/rendering/CompositingReasons.h"
 #include "core/rendering/PaintInfo.h"
 #include "core/rendering/RenderBox.h"
 
@@ -79,56 +80,6 @@
     NeedsFullRepaintForPositionedMovementLayout = 1 << 1
 };
 
-enum {
-    CompositingReasonNone                                   = 0,
-
-    // Intrinsic reasons that can be known right away by the layer
-    CompositingReason3DTransform                            = 1 << 0,
-    CompositingReasonVideo                                  = 1 << 1,
-    CompositingReasonCanvas                                 = 1 << 2,
-    CompositingReasonPlugin                                 = 1 << 3,
-    CompositingReasonIFrame                                 = 1 << 4,
-    CompositingReasonBackfaceVisibilityHidden               = 1 << 5,
-    CompositingReasonAnimation                              = 1 << 6,
-    CompositingReasonFilters                                = 1 << 7,
-    CompositingReasonPositionFixed                          = 1 << 8,
-    CompositingReasonPositionSticky                         = 1 << 9,
-    CompositingReasonOverflowScrollingTouch                 = 1 << 10,
-    CompositingReasonBlending                               = 1 << 11,
-
-    // Overlap reasons that require knowing what's behind you in paint-order before knowing the answer
-    CompositingReasonAssumedOverlap                         = 1 << 12,
-    CompositingReasonOverlap                                = 1 << 13,
-    CompositingReasonNegativeZIndexChildren                 = 1 << 14,
-
-    // Subtree reasons that require knowing what the status of your subtree is before knowing the answer
-    CompositingReasonTransformWithCompositedDescendants     = 1 << 15,
-    CompositingReasonOpacityWithCompositedDescendants       = 1 << 16,
-    CompositingReasonMaskWithCompositedDescendants          = 1 << 17,
-    CompositingReasonReflectionWithCompositedDescendants    = 1 << 18,
-    CompositingReasonFilterWithCompositedDescendants        = 1 << 19,
-    CompositingReasonBlendingWithCompositedDescendants      = 1 << 20,
-    CompositingReasonClipsCompositingDescendants            = 1 << 21,
-    CompositingReasonPerspective                            = 1 << 22,
-    CompositingReasonPreserve3D                             = 1 << 23,
-    CompositingReasonReflectionOfCompositedParent           = 1 << 24,
-
-    // The root layer is a special case that may be forced to be a layer, but also it needs to be
-    // a layer if anything else in the subtree is composited.
-    CompositingReasonRoot                                   = 1 << 25,
-
-    // RenderLayerBacking internal hierarchy reasons
-    CompositingReasonLayerForClip                           = 1 << 26,
-    CompositingReasonLayerForScrollbar                      = 1 << 27,
-    CompositingReasonLayerForScrollingContainer             = 1 << 28,
-    CompositingReasonLayerForForeground                     = 1 << 29,
-    CompositingReasonLayerForBackground                     = 1 << 30,
-    CompositingReasonLayerForMask                           = 1 << 31,
-
-    // Note: if you add more reasons here, you will need to update the WebCompositingReasons enum as well.
-};
-typedef unsigned CompositingReasons;
-
 class ClipRect {
 public:
     ClipRect()
@@ -900,6 +851,9 @@
     void dirtyAncestorChainHasOutOfFlowPositionedDescendantStatus();
 
     bool acceleratedCompositingForOverflowScrollEnabled() const;
+    // FIXME: This is a temporary flag and should be removed once accelerated
+    // overflow scroll is ready (crbug.com/254111).
+    bool compositorDrivenAcceleratedScrollingEnabled() const;
     void updateCanBeStackingContainer();
     void collectBeforePromotionZOrderList(RenderLayer* ancestorStackingContext, OwnPtr<Vector<RenderLayer*> >& posZOrderListBeforePromote, OwnPtr<Vector<RenderLayer*> >& negZOrderListBeforePromote);
     void collectAfterPromotionZOrderList(RenderLayer* ancestorStackingContext, OwnPtr<Vector<RenderLayer*> >& posZOrderListAfterPromote, OwnPtr<Vector<RenderLayer*> >& negZOrderListAfterPromote);
@@ -1220,7 +1174,6 @@
                                             // in a preserves3D hierarchy. Hint to do 3D-aware hit testing.
 
     bool m_containsDirtyOverlayScrollbars : 1;
-    bool m_updatingMarqueePosition : 1;
 
 #if !ASSERT_DISABLED
     bool m_layerListMutationAllowed : 1;
@@ -1245,7 +1198,7 @@
     LayoutRect m_repaintRect; // Cached repaint rects. Used by layout.
     LayoutRect m_outlineBox;
 
-    // Paint time offset only, it is used for properly paint relative / sticky positioned elements and exclusion boxes on floats.
+    // Paint time offset only, it is used for properly paint relative / sticky positioned elements and shape boxes on floats.
     LayoutSize m_paintOffset;
 
     // Our (x,y) coordinates are in our parent layer's coordinate space.
diff --git a/Source/core/rendering/RenderLayerCompositor.cpp b/Source/core/rendering/RenderLayerCompositor.cpp
index ecbfcb4..55f2c44 100644
--- a/Source/core/rendering/RenderLayerCompositor.cpp
+++ b/Source/core/rendering/RenderLayerCompositor.cpp
@@ -60,11 +60,12 @@
 #include "core/rendering/RenderReplica.h"
 #include "core/rendering/RenderVideo.h"
 #include "core/rendering/RenderView.h"
-#include <wtf/MemoryInstrumentationHashMap.h>
-#include <wtf/TemporaryChange.h>
+#include "wtf/MemoryInstrumentationHashMap.h"
+#include "wtf/MemoryInstrumentationHashSet.h"
+#include "wtf/TemporaryChange.h"
 
 #if !LOG_DISABLED
-#include <wtf/CurrentTime.h>
+#include "wtf/CurrentTime.h"
 #endif
 
 #ifndef NDEBUG
@@ -1573,16 +1574,14 @@
     if (requiresCompositingForTransform(renderer))
         directReasons |= CompositingReason3DTransform;
 
+    // Only zero or one of the following conditions will be true for a given RenderLayer.
     if (requiresCompositingForVideo(renderer))
         directReasons |= CompositingReasonVideo;
-
-    if (requiresCompositingForCanvas(renderer))
+    else if (requiresCompositingForCanvas(renderer))
         directReasons |= CompositingReasonCanvas;
-
-    if (requiresCompositingForPlugin(renderer))
+    else if (requiresCompositingForPlugin(renderer))
         directReasons |= CompositingReasonPlugin;
-
-    if (requiresCompositingForFrame(renderer))
+    else if (requiresCompositingForFrame(renderer))
         directReasons |= CompositingReasonIFrame;
     
     if (requiresCompositingForBackfaceVisibilityHidden(renderer))
@@ -2498,7 +2497,7 @@
         case RootLayerAttachedViaEnclosingFrame: {
             // The layer will get hooked up via RenderLayerBacking::updateGraphicsLayerConfiguration()
             // for the frame's renderer in the parent document.
-            m_renderView->document()->ownerElement()->scheduleSyntheticStyleChange();
+            m_renderView->document()->ownerElement()->scheduleLayerUpdate();
             break;
         }
     }
@@ -2521,7 +2520,7 @@
             m_rootContentLayer->removeFromParent();
 
         if (HTMLFrameOwnerElement* ownerElement = m_renderView->document()->ownerElement())
-            ownerElement->scheduleSyntheticStyleChange();
+            ownerElement->scheduleLayerUpdate();
         break;
     }
     case RootLayerAttachedViaChromeClient: {
@@ -2561,13 +2560,13 @@
 
     for (Frame* child = frame->tree()->firstChild(); child; child = child->tree()->traverseNext(frame)) {
         if (child->document() && child->document()->ownerElement())
-            child->document()->ownerElement()->scheduleSyntheticStyleChange();
+            child->document()->ownerElement()->scheduleLayerUpdate();
     }
     
     // Compositing also affects the answer to RenderIFrame::requiresAcceleratedCompositing(), so 
     // we need to schedule a style recalc in our parent document.
     if (HTMLFrameOwnerElement* ownerElement = m_renderView->document()->ownerElement())
-        ownerElement->scheduleSyntheticStyleChange();
+        ownerElement->scheduleLayerUpdate();
 }
 
 bool RenderLayerCompositor::layerHas3DContent(const RenderLayer* layer) const
diff --git a/Source/core/rendering/RenderMarquee.cpp b/Source/core/rendering/RenderMarquee.cpp
index 013a0c1..6dee3e9 100644
--- a/Source/core/rendering/RenderMarquee.cpp
+++ b/Source/core/rendering/RenderMarquee.cpp
@@ -274,6 +274,13 @@
         m_timer.stop();
 }
 
+void RenderMarquee::layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight)
+{
+    RenderBlock::layoutBlock(relayoutChildren, pageLogicalHeight);
+
+    updateMarqueePosition();
+}
+
 void RenderMarquee::timerFired(Timer<RenderMarquee>*)
 {
     // FIXME: Why do we need to check the view and not just the RenderMarquee itself?
diff --git a/Source/core/rendering/RenderMarquee.h b/Source/core/rendering/RenderMarquee.h
index 0c6ac01..02aef3e 100644
--- a/Source/core/rendering/RenderMarquee.h
+++ b/Source/core/rendering/RenderMarquee.h
@@ -86,6 +86,8 @@
 
     virtual void styleDidChange(StyleDifference, const RenderStyle* oldStyle) OVERRIDE FINAL;
 
+    virtual void layoutBlock(bool relayoutChildren, LayoutUnit pageLogicalHeight = 0) OVERRIDE FINAL;
+
     void timerFired(Timer<RenderMarquee>*);
 
     int m_currentLoop;
diff --git a/Source/core/rendering/RenderMultiColumnBlock.cpp b/Source/core/rendering/RenderMultiColumnBlock.cpp
index e441829..434fccd 100644
--- a/Source/core/rendering/RenderMultiColumnBlock.cpp
+++ b/Source/core/rendering/RenderMultiColumnBlock.cpp
@@ -27,6 +27,8 @@
 #include "core/rendering/RenderMultiColumnBlock.h"
 
 #include "core/rendering/RenderMultiColumnFlowThread.h"
+#include "core/rendering/RenderMultiColumnSet.h"
+#include "core/rendering/RenderView.h"
 
 using namespace std;
 
@@ -37,8 +39,8 @@
     , m_flowThread(0)
     , m_columnCount(1)
     , m_columnWidth(0)
-    , m_columnHeight(0)
-    , m_requiresBalancing(false)
+    , m_columnHeightAvailable(0)
+    , m_inBalancingPass(false)
 {
 }
 
@@ -89,21 +91,49 @@
 {
     // We don't actually update any of the variables. We just subclassed to adjust our column height.
     updateLogicalHeight();
-    LayoutUnit newContentLogicalHeight = contentLogicalHeight();
-    m_requiresBalancing = !newContentLogicalHeight;
-    if (!m_requiresBalancing) {
-        // The regions will be invalidated when we lay them out and they change size to
-        // the new column height.
-        if (columnHeight() != newContentLogicalHeight)
-            setColumnHeight(newContentLogicalHeight);
-    }
+    m_columnHeightAvailable = max<LayoutUnit>(contentLogicalHeight(), 0);
     setLogicalHeight(0);
 }
 
-bool RenderMultiColumnBlock::relayoutForPagination(bool, LayoutUnit, LayoutStateMaintainer&)
+bool RenderMultiColumnBlock::relayoutForPagination(bool, LayoutUnit, LayoutStateMaintainer& statePusher)
 {
-    // FIXME: Implement.
-    return false;
+    if (m_inBalancingPass || !requiresBalancing())
+        return false;
+    m_inBalancingPass = true; // Prevent re-entering this method (and recursion into layout).
+
+    bool needsRelayout;
+    bool neededRelayout = false;
+    bool firstPass = true;
+    do {
+        // Column heights may change here because of balancing. We may have to do multiple layout
+        // passes, depending on how the contents is fitted to the changed column heights. In most
+        // cases, laying out again twice or even just once will suffice. Sometimes we need more
+        // passes than that, though, but the number of retries should not exceed the number of
+        // columns, unless we have a bug.
+        needsRelayout = false;
+        for (RenderBox* childBox = firstChildBox(); childBox; childBox = childBox->nextSiblingBox()) {
+            if (childBox != m_flowThread && childBox->isRenderMultiColumnSet()) {
+                RenderMultiColumnSet* multicolSet = toRenderMultiColumnSet(childBox);
+                if (multicolSet->calculateBalancedHeight(firstPass)) {
+                    multicolSet->setChildNeedsLayout(true, MarkOnlyThis);
+                    needsRelayout = true;
+                }
+            }
+        }
+
+        if (needsRelayout) {
+            // Layout again. Column balancing resulted in a new height.
+            neededRelayout = true;
+            m_flowThread->setChildNeedsLayout(true, MarkOnlyThis);
+            setChildNeedsLayout(true, MarkOnlyThis);
+            if (firstPass)
+                statePusher.pop();
+            layoutBlock(false);
+        }
+        firstPass = false;
+    } while (needsRelayout);
+    m_inBalancingPass = false;
+    return neededRelayout;
 }
 
 void RenderMultiColumnBlock::addChild(RenderObject* newChild, RenderObject* beforeChild)
@@ -121,17 +151,17 @@
     if (!m_flowThread)
         return 0;
     
-    // Update the sizes of our regions (but not the placement) before we lay out the flow thread.
+    // Update the dimensions of our regions before we lay out the flow thread.
     // FIXME: Eventually this is going to get way more complicated, and we will be destroying regions
     // instead of trying to keep them around.
     bool shouldInvalidateRegions = false;
     for (RenderBox* childBox = firstChildBox(); childBox; childBox = childBox->nextSiblingBox()) {
         if (childBox == m_flowThread)
             continue;
-        
+
         if (relayoutChildren || childBox->needsLayout()) {
-            childBox->updateLogicalWidth();
-            childBox->updateLogicalHeight();
+            if (!m_inBalancingPass && childBox->isRenderMultiColumnSet())
+                toRenderMultiColumnSet(childBox)->prepareForLayout();
             shouldInvalidateRegions = true;
         }
     }
diff --git a/Source/core/rendering/RenderMultiColumnBlock.h b/Source/core/rendering/RenderMultiColumnBlock.h
index 1dfaf23..c4e3cdc 100644
--- a/Source/core/rendering/RenderMultiColumnBlock.h
+++ b/Source/core/rendering/RenderMultiColumnBlock.h
@@ -37,15 +37,14 @@
 public:
     RenderMultiColumnBlock(Element*);
 
-    LayoutUnit columnHeight() const { return m_columnHeight; }
-    void setColumnHeight(LayoutUnit columnHeight) { m_columnHeight = columnHeight; }
+    LayoutUnit columnHeightAvailable() const { return m_columnHeightAvailable; }
 
     LayoutUnit columnWidth() const { return m_columnWidth; }
     unsigned columnCount() const { return m_columnCount; }
 
     RenderMultiColumnFlowThread* flowThread() const { return m_flowThread; }
 
-    bool requiresBalancing() const { return m_requiresBalancing; }
+    bool requiresBalancing() const { return !m_columnHeightAvailable; }
 
 private:
     virtual bool isRenderMultiColumnBlock() const { return true; }
@@ -70,8 +69,8 @@
     unsigned m_columnCount;   // The default column count/width that are based off our containing block width. These values represent only the default,
     LayoutUnit m_columnWidth; // since a multi-column block that is split across variable width pages or regions will have different column counts and widths in each.
                               // These values will be cached (eventually) for multi-column blocks.
-    LayoutUnit m_columnHeight; // The current column height.
-    bool m_requiresBalancing; // Whether or not the block specified any kind of logical height. We have to balance by default if it didn't.
+    LayoutUnit m_columnHeightAvailable; // Total height available to columns, or 0 if auto.
+    bool m_inBalancingPass; // Set when relayouting for column balancing.
 };
 
 inline RenderMultiColumnBlock* toRenderMultiColumnBlock(RenderObject* object)
diff --git a/Source/core/rendering/RenderMultiColumnFlowThread.cpp b/Source/core/rendering/RenderMultiColumnFlowThread.cpp
index 2bf3688..5e3c26f 100644
--- a/Source/core/rendering/RenderMultiColumnFlowThread.cpp
+++ b/Source/core/rendering/RenderMultiColumnFlowThread.cpp
@@ -95,14 +95,25 @@
     firstSet = RenderMultiColumnSet::createAnonymous(this);
     firstSet->setStyle(RenderStyle::createAnonymousStyleWithDisplay(parentBlock->style(), BLOCK));
     parentBlock->RenderBlock::addChild(firstSet);
-    
-    // Even though we aren't placed yet, we can go ahead and set up our size.
-    firstSet->updateLogicalWidth();
-    firstSet->updateLogicalHeight();
 
-    firstSet->setRequiresBalancing(parentBlock->requiresBalancing());
-    
+    // Even though we aren't placed yet, we can go ahead and set up our size. At this point we're
+    // typically in the middle of laying out the thread, attempting to paginate, and we need to do
+    // some rudimentary "layout" of the set now, so that pagination will work.
+    firstSet->prepareForLayout();
+
     validateRegions();
 }
 
+void RenderMultiColumnFlowThread::setPageBreak(LayoutUnit offset, LayoutUnit spaceShortage)
+{
+    if (RenderMultiColumnSet* multicolSet = toRenderMultiColumnSet(regionAtBlockOffset(offset)))
+        multicolSet->recordSpaceShortage(spaceShortage);
+}
+
+void RenderMultiColumnFlowThread::updateMinimumPageHeight(LayoutUnit offset, LayoutUnit minHeight)
+{
+    if (RenderMultiColumnSet* multicolSet = toRenderMultiColumnSet(regionAtBlockOffset(offset)))
+        multicolSet->updateMinimumColumnHeight(minHeight);
+}
+
 }
diff --git a/Source/core/rendering/RenderMultiColumnFlowThread.h b/Source/core/rendering/RenderMultiColumnFlowThread.h
index d57cb1b..ace5c43 100644
--- a/Source/core/rendering/RenderMultiColumnFlowThread.h
+++ b/Source/core/rendering/RenderMultiColumnFlowThread.h
@@ -44,6 +44,8 @@
     virtual void computeLogicalHeight(LayoutUnit logicalHeight, LayoutUnit logicalTop, LogicalExtentComputedValues&) const OVERRIDE;
     virtual void autoGenerateRegionsToBlockOffset(LayoutUnit) OVERRIDE;
     virtual LayoutUnit initialLogicalWidth() const OVERRIDE;
+    virtual void setPageBreak(LayoutUnit offset, LayoutUnit spaceShortage) OVERRIDE;
+    virtual void updateMinimumPageHeight(LayoutUnit offset, LayoutUnit minHeight) OVERRIDE;
 };
 
 } // namespace WebCore
diff --git a/Source/core/rendering/RenderMultiColumnSet.cpp b/Source/core/rendering/RenderMultiColumnSet.cpp
index 59b89ad..78413e4 100644
--- a/Source/core/rendering/RenderMultiColumnSet.cpp
+++ b/Source/core/rendering/RenderMultiColumnSet.cpp
@@ -40,7 +40,8 @@
     , m_computedColumnCount(1)
     , m_computedColumnWidth(0)
     , m_computedColumnHeight(0)
-    , m_requiresBalancing(false)
+    , m_maxColumnHeight(LayoutUnit::max())
+    , m_minSpaceShortage(LayoutUnit::max())
     , m_minimumColumnHeight(0)
     , m_forcedBreaksCount(0)
     , m_maximumDistanceBetweenForcedBreaks(0)
@@ -56,13 +57,84 @@
     return renderer;
 }
 
+LayoutUnit RenderMultiColumnSet::heightAdjustedForSetOffset(LayoutUnit height) const
+{
+    RenderMultiColumnBlock* multicolBlock = toRenderMultiColumnBlock(parent());
+    LayoutUnit contentLogicalTop = logicalTop() - multicolBlock->borderBefore() - multicolBlock->paddingBefore();
+
+    height -= contentLogicalTop;
+    return max(height, LayoutUnit(1)); // Let's avoid zero height, as that would probably cause an infinite amount of columns to be created.
+}
+
 LayoutUnit RenderMultiColumnSet::pageLogicalTopForOffset(LayoutUnit offset) const
 {
     LayoutUnit portionLogicalTop = (isHorizontalWritingMode() ? flowThreadPortionRect().y() : flowThreadPortionRect().x());
-    unsigned columnIndex = (offset - portionLogicalTop) / computedColumnHeight();
+    unsigned columnIndex = columnIndexAtOffset(offset, AssumeNewColumns);
     return portionLogicalTop + columnIndex * computedColumnHeight();
 }
 
+void RenderMultiColumnSet::setAndConstrainColumnHeight(LayoutUnit newHeight)
+{
+    m_computedColumnHeight = newHeight;
+    if (m_computedColumnHeight > m_maxColumnHeight)
+        m_computedColumnHeight = m_maxColumnHeight;
+    // FIXME: the height may also be affected by the enclosing pagination context, if any.
+}
+
+bool RenderMultiColumnSet::calculateBalancedHeight(bool initial)
+{
+    ASSERT(toRenderMultiColumnBlock(parent())->requiresBalancing());
+    LayoutUnit oldColumnHeight = m_computedColumnHeight;
+    LayoutUnit currentMinSpaceShortage = m_minSpaceShortage;
+    m_minSpaceShortage = LayoutUnit::max();
+
+    if (initial) {
+        // Start with the lowest imaginable column height.
+        LayoutUnit logicalHeightGuess = ceilf(float(flowThread()->logicalHeight()) / float(m_computedColumnCount));
+        logicalHeightGuess = max(logicalHeightGuess, m_minimumColumnHeight);
+        setAndConstrainColumnHeight(logicalHeightGuess);
+
+        // The multicol container now typically needs at least one more layout pass with a new
+        // column height, but if height was specified, we only need to do this if we found that we
+        // might need less space than that. On the other hand, if we determined that the columns
+        // need to be as tall as the specified height of the container, we have already laid it out
+        // correctly, and there's no need for another pass.
+        return m_computedColumnHeight != oldColumnHeight;
+    }
+
+    if (columnCount() <= computedColumnCount()) {
+        // With the current column height, the content fits without creating overflowing columns. We're done.
+        return false;
+    }
+
+    // If the initial guessed column height wasn't enough, stretch it now. Stretch by the lowest
+    // amount of space shortage found during layout.
+
+    ASSERT(currentMinSpaceShortage != LayoutUnit::max()); // If this can actually happen, we probably have a bug.
+    if (currentMinSpaceShortage == LayoutUnit::max())
+        return false; // So bail out rather than looping infinitely.
+
+    setAndConstrainColumnHeight(m_computedColumnHeight + currentMinSpaceShortage);
+
+    // If we reach the maximum column height (typically set by the height or max-height property),
+    // we may not be allowed to stretch further. Return true only if stretching
+    // succeeded. Otherwise, we're done.
+    ASSERT(m_computedColumnHeight >= oldColumnHeight); // We shouldn't be able to shrink the height!
+    return m_computedColumnHeight > oldColumnHeight;
+}
+
+void RenderMultiColumnSet::recordSpaceShortage(LayoutUnit spaceShortage)
+{
+    if (spaceShortage >= m_minSpaceShortage)
+        return;
+
+    // The space shortage is what we use as our stretch amount. We need a positive number here in
+    // order to get anywhere.
+    ASSERT(spaceShortage > 0);
+
+    m_minSpaceShortage = spaceShortage;
+}
+
 void RenderMultiColumnSet::updateLogicalWidth()
 {
     RenderMultiColumnBlock* parentBlock = toRenderMultiColumnBlock(parent());
@@ -74,9 +146,6 @@
 
     // If we overflow, increase our logical width.
     unsigned colCount = columnCount();
-    if (!colCount)
-        return;
-    
     LayoutUnit colGap = columnGap();
     LayoutUnit minimumContentLogicalWidth = colCount * computedColumnWidth() + (colCount - 1) * colGap;
     LayoutUnit currentContentLogicalWidth = contentLogicalWidth();
@@ -88,23 +157,42 @@
     setLogicalWidth(logicalWidth() + delta);
 }
 
-void RenderMultiColumnSet::updateLogicalHeight()
+void RenderMultiColumnSet::prepareForLayout()
 {
-    // FIXME: This is the only class that overrides updateLogicalHeight. If we didn't have to set computedColumnHeight,
-    // we could remove this and make updateLogicalHeight non-virtual. https://bugs.webkit.org/show_bug.cgi?id=96804
-    // Make sure our column height is up to date.
-    LogicalExtentComputedValues computedValues;
-    computeLogicalHeight(0, 0, computedValues);
-    setComputedColumnHeight(computedValues.m_extent); // FIXME: Once we make more than one column set, this will become variable.
-    
-    // Our logical height is always just the height of our columns.
-    setLogicalHeight(computedColumnHeight());
+    RenderMultiColumnBlock* multicolBlock = toRenderMultiColumnBlock(parent());
+    RenderStyle* multicolStyle = multicolBlock->style();
+
+    // Set box logical top.
+    ASSERT(!previousSiblingBox() || !previousSiblingBox()->isRenderMultiColumnSet()); // FIXME: multiple set not implemented; need to examine previous set to calculate the correct logical top.
+    setLogicalTop(multicolBlock->borderBefore() + multicolBlock->paddingBefore());
+
+    // Set box width.
+    updateLogicalWidth();
+
+    if (multicolBlock->requiresBalancing()) {
+        // Set maximum column height. We will not stretch beyond this.
+        m_maxColumnHeight = LayoutUnit::max();
+        if (!multicolStyle->logicalHeight().isAuto())
+            m_maxColumnHeight = multicolBlock->computeContentLogicalHeight(multicolStyle->logicalHeight(), -1);
+        if (!multicolStyle->logicalMaxHeight().isUndefined()) {
+            LayoutUnit logicalMaxHeight = multicolBlock->computeContentLogicalHeight(multicolStyle->logicalMaxHeight(), -1);
+            if (m_maxColumnHeight > logicalMaxHeight)
+                m_maxColumnHeight = logicalMaxHeight;
+        }
+        m_maxColumnHeight = heightAdjustedForSetOffset(m_maxColumnHeight);
+        m_computedColumnHeight = 0; // Restart balancing.
+    } else {
+        setAndConstrainColumnHeight(heightAdjustedForSetOffset(multicolBlock->columnHeightAvailable()));
+    }
+
+    // Nuke previously stored minimum column height. Contents may have changed for all we know.
+    m_minimumColumnHeight = 0;
 }
 
-void RenderMultiColumnSet::computeLogicalHeight(LayoutUnit, LayoutUnit, LogicalExtentComputedValues& computedValues) const
+void RenderMultiColumnSet::computeLogicalHeight(LayoutUnit, LayoutUnit logicalTop, LogicalExtentComputedValues& computedValues) const
 {
-    RenderMultiColumnBlock* parentBlock = toRenderMultiColumnBlock(parent());
-    computedValues.m_extent = parentBlock->columnHeight();
+    computedValues.m_extent = m_computedColumnHeight;
+    computedValues.m_position = logicalTop;
 }
 
 LayoutUnit RenderMultiColumnSet::columnGap() const
@@ -119,12 +207,16 @@
 
 unsigned RenderMultiColumnSet::columnCount() const
 {
+    // We must always return a value of 1 or greater. Column count = 0 is a meaningless situation,
+    // and will confuse and cause problems in other parts of the code.
     if (!computedColumnHeight())
-        return 0;
-    
+        return 1;
+
     // Our portion rect determines our column count. We have as many columns as needed to fit all the content.
     LayoutUnit logicalHeightInColumns = flowThread()->isHorizontalWritingMode() ? flowThreadPortionRect().height() : flowThreadPortionRect().width();
-    return ceil(static_cast<float>(logicalHeightInColumns) / computedColumnHeight());
+    unsigned count = ceil(static_cast<float>(logicalHeightInColumns) / computedColumnHeight());
+    ASSERT(count >= 1);
+    return count;
 }
 
 LayoutRect RenderMultiColumnSet::columnRectAt(unsigned index) const
@@ -144,18 +236,22 @@
     return LayoutRect(colLogicalTop, colLogicalLeft, colLogicalHeight, colLogicalWidth);
 }
 
-unsigned RenderMultiColumnSet::columnIndexAtOffset(LayoutUnit offset) const
+unsigned RenderMultiColumnSet::columnIndexAtOffset(LayoutUnit offset, ColumnIndexCalculationMode mode) const
 {
     LayoutRect portionRect(flowThreadPortionRect());
-    LayoutUnit flowThreadLogicalTop = isHorizontalWritingMode() ? portionRect.y() : portionRect.x();
-    LayoutUnit flowThreadLogicalBottom = isHorizontalWritingMode() ? portionRect.maxY() : portionRect.maxX();
-    
+
     // Handle the offset being out of range.
+    LayoutUnit flowThreadLogicalTop = isHorizontalWritingMode() ? portionRect.y() : portionRect.x();
     if (offset < flowThreadLogicalTop)
         return 0;
-    if (offset >= flowThreadLogicalBottom)
-        return columnCount() - 1;
-    
+    // If we're laying out right now, we cannot constrain against some logical bottom, since it
+    // isn't known yet. Otherwise, just return the last column if we're past the logical bottom.
+    if (mode == ClampToExistingColumns) {
+        LayoutUnit flowThreadLogicalBottom = isHorizontalWritingMode() ? portionRect.maxY() : portionRect.maxX();
+        if (offset >= flowThreadLogicalBottom)
+            return columnCount() - 1;
+    }
+
     // Just divide by the column height to determine the correct column.
     return static_cast<float>(offset - flowThreadLogicalTop) / computedColumnHeight();
 }
diff --git a/Source/core/rendering/RenderMultiColumnSet.h b/Source/core/rendering/RenderMultiColumnSet.h
index bd5b0cd..a0d2792 100644
--- a/Source/core/rendering/RenderMultiColumnSet.h
+++ b/Source/core/rendering/RenderMultiColumnSet.h
@@ -56,10 +56,8 @@
         m_computedColumnWidth = width;
         m_computedColumnCount = count;
     }
-    void setComputedColumnHeight(LayoutUnit height)
-    {
-        m_computedColumnHeight = height;
-    }
+
+    LayoutUnit heightAdjustedForSetOffset(LayoutUnit height) const;
 
     void updateMinimumColumnHeight(LayoutUnit height) { m_minimumColumnHeight = std::max(height, m_minimumColumnHeight); }
     LayoutUnit minimumColumnHeight() const { return m_minimumColumnHeight; }
@@ -84,12 +82,21 @@
         m_forcedBreakOffset = offsetFromFirstPage;
     }
 
-    bool requiresBalancing() const { return m_requiresBalancing; }
-    void setRequiresBalancing(bool balancing) { m_requiresBalancing = balancing; }
+    // Calculate the column height when contents are supposed to be balanced. If 'initial' is set,
+    // guess an initial column height; otherwise, stretch the column height a tad. Return true if
+    // column height changed and another layout pass is required.
+    bool calculateBalancedHeight(bool initial);
+
+    // Record space shortage (the amount of space that would have been enough to prevent some
+    // element from being moved to the next column) at a column break. The smallest amount of space
+    // shortage we find is the amount with which we will stretch the column height, if it turns out
+    // after layout that the columns weren't tall enough.
+    void recordSpaceShortage(LayoutUnit spaceShortage);
 
     virtual void updateLogicalWidth() OVERRIDE;
-    virtual void updateLogicalHeight() OVERRIDE;
-    
+
+    void prepareForLayout();
+
 private:
     RenderMultiColumnSet(RenderFlowThread*);
 
@@ -123,15 +130,22 @@
 
     LayoutRect flowThreadPortionRectAt(unsigned index) const;
     LayoutRect flowThreadPortionOverflowRect(const LayoutRect& flowThreadPortion, unsigned index, unsigned colCount, LayoutUnit colGap) const;
-    
-    unsigned columnIndexAtOffset(LayoutUnit) const;
-    
+
+    enum ColumnIndexCalculationMode {
+        ClampToExistingColumns, // Stay within the range of already existing columns.
+        AssumeNewColumns // Allow column indices outside the range of already existing columns.
+    };
+    unsigned columnIndexAtOffset(LayoutUnit, ColumnIndexCalculationMode = ClampToExistingColumns) const;
+
+    void setAndConstrainColumnHeight(LayoutUnit);
+
     unsigned m_computedColumnCount;
     LayoutUnit m_computedColumnWidth;
     LayoutUnit m_computedColumnHeight;
     
     // The following variables are used when balancing the column set.
-    bool m_requiresBalancing; // Whether or not the columns in the column set have to be balanced, i.e., made to be similar logical heights.
+    LayoutUnit m_maxColumnHeight; // Maximum column height allowed.
+    LayoutUnit m_minSpaceShortage; // The smallest amout of space shortage that caused a column break.
     LayoutUnit m_minimumColumnHeight;
     unsigned m_forcedBreaksCount; // FIXME: We will ultimately need to cache more information to balance around forced breaks properly.
     LayoutUnit m_maximumDistanceBetweenForcedBreaks;
diff --git a/Source/core/rendering/RenderNamedFlowThread.cpp b/Source/core/rendering/RenderNamedFlowThread.cpp
index f83f46c..0f64ff5 100644
--- a/Source/core/rendering/RenderNamedFlowThread.cpp
+++ b/Source/core/rendering/RenderNamedFlowThread.cpp
@@ -53,8 +53,10 @@
 }
 
 RenderNamedFlowThread::RenderNamedFlowThread(PassRefPtr<NamedFlow> namedFlow)
-    : m_namedFlow(namedFlow)
+    : m_overset(true)
+    , m_namedFlow(namedFlow)
     , m_regionLayoutUpdateEventTimer(this, &RenderNamedFlowThread::regionLayoutUpdateEventTimerFired)
+    , m_regionOversetChangeEventTimer(this, &RenderNamedFlowThread::regionOversetChangeEventTimerFired)
 {
 }
 
@@ -293,6 +295,54 @@
     invalidateRegions();
 }
 
+void RenderNamedFlowThread::computeOversetStateForRegions(LayoutUnit oldClientAfterEdge)
+{
+    LayoutUnit height = oldClientAfterEdge;
+
+    // FIXME: the visual overflow of middle region (if it is the last one to contain any content in a render flow thread)
+    // might not be taken into account because the render flow thread height is greater that that regions height + its visual overflow
+    // because of how computeLogicalHeight is implemented for RenderFlowThread (as a sum of all regions height).
+    // This means that the middle region will be marked as fit (even if it has visual overflow flowing into the next region)
+    if (hasRenderOverflow()
+        && ( (isHorizontalWritingMode() && visualOverflowRect().maxY() > clientBoxRect().maxY())
+            || (!isHorizontalWritingMode() && visualOverflowRect().maxX() > clientBoxRect().maxX())))
+        height = isHorizontalWritingMode() ? visualOverflowRect().maxY() : visualOverflowRect().maxX();
+
+    RenderRegion* lastReg = lastRegion();
+    for (RenderRegionList::iterator iter = m_regionList.begin(); iter != m_regionList.end(); ++iter) {
+        RenderRegion* region = *iter;
+        LayoutUnit flowMin = height - (isHorizontalWritingMode() ? region->flowThreadPortionRect().y() : region->flowThreadPortionRect().x());
+        LayoutUnit flowMax = height - (isHorizontalWritingMode() ? region->flowThreadPortionRect().maxY() : region->flowThreadPortionRect().maxX());
+        RegionOversetState previousState = region->regionOversetState();
+        RegionOversetState state = RegionFit;
+        if (flowMin <= 0)
+            state = RegionEmpty;
+        if (flowMax > 0 && region == lastReg)
+            state = RegionOverset;
+        region->setRegionOversetState(state);
+        // determine whether the NamedFlow object should dispatch a regionLayoutUpdate event
+        // FIXME: currently it cannot determine whether a region whose regionOverset state remained either "fit" or "overset" has actually
+        // changed, so it just assumes that the NamedFlow should dispatch the event
+        if (previousState != state
+            || state == RegionFit
+            || state == RegionOverset)
+            setDispatchRegionLayoutUpdateEvent(true);
+
+        if (previousState != state)
+            setDispatchRegionOversetChangeEvent(true);
+    }
+
+    // If the number of regions has changed since we last computed the overset property, schedule the regionOversetChange event.
+    if (previousRegionCountChanged()) {
+        setDispatchRegionOversetChangeEvent(true);
+        updatePreviousRegionCount();
+    }
+
+    // With the regions overflow state computed we can also set the overset flag for the named flow.
+    // If there are no valid regions in the chain, overset is true.
+    m_overset = lastReg ? lastReg->regionOversetState() == RegionOverset : true;
+}
+
 void RenderNamedFlowThread::checkInvalidRegions()
 {
     Vector<RenderRegion*> newValidRegions;
@@ -413,6 +463,9 @@
 
     ASSERT(child->node()->isElementNode());
     RenderObject* parentRenderer = NodeRenderingContext(child->node()).parentRenderer();
+    if (!parentRenderer)
+        return true;
+
     return parentRenderer->isChildAllowed(child, style);
 }
 
@@ -425,6 +478,15 @@
         m_regionLayoutUpdateEventTimer.startOneShot(0);
 }
 
+void RenderNamedFlowThread::dispatchRegionOversetChangeEvent()
+{
+    RenderFlowThread::dispatchRegionOversetChangeEvent();
+    InspectorInstrumentation::didChangeRegionOverset(document(), m_namedFlow.get());
+
+    if (!m_regionOversetChangeEventTimer.isActive() && m_namedFlow->hasEventListeners())
+        m_regionOversetChangeEventTimer.startOneShot(0);
+}
+
 void RenderNamedFlowThread::regionLayoutUpdateEventTimerFired(Timer<RenderNamedFlowThread>*)
 {
     ASSERT(m_namedFlow);
@@ -432,6 +494,13 @@
     m_namedFlow->dispatchRegionLayoutUpdateEvent();
 }
 
+void RenderNamedFlowThread::regionOversetChangeEventTimerFired(Timer<RenderNamedFlowThread>*)
+{
+    ASSERT(m_namedFlow);
+
+    m_namedFlow->dispatchRegionOversetChangeEvent();
+}
+
 void RenderNamedFlowThread::setMarkForDestruction()
 {
     if (m_namedFlow->flowState() == NamedFlow::FlowStateNull)
diff --git a/Source/core/rendering/RenderNamedFlowThread.h b/Source/core/rendering/RenderNamedFlowThread.h
index 67b6e95..e9fad64 100644
--- a/Source/core/rendering/RenderNamedFlowThread.h
+++ b/Source/core/rendering/RenderNamedFlowThread.h
@@ -68,6 +68,9 @@
     virtual void addRegionToThread(RenderRegion*) OVERRIDE;
     virtual void removeRegionFromThread(RenderRegion*) OVERRIDE;
 
+    bool overset() const { return m_overset; }
+    void computeOversetStateForRegions(LayoutUnit oldClientAfterEdge);
+
     void registerNamedFlowContentNode(Node*);
     void unregisterNamedFlowContentNode(Node*);
     const NamedFlowContentNodes& contentNodes() const { return m_contentNodes; }
@@ -87,6 +90,7 @@
     virtual bool isChildAllowed(RenderObject*, RenderStyle*) const OVERRIDE;
 
     virtual void dispatchRegionLayoutUpdateEvent() OVERRIDE;
+    virtual void dispatchRegionOversetChangeEvent() OVERRIDE;
 
     bool dependsOn(RenderNamedFlowThread* otherRenderFlowThread) const;
     void addDependencyOnFlowThread(RenderNamedFlowThread*);
@@ -98,6 +102,7 @@
 
     bool canBeDestroyed() const { return m_invalidRegionList.isEmpty() && m_regionList.isEmpty() && m_contentNodes.isEmpty(); }
     void regionLayoutUpdateEventTimerFired(Timer<RenderNamedFlowThread>*);
+    void regionOversetChangeEventTimerFired(Timer<RenderNamedFlowThread>*);
     void clearContentNodes();
 
 private:
@@ -119,10 +124,13 @@
 
     RenderRegionList m_invalidRegionList;
 
+    bool m_overset : 1;
+
     // The DOM Object that represents a named flow.
     RefPtr<NamedFlow> m_namedFlow;
 
     Timer<RenderNamedFlowThread> m_regionLayoutUpdateEventTimer;
+    Timer<RenderNamedFlowThread> m_regionOversetChangeEventTimer;
 };
 
 inline RenderNamedFlowThread* toRenderNamedFlowThread(RenderObject* object)
diff --git a/Source/core/rendering/RenderObject.cpp b/Source/core/rendering/RenderObject.cpp
index da52773..a08b09e 100644
--- a/Source/core/rendering/RenderObject.cpp
+++ b/Source/core/rendering/RenderObject.cpp
@@ -1150,7 +1150,7 @@
     int outlineOffset = styleToUse->outlineOffset();
 
     if (styleToUse->outlineStyleIsAuto() || hasOutlineAnnotation()) {
-        if (!theme()->supportsFocusRing(styleToUse)) {
+        if (theme()->shouldDrawDefaultFocusRing(this)) {
             // Only paint the focus ring by hand if the theme isn't able to draw the focus ring.
             paintFocusRing(paintInfo, paintRect.location(), styleToUse);
         }
@@ -1643,10 +1643,15 @@
 
 #endif // NDEBUG
 
+static bool shouldUseSelectionColor(const RenderStyle& style)
+{
+    return style.userSelect() != SELECT_NONE || style.userModify() != READ_ONLY;
+}
+
 Color RenderObject::selectionBackgroundColor() const
 {
     Color color;
-    if (style()->userSelect() != SELECT_NONE) {
+    if (shouldUseSelectionColor(*style())) {
         RefPtr<RenderStyle> pseudoStyle = getUncachedPseudoStyle(PseudoStyleRequest(SELECTION));
         if (pseudoStyle && pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).isValid())
             color = pseudoStyle->visitedDependentColor(CSSPropertyBackgroundColor).blendWithWhite();
@@ -1664,7 +1669,7 @@
     Color color;
     // If the element is unselectable, or we are only painting the selection,
     // don't override the foreground color with the selection foreground color.
-    if (style()->userSelect() == SELECT_NONE
+    if (!shouldUseSelectionColor(*style())
         || (frame()->view()->paintBehavior() & PaintBehaviorSelectionOnly))
         return color;
 
diff --git a/Source/core/rendering/RenderObject.h b/Source/core/rendering/RenderObject.h
index 8cc247b..3e12f3b 100644
--- a/Source/core/rendering/RenderObject.h
+++ b/Source/core/rendering/RenderObject.h
@@ -342,6 +342,7 @@
     virtual bool isMeter() const { return false; }
     virtual bool isProgress() const { return false; }
     virtual bool isRenderBlock() const { return false; }
+    virtual bool isRenderSVGBlock() const { return false; };
     virtual bool isRenderLazyBlock() const { return false; }
     virtual bool isRenderButton() const { return false; }
     virtual bool isRenderIFrame() const { return false; }
diff --git a/Source/core/rendering/RenderRegion.cpp b/Source/core/rendering/RenderRegion.cpp
index 5bb9041..c7cbc18 100644
--- a/Source/core/rendering/RenderRegion.cpp
+++ b/Source/core/rendering/RenderRegion.cpp
@@ -48,7 +48,6 @@
     , m_isValid(false)
     , m_hasCustomRegionStyle(false)
     , m_hasAutoLogicalHeight(false)
-    , m_regionState(RegionUndefined)
 {
 }
 
@@ -126,6 +125,26 @@
     return clipRect;
 }
 
+RegionOversetState RenderRegion::regionOversetState() const
+{
+    if (isValid() && element())
+        return element()->regionOversetState();
+
+    return RegionUndefined;
+}
+
+void RenderRegion::setRegionOversetState(RegionOversetState state)
+{
+    if (element())
+        element()->setRegionOversetState(state);
+}
+
+Element* RenderRegion::element() const
+{
+    ASSERT(node() && node()->isElementNode());
+    return toElement(node());
+}
+
 LayoutUnit RenderRegion::pageLogicalTopForOffset(LayoutUnit /* offset */) const
 {
     return flowThread()->isHorizontalWritingMode() ? flowThreadPortionRect().y() : flowThreadPortionRect().x();
diff --git a/Source/core/rendering/RenderRegion.h b/Source/core/rendering/RenderRegion.h
index d06df36..b9b562f 100644
--- a/Source/core/rendering/RenderRegion.h
+++ b/Source/core/rendering/RenderRegion.h
@@ -82,15 +82,10 @@
 
     void clearObjectStyleInRegion(const RenderObject*);
 
-    enum RegionState {
-        RegionUndefined,
-        RegionEmpty,
-        RegionFit,
-        RegionOverset
-    };
+    RegionOversetState regionOversetState() const;
+    void setRegionOversetState(RegionOversetState);
 
-    RegionState regionState() const { return isValid() ? m_regionState : RegionUndefined; }
-    void setRegionState(RegionState regionState) { m_regionState = regionState; }
+    Element* element() const;
     
     // These methods represent the width and height of a "page" and for a RenderRegion they are just the
     // content width and content height of a region. For RenderRegionSets, however, they will be the width and
@@ -197,7 +192,6 @@
     bool m_isValid : 1;
     bool m_hasCustomRegionStyle : 1;
     bool m_hasAutoLogicalHeight : 1;
-    RegionState m_regionState;
 };
 
 inline RenderRegion* toRenderRegion(RenderObject* object)
diff --git a/Source/core/rendering/RenderTableSection.cpp b/Source/core/rendering/RenderTableSection.cpp
index 025fb7e..3bcff2d 100644
--- a/Source/core/rendering/RenderTableSection.cpp
+++ b/Source/core/rendering/RenderTableSection.cpp
@@ -48,12 +48,10 @@
 static unsigned gMinTableSizeToUseFastPaintPathWithOverflowingCell = 75 * 75;
 static float gMaxAllowedOverflowingCellRatioForFastPaintPath = 0.1f;
 
-static inline void setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(RenderTableSection::RowStruct& row)
+static inline void setRowLogicalHeightToRowStyleLogicalHeight(RenderTableSection::RowStruct& row)
 {
     ASSERT(row.rowRenderer);
     row.logicalHeight = row.rowRenderer->style()->logicalHeight();
-    if (row.logicalHeight.isRelative())
-        row.logicalHeight = Length();
 }
 
 static inline void updateLogicalHeightForCell(RenderTableSection::RowStruct& row, const RenderTableCell* cell)
@@ -63,7 +61,7 @@
         return;
 
     Length logicalHeight = cell->style()->logicalHeight();
-    if (logicalHeight.isPositive() || (logicalHeight.isRelative() && logicalHeight.value() >= 0)) {
+    if (logicalHeight.isPositive()) {
         Length cRowLogicalHeight = row.logicalHeight;
         switch (logicalHeight.type()) {
         case Percent:
@@ -76,7 +74,6 @@
                 || (cRowLogicalHeight.isFixed() && cRowLogicalHeight.value() < logicalHeight.value()))
                 row.logicalHeight = logicalHeight;
             break;
-        case Relative:
         default:
             break;
         }
@@ -174,7 +171,7 @@
     row->setRowIndex(insertionRow);
 
     if (!beforeChild)
-        setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(m_grid[insertionRow]);
+        setRowLogicalHeightToRowStyleLogicalHeight(m_grid[insertionRow]);
 
     if (beforeChild && beforeChild->parent() != this)
         beforeChild = splitAnonymousBoxesAroundChild(beforeChild);
@@ -255,6 +252,79 @@
     cell->setCol(table()->effColToCol(col));
 }
 
+// Distribute rowSpan cell height in rows those comes in rowSpan cell based on the ratio of row's height if
+// 1. RowSpan cell height is greater then the total height of rows in rowSpan cell
+void RenderTableSection::distributeRowSpanHeightToRows(SpanningRenderTableCells& rowSpanCells)
+{
+    ASSERT(rowSpanCells.size());
+
+    // FIXME: For now, we handle the first rowspan cell in the table but this is wrong.
+    RenderTableCell* cell = rowSpanCells[0];
+
+    unsigned rowSpan = cell->rowSpan();
+    unsigned rowIndex = cell->rowIndex();
+    int initialPos = m_rowPos[rowIndex + rowSpan];
+
+    int totalRowsHeight = 0;
+    int rowSpanCellHeight = cell->logicalHeightForRowSizing();
+    Vector<int> rowsHeight(rowSpan);
+
+    // Getting height of rows in current rowSpan cell, getting total height of rows and adjusting rowSpan cell height with border spacing.
+    for (unsigned row = 0; row < rowSpan; row++) {
+        unsigned actualRow = row + rowIndex;
+        rowsHeight[row] = m_rowPos[actualRow + 1] - m_rowPos[actualRow] - borderSpacingForRow(actualRow);
+        totalRowsHeight += rowsHeight[row];
+        rowSpanCellHeight -= borderSpacingForRow(actualRow);
+    }
+    rowSpanCellHeight += borderSpacingForRow(rowIndex + rowSpan - 1);
+
+    if (!totalRowsHeight || rowSpanCellHeight <= totalRowsHeight)
+        return;
+
+    // Recalculating the height of rows based on rowSpan cell height if rowSpan cell height is more than total height of rows.
+    int remainingHeight = rowSpanCellHeight;
+
+    for (unsigned row = rowIndex; row < (rowIndex + rowSpan); row++) {
+        int rowHeight = (rowSpanCellHeight * rowsHeight[row - rowIndex]) / totalRowsHeight;
+        remainingHeight -= rowHeight;
+        m_rowPos[row + 1] = m_rowPos[row] + rowHeight + borderSpacingForRow(row);
+    }
+    // Remaining height added in the last row under rowSpan cell
+    m_rowPos[rowIndex + rowSpan] += remainingHeight;
+
+    // Getting total changed height in the table
+    unsigned changedHeight = changedHeight = m_rowPos[rowIndex + rowSpan] - initialPos;
+
+    if (changedHeight) {
+        unsigned totalRows = m_grid.size();
+
+        // Apply changed height by rowSpan cells to rows present at the end of the table
+        for (unsigned row = rowIndex + rowSpan + 1; row <= totalRows; row++)
+            m_rowPos[row] += changedHeight;
+    }
+}
+
+// Find out the baseline of the cell
+// If the cell's baseline is more then the row's baseline then the cell's baseline become the row's baseline
+// and if the row's baseline goes out of the row's boundries then adjust row height accordingly.
+void RenderTableSection::updateBaselineForCell(RenderTableCell* cell, unsigned row, LayoutUnit& baselineDescent)
+{
+    if (!cell->isBaselineAligned())
+        return;
+
+    LayoutUnit baselinePosition = cell->cellBaselinePosition();
+    if (baselinePosition > cell->borderBefore() + cell->paddingBefore()) {
+        m_grid[row].baseline = max(m_grid[row].baseline, baselinePosition);
+
+        int cellStartRowBaselineDescent = 0;
+        if (cell->rowSpan() == 1) {
+            baselineDescent = max(baselineDescent, cell->logicalHeightForRowSizing() - (baselinePosition - cell->intrinsicPaddingBefore()));
+            cellStartRowBaselineDescent = baselineDescent;
+        }
+        m_rowPos[row + 1] = max<int>(m_rowPos[row + 1], m_rowPos[row] + m_grid[row].baseline + cellStartRowBaselineDescent);
+    }
+}
+
 int RenderTableSection::calcRowLogicalHeight()
 {
 #ifndef NDEBUG
@@ -264,14 +334,14 @@
     ASSERT(!needsLayout());
 
     RenderTableCell* cell;
-
-    int spacing = table()->vBorderSpacing();
     
     RenderView* viewRenderer = view();
     LayoutStateMaintainer statePusher(viewRenderer);
 
     m_rowPos.resize(m_grid.size() + 1);
-    m_rowPos[0] = spacing;
+    m_rowPos[0] = table()->vBorderSpacing();
+
+    SpanningRenderTableCells rowSpanCells;
 
     for (unsigned r = 0; r < m_grid.size(); r++) {
         m_grid[r].baseline = 0;
@@ -290,13 +360,18 @@
                 if (current.inColSpan && cell->rowSpan() == 1)
                     continue;
 
-                // FIXME: We are always adding the height of a rowspan to the last rows which doesn't match
-                // other browsers. See webkit.org/b/52185 for example.
-                if ((cell->rowIndex() + cell->rowSpan() - 1) != r)
-                    continue;
+                if (cell->rowSpan() > 1) {
+                    // For row spanning cells, we only handle them for the first row they span. This ensures we take their baseline into account.
+                    if (cell->rowIndex() == r) {
+                        rowSpanCells.append(cell);
 
-                // For row spanning cells, |r| is the last row in the span.
-                unsigned cellStartRow = cell->rowIndex();
+                        // Find out the baseline. The baseline is set on the first row in a rowSpan.
+                        updateBaselineForCell(cell, r, baselineDescent);
+                    }
+                    continue;
+                }
+
+                ASSERT(cell->rowSpan() == 1);
 
                 if (cell->hasOverrideHeight()) {
                     if (!statePusher.didPush()) {
@@ -310,33 +385,21 @@
                     cell->layoutIfNeeded();
                 }
 
-                int cellLogicalHeight = cell->logicalHeightForRowSizing();
-                m_rowPos[r + 1] = max(m_rowPos[r + 1], m_rowPos[cellStartRow] + cellLogicalHeight);
+                m_rowPos[r + 1] = max(m_rowPos[r + 1], m_rowPos[r] + cell->logicalHeightForRowSizing());
 
-                // Find out the baseline. The baseline is set on the first row in a rowspan.
-                if (cell->isBaselineAligned()) {
-                    LayoutUnit baselinePosition = cell->cellBaselinePosition();
-                    if (baselinePosition > cell->borderBefore() + cell->paddingBefore()) {
-                        m_grid[cellStartRow].baseline = max(m_grid[cellStartRow].baseline, baselinePosition);
-                        // The descent of a cell that spans multiple rows does not affect the height of the first row it spans, so don't let it
-                        // become the baseline descent applied to the rest of the row. Also we don't account for the baseline descent of
-                        // non-spanning cells when computing a spanning cell's extent.
-                        int cellStartRowBaselineDescent = 0;
-                        if (cell->rowSpan() == 1) {
-                            baselineDescent = max(baselineDescent, cellLogicalHeight - (baselinePosition - cell->intrinsicPaddingBefore()));
-                            cellStartRowBaselineDescent = baselineDescent;
-                        }
-                        m_rowPos[cellStartRow + 1] = max<int>(m_rowPos[cellStartRow + 1], m_rowPos[cellStartRow] + m_grid[cellStartRow].baseline + cellStartRowBaselineDescent);
-                    }
-                }
+                // Find out the baseline.
+                updateBaselineForCell(cell, r, baselineDescent);
             }
         }
 
         // Add the border-spacing to our final position.
-        m_rowPos[r + 1] += m_grid[r].rowRenderer ? spacing : 0;
+        m_rowPos[r + 1] += borderSpacingForRow(r);
         m_rowPos[r + 1] = max(m_rowPos[r + 1], m_rowPos[r]);
     }
 
+    if (!rowSpanCells.isEmpty())
+        distributeRowSpanHeightToRows(rowSpanCells);
+
     ASSERT(!needsLayout());
 
     statePusher.pop();
@@ -1211,7 +1274,7 @@
             RenderTableRow* tableRow = toRenderTableRow(row);
             m_grid[insertionRow].rowRenderer = tableRow;
             tableRow->setRowIndex(insertionRow);
-            setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(m_grid[insertionRow]);
+            setRowLogicalHeightToRowStyleLogicalHeight(m_grid[insertionRow]);
 
             for (RenderObject* cell = row->firstChild(); cell; cell = cell->nextSibling()) {
                 if (!cell->isTableCell())
@@ -1233,7 +1296,7 @@
     if (needsCellRecalc())
         return;
 
-    setRowLogicalHeightToRowStyleLogicalHeightIfNotRelative(m_grid[rowIndex]);
+    setRowLogicalHeightToRowStyleLogicalHeight(m_grid[rowIndex]);
 
     for (RenderObject* cell = m_grid[rowIndex].rowRenderer->firstChild(); cell; cell = cell->nextSibling()) {
         if (!cell->isTableCell())
diff --git a/Source/core/rendering/RenderTableSection.h b/Source/core/rendering/RenderTableSection.h
index 0a0cca3..41c2359 100644
--- a/Source/core/rendering/RenderTableSection.h
+++ b/Source/core/rendering/RenderTableSection.h
@@ -83,6 +83,8 @@
 
     RenderTable* table() const { return toRenderTable(parent()); }
 
+    typedef Vector<RenderTableCell*, 2> SpanningRenderTableCells;
+
     struct CellStruct {
         Vector<RenderTableCell*, 1> cells; 
         bool inColSpan; // true for columns after the first in a colspan
@@ -226,12 +228,18 @@
 
     virtual bool nodeAtPoint(const HitTestRequest&, HitTestResult&, const HitTestLocation& locationInContainer, const LayoutPoint& accumulatedOffset, HitTestAction) OVERRIDE;
 
+    int borderSpacingForRow(unsigned row) const { return m_grid[row].rowRenderer ? table()->vBorderSpacing() : 0; }
+
     void ensureRows(unsigned);
 
+    void distributeRowSpanHeightToRows(SpanningRenderTableCells& rowSpanCells);
+
     void distributeExtraLogicalHeightToPercentRows(int& extraLogicalHeight, int totalPercent);
     void distributeExtraLogicalHeightToAutoRows(int& extraLogicalHeight, unsigned autoRowsCount);
     void distributeRemainingExtraLogicalHeight(int& extraLogicalHeight);
 
+    void updateBaselineForCell(RenderTableCell*, unsigned row, LayoutUnit& baselineDescent);
+
     bool hasOverflowingCell() const { return m_overflowingCells.size() || m_forceSlowPaintPathWithOverflowingCell; }
     void computeOverflowFromCells(unsigned totalRows, unsigned nEffCols);
 
diff --git a/Source/core/rendering/RenderText.cpp b/Source/core/rendering/RenderText.cpp
index 5c2ff91..acf1042 100644
--- a/Source/core/rendering/RenderText.cpp
+++ b/Source/core/rendering/RenderText.cpp
@@ -141,8 +141,8 @@
     , m_needsTranscoding(false)
     , m_minWidth(-1)
     , m_maxWidth(-1)
-    , m_beginMinWidth(0)
-    , m_endMinWidth(0)
+    , m_firstLineMinWidth(0)
+    , m_lastLineLineMinWidth(0)
     , m_text(str)
     , m_firstTextBox(0)
     , m_lastTextBox(0)
@@ -768,11 +768,11 @@
 }
 
 void RenderText::trimmedPrefWidths(float leadWidth,
-                                   float& beginMinW, bool& beginWS,
-                                   float& endMinW, bool& endWS,
-                                   bool& hasBreakableChar, bool& hasBreak,
-                                   float& beginMaxW, float& endMaxW,
-                                   float& minW, float& maxW, bool& stripFrontSpaces)
+    float& firstLineMinWidth, bool& hasBreakableStart,
+    float& lastLineMinWidth, bool& hasBreakableEnd,
+    bool& hasBreakableChar, bool& hasBreak,
+    float& firstLineMaxWidth, float& lastLineMaxWidth,
+    float& minWidth, float& maxWidth, bool& stripFrontSpaces)
 {
     bool collapseWhiteSpace = style()->collapseWhiteSpace();
     if (!collapseWhiteSpace)
@@ -781,27 +781,27 @@
     if (m_hasTab || preferredLogicalWidthsDirty())
         computePreferredLogicalWidths(leadWidth);
 
-    beginWS = !stripFrontSpaces && m_hasBeginWS;
-    endWS = m_hasEndWS;
+    hasBreakableStart = !stripFrontSpaces && m_hasBreakableStart;
+    hasBreakableEnd = m_hasBreakableEnd;
 
     int len = textLength();
 
     if (!len || (stripFrontSpaces && text()->containsOnlyWhitespace())) {
-        beginMinW = 0;
-        endMinW = 0;
-        beginMaxW = 0;
-        endMaxW = 0;
-        minW = 0;
-        maxW = 0;
+        firstLineMinWidth = 0;
+        lastLineMinWidth = 0;
+        firstLineMaxWidth = 0;
+        lastLineMaxWidth = 0;
+        minWidth = 0;
+        maxWidth = 0;
         hasBreak = false;
         return;
     }
 
-    minW = m_minWidth;
-    maxW = m_maxWidth;
+    minWidth = m_minWidth;
+    maxWidth = m_maxWidth;
 
-    beginMinW = m_beginMinWidth;
-    endMinW = m_endMinWidth;
+    firstLineMinWidth = m_firstLineMinWidth;
+    lastLineMinWidth = m_lastLineLineMinWidth;
 
     hasBreakableChar = m_hasBreakableChar;
     hasBreak = m_hasBreak;
@@ -813,45 +813,47 @@
         if (stripFrontSpaces) {
             const UChar space = ' ';
             float spaceWidth = font.width(RenderBlock::constructTextRun(this, font, &space, 1, style()));
-            maxW -= spaceWidth;
-        } else
-            maxW += font.wordSpacing();
+            maxWidth -= spaceWidth;
+        } else {
+            maxWidth += font.wordSpacing();
+        }
     }
 
-    stripFrontSpaces = collapseWhiteSpace && m_hasEndWS;
+    stripFrontSpaces = collapseWhiteSpace && m_hasEndWhiteSpace;
 
-    if (!style()->autoWrap() || minW > maxW)
-        minW = maxW;
+    if (!style()->autoWrap() || minWidth > maxWidth)
+        minWidth = maxWidth;
 
     // Compute our max widths by scanning the string for newlines.
     if (hasBreak) {
         const Font& f = style()->font(); // FIXME: This ignores first-line.
         bool firstLine = true;
-        beginMaxW = maxW;
-        endMaxW = maxW;
+        firstLineMaxWidth = maxWidth;
+        lastLineMaxWidth = maxWidth;
         for (int i = 0; i < len; i++) {
             int linelen = 0;
             while (i + linelen < len && text[i + linelen] != '\n')
                 linelen++;
 
             if (linelen) {
-                endMaxW = widthFromCache(f, i, linelen, leadWidth + endMaxW, 0, 0);
+                lastLineMaxWidth = widthFromCache(f, i, linelen, leadWidth + lastLineMaxWidth, 0, 0);
                 if (firstLine) {
                     firstLine = false;
                     leadWidth = 0;
-                    beginMaxW = endMaxW;
+                    firstLineMaxWidth = lastLineMaxWidth;
                 }
                 i += linelen;
             } else if (firstLine) {
-                beginMaxW = 0;
+                firstLineMaxWidth = 0;
                 firstLine = false;
                 leadWidth = 0;
             }
 
-            if (i == len - 1)
+            if (i == len - 1) {
                 // A <pre> run that ends with a newline, as in, e.g.,
                 // <pre>Some text\n\n<span>More text</pre>
-                endMaxW = 0;
+                lastLineMaxWidth = 0;
+            }
         }
     }
 }
@@ -932,9 +934,9 @@
     ASSERT(m_hasTab || preferredLogicalWidthsDirty() || !m_knownToHaveNoOverflowAndNoFallbackFonts);
 
     m_minWidth = 0;
-    m_beginMinWidth = 0;
-    m_endMinWidth = 0;
     m_maxWidth = 0;
+    m_firstLineMinWidth = 0;
+    m_lastLineLineMinWidth = 0;
 
     if (isBR())
         return;
@@ -944,8 +946,9 @@
     m_hasBreakableChar = false;
     m_hasBreak = false;
     m_hasTab = false;
-    m_hasBeginWS = false;
-    m_hasEndWS = false;
+    m_hasBreakableStart = false;
+    m_hasBreakableEnd = false;
+    m_hasEndWhiteSpace = false;
 
     RenderStyle* styleToUse = style();
     const Font& f = styleToUse->font(); // FIXME: This ignores first-line.
@@ -1008,10 +1011,13 @@
         } else
             isSpace = c == ' ';
 
-        if ((isSpace || isNewline) && !i)
-            m_hasBeginWS = true;
-        if ((isSpace || isNewline) && i == len - 1)
-            m_hasEndWS = true;
+        bool isBreakableLocation = isNewline || (isSpace && styleToUse->autoWrap());
+        if (!i)
+            m_hasBreakableStart = isBreakableLocation;
+        if (i == len - 1) {
+            m_hasBreakableEnd = isBreakableLocation;
+            m_hasEndWhiteSpace = isNewline || isSpace;
+        }
 
         if (!ignoringSpaces && styleToUse->collapseWhiteSpace() && previousCharacterIsSpace && isSpace)
             ignoringSpaces = true;
@@ -1106,9 +1112,9 @@
                 // being appended to a previous text run when considering the total minimum width of the containing block.
                 if (hasBreak)
                     m_hasBreakableChar = true;
-                m_beginMinWidth = hasBreak ? 0 : currMinWidth;
+                m_firstLineMinWidth = hasBreak ? 0 : currMinWidth;
             }
-            m_endMinWidth = currMinWidth;
+            m_lastLineLineMinWidth = currMinWidth;
 
             if (currMinWidth > m_minWidth)
                 m_minWidth = currMinWidth;
@@ -1130,7 +1136,7 @@
                     firstLine = false;
                     leadWidth = 0;
                     if (!styleToUse->autoWrap())
-                        m_beginMinWidth = currMaxWidth;
+                        m_firstLineMinWidth = currMaxWidth;
                 }
 
                 if (currMaxWidth > m_maxWidth)
@@ -1166,8 +1172,8 @@
 
     if (styleToUse->whiteSpace() == PRE) {
         if (firstLine)
-            m_beginMinWidth = m_maxWidth;
-        m_endMinWidth = currMaxWidth;
+            m_firstLineMinWidth = m_maxWidth;
+        m_lastLineLineMinWidth = currMaxWidth;
     }
 
     setPreferredLogicalWidthsDirty(false);
diff --git a/Source/core/rendering/RenderText.h b/Source/core/rendering/RenderText.h
index 7dd5a83..0566d9c 100644
--- a/Source/core/rendering/RenderText.h
+++ b/Source/core/rendering/RenderText.h
@@ -72,7 +72,7 @@
     bool is8Bit() const { return m_text.is8Bit(); }
     const LChar* characters8() const { return m_text.impl()->characters8(); }
     const UChar* characters16() const { return m_text.impl()->characters16(); }
-    const UChar* characters() const { return m_text.characters(); }
+    const UChar* characters() const { return m_text.bloatedCharacters(); }
     UChar characterAt(unsigned) const;
     UChar uncheckedCharacterAt(unsigned) const;
     UChar operator[](unsigned i) const { return uncheckedCharacterAt(i); }
@@ -86,11 +86,11 @@
     float maxLogicalWidth() const;
 
     void trimmedPrefWidths(float leadWidth,
-                           float& beginMinW, bool& beginWS,
-                           float& endMinW, bool& endWS,
-                           bool& hasBreakableChar, bool& hasBreak,
-                           float& beginMaxW, float& endMaxW,
-                           float& minW, float& maxW, bool& stripFrontSpaces);
+        float& firstLineMinWidth, bool& hasBreakableStart,
+        float& lastLineMinWidth, bool& hasBreakableEnd,
+        bool& hasBreakableChar, bool& hasBreak,
+        float& firstLineMaxWidth, float& lastLineMaxWidth,
+        float& minWidth, float& maxWidth, bool& stripFrontSpaces);
 
     virtual IntRect linesBoundingBox() const;
     LayoutRect linesVisualOverflowBoundingBox() const;
@@ -181,8 +181,9 @@
     bool m_hasBreakableChar : 1; // Whether or not we can be broken into multiple lines.
     bool m_hasBreak : 1; // Whether or not we have a hard break (e.g., <pre> with '\n').
     bool m_hasTab : 1; // Whether or not we have a variable width tab character (e.g., <pre> with '\t').
-    bool m_hasBeginWS : 1; // Whether or not we begin with WS (only true if we aren't pre)
-    bool m_hasEndWS : 1; // Whether or not we end with WS (only true if we aren't pre)
+    bool m_hasBreakableStart : 1;
+    bool m_hasBreakableEnd : 1;
+    bool m_hasEndWhiteSpace : 1;
     bool m_linesDirty : 1; // This bit indicates that the text run has already dirtied specific
                            // line boxes, and this hint will enable layoutInlineChildren to avoid
                            // just dirtying everything when character data is modified (e.g., appended/inserted
@@ -195,8 +196,8 @@
     
     float m_minWidth;
     float m_maxWidth;
-    float m_beginMinWidth;
-    float m_endMinWidth;
+    float m_firstLineMinWidth;
+    float m_lastLineLineMinWidth;
 
     String m_text;
 
diff --git a/Source/core/rendering/RenderTheme.cpp b/Source/core/rendering/RenderTheme.cpp
index 143cf04..a8999b9 100644
--- a/Source/core/rendering/RenderTheme.cpp
+++ b/Source/core/rendering/RenderTheme.cpp
@@ -700,6 +700,22 @@
 #endif
 }
 
+bool RenderTheme::shouldDrawDefaultFocusRing(RenderObject* renderer) const
+{
+    if (supportsFocusRing(renderer->style()))
+        return false;
+    if (!renderer->style()->hasAppearance())
+        return true;
+    Node* node = renderer->node();
+    if (!node)
+        return true;
+    // We can't use RenderTheme::isFocused because outline:auto might be
+    // specified to non-:focus rulesets.
+    if (node->focused() && !node->shouldHaveFocusAppearance())
+        return false;
+    return true;
+}
+
 bool RenderTheme::supportsFocusRing(const RenderStyle* style) const
 {
     return (style->hasAppearance() && style->appearance() != TextFieldPart && style->appearance() != TextAreaPart && style->appearance() != MenulistButtonPart && style->appearance() != ListboxPart);
@@ -796,7 +812,7 @@
     node = node->focusDelegate();
     Document* document = node->document();
     Frame* frame = document->frame();
-    return node == document->focusedNode() && frame && frame->selection()->isFocusedAndActive();
+    return node == document->focusedNode() && node->shouldHaveFocusAppearance() && frame && frame->selection()->isFocusedAndActive();
 }
 
 bool RenderTheme::isPressed(const RenderObject* o) const
diff --git a/Source/core/rendering/RenderTheme.h b/Source/core/rendering/RenderTheme.h
index c39043f..f342c5a 100644
--- a/Source/core/rendering/RenderTheme.h
+++ b/Source/core/rendering/RenderTheme.h
@@ -119,8 +119,7 @@
     // old theme.
     virtual void themeChanged() { }
 
-    // A method asking if the theme is able to draw the focus ring.
-    virtual bool supportsFocusRing(const RenderStyle*) const;
+    bool shouldDrawDefaultFocusRing(RenderObject*) const;
 
     // A method asking if the theme's controls actually care about redrawing when hovered.
     virtual bool supportsHover(const RenderStyle*) const { return false; }
@@ -230,6 +229,8 @@
     virtual Color platformActiveListBoxSelectionForegroundColor() const;
     virtual Color platformInactiveListBoxSelectionForegroundColor() const;
 
+    // A method asking if the theme is able to draw the focus ring.
+    virtual bool supportsFocusRing(const RenderStyle*) const;
     virtual bool supportsSelectionForegroundColors() const { return true; }
     virtual bool supportsListBoxSelectionForegroundColors() const { return true; }
 
diff --git a/Source/core/rendering/RenderThemeChromiumAndroid.cpp b/Source/core/rendering/RenderThemeChromiumAndroid.cpp
index 40a7cbe..778d769 100644
--- a/Source/core/rendering/RenderThemeChromiumAndroid.cpp
+++ b/Source/core/rendering/RenderThemeChromiumAndroid.cpp
@@ -60,7 +60,7 @@
 Color RenderThemeChromiumAndroid::systemColor(CSSValueID cssValueId) const
 {
     if (isRunningLayoutTest() && cssValueId == CSSValueButtonface) {
-        // Match Chromium Linux' button color in layout tests.
+        // Match Linux button color in layout tests.
         static const Color linuxButtonGrayColor(0xffdddddd);
         return linuxButtonGrayColor;
     }
@@ -81,7 +81,7 @@
 void RenderThemeChromiumAndroid::adjustInnerSpinButtonStyle(RenderStyle* style, Element*) const
 {
     if (isRunningLayoutTest()) {
-        // Match Chromium Linux spin button style in layout tests.
+        // Match Linux spin button style in layout tests.
         // FIXME: Consider removing the conditional if a future Android theme matches this.
         IntSize size = WebKit::Platform::current()->themeEngine()->getSize(WebKit::WebThemeEngine::PartInnerSpinButton);
 
diff --git a/Source/core/rendering/RenderThemeChromiumMac.h b/Source/core/rendering/RenderThemeChromiumMac.h
index f44ecb2..6fbfe5d 100644
--- a/Source/core/rendering/RenderThemeChromiumMac.h
+++ b/Source/core/rendering/RenderThemeChromiumMac.h
@@ -166,8 +166,6 @@
     NSPopUpButtonCell* popupButton() const;
     NSSearchFieldCell* search() const;
     NSMenu* searchMenuTemplate() const;
-    NSSliderCell* sliderThumbHorizontal() const;
-    NSSliderCell* sliderThumbVertical() const;
     NSTextFieldCell* textField() const;
 
     NSLevelIndicatorStyle levelIndicatorStyleFor(ControlPart) const;
@@ -212,14 +210,9 @@
     mutable RetainPtr<NSPopUpButtonCell> m_popupButton;
     mutable RetainPtr<NSSearchFieldCell> m_search;
     mutable RetainPtr<NSMenu> m_searchMenuTemplate;
-    mutable RetainPtr<NSSliderCell> m_sliderThumbHorizontal;
-    mutable RetainPtr<NSSliderCell> m_sliderThumbVertical;
     mutable RetainPtr<NSLevelIndicatorCell> m_levelIndicator;
     mutable RetainPtr<NSTextFieldCell> m_textField;
 
-    bool m_isSliderThumbHorizontalPressed;
-    bool m_isSliderThumbVerticalPressed;
-
     mutable HashMap<int, RGBA32> m_systemColorCache;
 
     RetainPtr<WebCoreRenderThemeNotificationObserver> m_notificationObserver;
diff --git a/Source/core/rendering/RenderThemeChromiumMac.mm b/Source/core/rendering/RenderThemeChromiumMac.mm
index d199579..38f3e24 100644
--- a/Source/core/rendering/RenderThemeChromiumMac.mm
+++ b/Source/core/rendering/RenderThemeChromiumMac.mm
@@ -58,6 +58,7 @@
 #import "core/rendering/RenderSlider.h"
 #import "core/rendering/RenderView.h"
 
+#import <AvailabilityMacros.h>
 #import <Carbon/Carbon.h>
 #import <Cocoa/Cocoa.h>
 #import <math.h>
@@ -169,9 +170,7 @@
 };
 
 RenderThemeChromiumMac::RenderThemeChromiumMac()
-    : m_isSliderThumbHorizontalPressed(false)
-    , m_isSliderThumbVerticalPressed(false)
-    , m_notificationObserver(AdoptNS, [[WebCoreRenderThemeNotificationObserver alloc] initWithTheme:this])
+    : m_notificationObserver(AdoptNS, [[WebCoreRenderThemeNotificationObserver alloc] initWithTheme:this])
 {
     [[NSNotificationCenter defaultCenter] addObserver:m_notificationObserver.get()
                                                         selector:@selector(systemColorsDidChange:)
@@ -524,6 +523,8 @@
     return RenderTheme::isControlStyled(style, border, background, backgroundColor);
 }
 
+const int sliderThumbShadowBlur = 1;
+
 void RenderThemeChromiumMac::adjustRepaintRect(const RenderObject* o, IntRect& r)
 {
     ControlPart part = o->style()->appearance();
@@ -550,6 +551,8 @@
         size.setHeight(size.height() * zoomLevel);
         size.setWidth(r.width());
         r = inflateRect(r, size, popupButtonMargins(), zoomLevel);
+    } else if (part == SliderThumbHorizontalPart || part == SliderThumbVerticalPart) {
+        r.setHeight(r.height() + sliderThumbShadowBlur);
     }
 }
 
@@ -661,10 +664,10 @@
     return NSMiniControlSize;
 }
 
-// We don't use controlSizeForFont() for cancel buttons because it needs to fit
+// We don't use controlSizeForFont() for search field decorations because it needs to fit
 // into the search field. The font size will already be modified by
 // setFontFromControlSize() called on the search field.
-static NSControlSize cancelButtonControlSizeForFont(RenderStyle* style)
+static NSControlSize searchFieldControlSizeForFont(RenderStyle* style)
 {
     int fontSize = style->fontSize();
     if (fontSize >= 13)
@@ -737,7 +740,10 @@
 
 NSControlSize RenderThemeChromiumMac::controlSizeForSystemFont(RenderStyle* style) const
 {
-    int fontSize = style->fontSize();
+    float fontSize = style->fontSize();
+    float zoomLevel = style->effectiveZoom();
+    if (zoomLevel != 1)
+        fontSize /= zoomLevel;
     if (fontSize >= [NSFont systemFontSizeForControlSize:NSRegularControlSize])
         return NSRegularControlSize;
     if (fontSize >= [NSFont systemFontSizeForControlSize:NSSmallControlSize])
@@ -1153,16 +1159,6 @@
         outData[i] = (1.0f - a) * dark[i] + a * light[i];
 }
 
-static void TrackGradientInterpolate(void*, const CGFloat* inData, CGFloat* outData)
-{
-    static float dark[4] = { 0.0f, 0.0f, 0.0f, 0.678f };
-    static float light[4] = { 0.0f, 0.0f, 0.0f, 0.13f };
-    float a = inData[0];
-    int i = 0;
-    for (i = 0; i < 4; i++)
-        outData[i] = (1.0f - a) * dark[i] + a * light[i];
-}
-
 void RenderThemeChromiumMac::paintMenuListButtonGradients(RenderObject* o, const PaintInfo& paintInfo, const IntRect& r)
 {
     if (r.isEmpty())
@@ -1415,107 +1411,161 @@
     return sizeForSystemFont(style, menuListSizes()).width();
 }
 
-const int trackWidth = 5;
-const int trackRadius = 2;
+const int sliderTrackWidth = 5;
+const int sliderTrackBorderWidth = 1;
 
 bool RenderThemeChromiumMac::paintSliderTrack(RenderObject* o, const PaintInfo& paintInfo, const IntRect& r)
 {
-    IntRect bounds = r;
-    float zoomLevel = o->style()->effectiveZoom();
-    float zoomedTrackWidth = trackWidth * zoomLevel;
-
-    if (o->style()->appearance() ==  SliderHorizontalPart || o->style()->appearance() ==  MediaSliderPart) {
-        bounds.setHeight(zoomedTrackWidth);
-        bounds.setY(r.y() + r.height() / 2 - zoomedTrackWidth / 2);
-    } else if (o->style()->appearance() == SliderVerticalPart) {
-        bounds.setWidth(zoomedTrackWidth);
-        bounds.setX(r.x() + r.width() / 2 - zoomedTrackWidth / 2);
-    }
-
-    LocalCurrentGraphicsContext localContext(paintInfo.context);
-    CGContextRef context = localContext.cgContext();
-    CGColorSpaceRef cspace = deviceRGBColorSpaceRef();
-
     paintSliderTicks(o, paintInfo, r);
 
-    GraphicsContextStateSaver stateSaver(*paintInfo.context);
-    CGContextClipToRect(context, bounds);
+    float zoomLevel = o->style()->effectiveZoom();
+    FloatRect unzoomedRect = r;
 
-    struct CGFunctionCallbacks mainCallbacks = { 0, TrackGradientInterpolate, NULL };
-    RetainPtr<CGFunctionRef> mainFunction(AdoptCF, CGFunctionCreate(NULL, 1, NULL, 4, NULL, &mainCallbacks));
-    RetainPtr<CGShadingRef> mainShading;
-    if (o->style()->appearance() == SliderVerticalPart)
-        mainShading.adoptCF(CGShadingCreateAxial(cspace, CGPointMake(bounds.x(),  bounds.maxY()), CGPointMake(bounds.maxX(), bounds.maxY()), mainFunction.get(), false, false));
-    else
-        mainShading.adoptCF(CGShadingCreateAxial(cspace, CGPointMake(bounds.x(),  bounds.y()), CGPointMake(bounds.x(), bounds.maxY()), mainFunction.get(), false, false));
-
-    IntSize radius(trackRadius, trackRadius);
-    paintInfo.context->clipRoundedRect(RoundedRect(bounds, radius, radius, radius, radius));
-    context = localContext.cgContext();
-    CGContextDrawShading(context, mainShading.get());
-
-    return false;
-}
-
-const float verticalSliderHeightPadding = 0.1f;
-
-bool RenderThemeChromiumMac::paintSliderThumb(RenderObject* o, const PaintInfo& paintInfo, const IntRect& r)
-{
-    NSSliderCell* sliderThumbCell = o->style()->appearance() == SliderThumbVerticalPart
-        ? sliderThumbVertical()
-        : sliderThumbHorizontal();
-
-    LocalCurrentGraphicsContext localContext(paintInfo.context);
-
-    // Update the various states we respond to.
-    updateActiveState(sliderThumbCell, o);
-    updateEnabledState(sliderThumbCell, o);
-    updateFocusedState(sliderThumbCell, (o->node() && o->node()->focusDelegate()->renderer()) ? o->node()->focusDelegate()->renderer() : o);
-
-    // Update the pressed state using the NSCell tracking methods, since that's how NSSliderCell keeps track of it.
-    bool oldPressed;
-    if (o->style()->appearance() == SliderThumbVerticalPart)
-        oldPressed = m_isSliderThumbVerticalPressed;
-    else
-        oldPressed = m_isSliderThumbHorizontalPressed;
-
-    bool pressed = isPressed(o);
-
-    if (o->style()->appearance() == SliderThumbVerticalPart)
-        m_isSliderThumbVerticalPressed = pressed;
-    else
-        m_isSliderThumbHorizontalPressed = pressed;
-
-    if (pressed != oldPressed) {
-        if (pressed)
-            [sliderThumbCell startTrackingAt:NSPoint() inView:nil];
-        else
-            [sliderThumbCell stopTracking:NSPoint() at:NSPoint() inView:nil mouseIsUp:YES];
+    if (o->style()->appearance() ==  SliderHorizontalPart || o->style()->appearance() ==  MediaSliderPart) {
+        unzoomedRect.setY(ceilf(unzoomedRect.y() + unzoomedRect.height() / 2 - zoomLevel * sliderTrackWidth / 2));
+        unzoomedRect.setHeight(zoomLevel * sliderTrackWidth);
+    } else if (o->style()->appearance() == SliderVerticalPart) {
+        unzoomedRect.setX(ceilf(unzoomedRect.x() + unzoomedRect.width() / 2 - zoomLevel * sliderTrackWidth / 2));
+        unzoomedRect.setWidth(zoomLevel * sliderTrackWidth);
     }
 
-    FloatRect bounds = r;
-    // Make the height of the vertical slider slightly larger so NSSliderCell will draw a vertical slider.
-    if (o->style()->appearance() == SliderThumbVerticalPart)
-        bounds.setHeight(bounds.height() + verticalSliderHeightPadding * o->style()->effectiveZoom());
-
-    GraphicsContextStateSaver stateSaver(*paintInfo.context);
-    float zoomLevel = o->style()->effectiveZoom();
-
-    FloatRect unzoomedRect = bounds;
-    if (zoomLevel != 1.0f) {
+    if (zoomLevel != 1) {
         unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
         unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
+    }
+
+    GraphicsContextStateSaver stateSaver(*paintInfo.context);
+    if (zoomLevel != 1) {
         paintInfo.context->translate(unzoomedRect.x(), unzoomedRect.y());
         paintInfo.context->scale(FloatSize(zoomLevel, zoomLevel));
         paintInfo.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
     }
 
-    paintInfo.context->translate(0, unzoomedRect.y());
-    paintInfo.context->scale(FloatSize(1, -1));
-    paintInfo.context->translate(0, -(unzoomedRect.y() + unzoomedRect.height()));
+    Color fillColor(205, 205, 205);
+    Color borderGradientTopColor(109, 109, 109);
+    Color borderGradientBottomColor(181, 181, 181);
+    Color shadowColor(0, 0, 0, 118);
 
-    [sliderThumbCell drawInteriorWithFrame:unzoomedRect inView:documentViewFor(o)];
-    [sliderThumbCell setControlView:nil];
+    if (!isEnabled(o)) {
+        Color tintColor(255, 255, 255, 128);
+        fillColor = fillColor.blend(tintColor);
+        borderGradientTopColor = borderGradientTopColor.blend(tintColor);
+        borderGradientBottomColor = borderGradientBottomColor.blend(tintColor);
+        shadowColor = shadowColor.blend(tintColor);
+    }
+
+    Color tintColor;
+    if (!isEnabled(o))
+        tintColor = Color(255, 255, 255, 128);
+
+    bool isVerticalSlider = o->style()->appearance() == SliderVerticalPart;
+
+    int fillRadiusSize = (sliderTrackWidth - sliderTrackBorderWidth) / 2;
+    IntSize fillRadius(fillRadiusSize, fillRadiusSize);
+    IntRect fillBounds = enclosedIntRect(unzoomedRect);
+    RoundedRect fillRect(fillBounds, fillRadius, fillRadius, fillRadius, fillRadius);
+    paintInfo.context->fillRoundedRect(fillRect, fillColor);
+
+    IntSize shadowOffset(isVerticalSlider ? 1 : 0,
+                         isVerticalSlider ? 0 : 1);
+    int shadowBlur = 3;
+    int shadowSpread = 0;
+    paintInfo.context->save();
+    paintInfo.context->drawInnerShadow(fillRect, shadowColor, shadowOffset, shadowBlur, shadowSpread);
+    paintInfo.context->restore();
+
+    RefPtr<Gradient> borderGradient = Gradient::create(fillBounds.minXMinYCorner(),
+        isVerticalSlider ? fillBounds.maxXMinYCorner() : fillBounds.minXMaxYCorner());
+    borderGradient->addColorStop(0.0, borderGradientTopColor);
+    borderGradient->addColorStop(1.0, borderGradientBottomColor);
+    Path borderPath;
+    FloatRect borderRect(unzoomedRect);
+    borderRect.inflate(-sliderTrackBorderWidth / 2.0);
+    float borderRadiusSize = (isVerticalSlider ? borderRect.width() : borderRect.height()) / 2;
+    FloatSize borderRadius(borderRadiusSize, borderRadiusSize);
+    borderPath.addRoundedRect(borderRect, borderRadius, borderRadius, borderRadius, borderRadius);
+    paintInfo.context->setStrokeGradient(borderGradient);
+    paintInfo.context->setStrokeThickness(sliderTrackBorderWidth);
+    paintInfo.context->strokePath(borderPath);
+    return false;
+}
+
+const int sliderThumbWidth = 15;
+const int sliderThumbHeight = 15;
+const int sliderThumbBorderWidth = 1;
+
+bool RenderThemeChromiumMac::paintSliderThumb(RenderObject* o, const PaintInfo& paintInfo, const IntRect& r)
+{
+    GraphicsContextStateSaver stateSaver(*paintInfo.context);
+    float zoomLevel = o->style()->effectiveZoom();
+
+    FloatRect unzoomedRect(r.x(), r.y(), sliderThumbWidth, sliderThumbHeight);
+    if (zoomLevel != 1.0f) {
+        paintInfo.context->translate(unzoomedRect.x(), unzoomedRect.y());
+        paintInfo.context->scale(FloatSize(zoomLevel, zoomLevel));
+        paintInfo.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
+    }
+
+    Color fillGradientTopColor(250, 250, 250);
+    Color fillGradientUpperMiddleColor(244, 244, 244);
+    Color fillGradientLowerMiddleColor(236, 236, 236);
+    Color fillGradientBottomColor(238, 238, 238);
+    Color borderGradientTopColor(151, 151, 151);
+    Color borderGradientBottomColor(128, 128, 128);
+    Color shadowColor(0, 0, 0, 36);
+
+    if (!isEnabled(o)) {
+        Color tintColor(255, 255, 255, 128);
+        fillGradientTopColor = fillGradientTopColor.blend(tintColor);
+        fillGradientUpperMiddleColor = fillGradientUpperMiddleColor.blend(tintColor);
+        fillGradientLowerMiddleColor = fillGradientLowerMiddleColor.blend(tintColor);
+        fillGradientBottomColor = fillGradientBottomColor.blend(tintColor);
+        borderGradientTopColor = borderGradientTopColor.blend(tintColor);
+        borderGradientBottomColor = borderGradientBottomColor.blend(tintColor);
+        shadowColor = shadowColor.blend(tintColor);
+    } else if (isPressed(o)) {
+        Color tintColor(0, 0, 0, 32);
+        fillGradientTopColor = fillGradientTopColor.blend(tintColor);
+        fillGradientUpperMiddleColor = fillGradientUpperMiddleColor.blend(tintColor);
+        fillGradientLowerMiddleColor = fillGradientLowerMiddleColor.blend(tintColor);
+        fillGradientBottomColor = fillGradientBottomColor.blend(tintColor);
+        borderGradientTopColor = borderGradientTopColor.blend(tintColor);
+        borderGradientBottomColor = borderGradientBottomColor.blend(tintColor);
+        shadowColor = shadowColor.blend(tintColor);
+    }
+
+    FloatRect borderBounds = unzoomedRect;
+    borderBounds.inflate(sliderThumbBorderWidth / 2.0);
+
+    FloatRect shadowBounds = unzoomedRect;
+    borderBounds.inflate(-sliderThumbBorderWidth);
+    FloatSize shadowOffset(0, 1);
+    paintInfo.context->setShadow(shadowOffset, sliderThumbShadowBlur, shadowColor);
+    paintInfo.context->setFillColor(Color::black);
+    paintInfo.context->fillEllipse(borderBounds);
+    paintInfo.context->clearShadow();
+
+    IntRect fillBounds = enclosedIntRect(unzoomedRect);
+    RefPtr<Gradient> fillGradient = Gradient::create(fillBounds.minXMinYCorner(), fillBounds.minXMaxYCorner());
+    fillGradient->addColorStop(0.0, fillGradientTopColor);
+    fillGradient->addColorStop(0.52, fillGradientUpperMiddleColor);
+    fillGradient->addColorStop(0.52, fillGradientLowerMiddleColor);
+    fillGradient->addColorStop(1.0, fillGradientBottomColor);
+    paintInfo.context->setFillGradient(fillGradient);
+    paintInfo.context->fillEllipse(borderBounds);
+
+    RefPtr<Gradient> borderGradient = Gradient::create(fillBounds.minXMinYCorner(), fillBounds.minXMaxYCorner());
+    borderGradient->addColorStop(0.0, borderGradientTopColor);
+    borderGradient->addColorStop(1.0, borderGradientBottomColor);
+    paintInfo.context->setStrokeGradient(borderGradient);
+    paintInfo.context->setStrokeThickness(sliderThumbBorderWidth);
+    paintInfo.context->strokeEllipse(borderBounds);
+
+    if (isFocused(o)) {
+        Path borderPath;
+        borderPath.addEllipse(borderBounds);
+        paintInfo.context->drawFocusRing(borderPath, 5, -2, focusRingColor());
+    }
 
     return false;
 }
@@ -1526,7 +1576,7 @@
 
     NSSearchFieldCell* search = this->search();
     setSearchCellState(o, r);
-    [search setControlSize:controlSizeForFont(o->style())];
+    [search setControlSize:searchFieldControlSizeForFont(o->style())];
 
     GraphicsContextStateSaver stateSaver(*paintInfo.context);
 
@@ -1565,7 +1615,13 @@
 
 const IntSize* RenderThemeChromiumMac::searchFieldSizes() const
 {
-    static const IntSize sizes[3] = { IntSize(0, 22), IntSize(0, 19), IntSize(0, 17) };
+    static const IntSize sizes[3] = { IntSize(0, 22), IntSize(0, 19), IntSize(0, 15) };
+    return sizes;
+}
+
+static const int* searchFieldHorizontalPaddings()
+{
+    static const int sizes[3] = { 3, 2, 1 };
     return sizes;
 }
 
@@ -1579,11 +1635,12 @@
     setSizeFromFont(style, searchFieldSizes());
 }
 
+const int searchFieldBorderWidth = 2;
 void RenderThemeChromiumMac::adjustSearchFieldStyle(RenderStyle* style, Element*) const
 {
     // Override border.
     style->resetBorder();
-    const short borderWidth = 2 * style->effectiveZoom();
+    const short borderWidth = searchFieldBorderWidth * style->effectiveZoom();
     style->setBorderLeftWidth(borderWidth);
     style->setBorderLeftStyle(INSET);
     style->setBorderRightWidth(borderWidth);
@@ -1597,14 +1654,16 @@
     style->setHeight(Length(Auto));
     setSearchFieldSize(style);
 
-    // Override padding size to match AppKit text positioning.
-    const int padding = 1 * style->effectiveZoom();
-    style->setPaddingLeft(Length(padding, Fixed));
-    style->setPaddingRight(Length(padding, Fixed));
-    style->setPaddingTop(Length(padding, Fixed));
-    style->setPaddingBottom(Length(padding, Fixed));
-
     NSControlSize controlSize = controlSizeForFont(style);
+
+    // Override padding size to match AppKit text positioning.
+    const int verticalPadding = 1 * style->effectiveZoom();
+    const int horizontalPadding = searchFieldHorizontalPaddings()[controlSize] * style->effectiveZoom();
+    style->setPaddingLeft(Length(horizontalPadding, Fixed));
+    style->setPaddingRight(Length(horizontalPadding, Fixed));
+    style->setPaddingTop(Length(verticalPadding, Fixed));
+    style->setPaddingBottom(Length(verticalPadding, Fixed));
+
     setFontFromControlSize(style, controlSize);
 
     style->setBoxShadow(nullptr);
@@ -1619,19 +1678,6 @@
     if (!input->renderer()->isBox())
         return false;
 
-    LocalCurrentGraphicsContext localContext(paintInfo.context);
-
-    NSSearchFieldCell* search = this->search();
-    setSearchCellState(input->renderer(), r);
-    [search setControlSize:cancelButtonControlSizeForFont(o->style())];
-
-    if (!input->isDisabledFormControl() && (input->isTextFormControl() && !toHTMLTextFormControlElement(input)->isReadOnly())) {
-        updateActiveState([search cancelButtonCell], o);
-        updatePressedState([search cancelButtonCell], o);
-    }
-    else if ([[search cancelButtonCell] isHighlighted])
-        [[search cancelButtonCell] setHighlighted:NO];
-
     GraphicsContextStateSaver stateSaver(*paintInfo.context);
 
     float zoomLevel = o->style()->effectiveZoom();
@@ -1644,14 +1690,43 @@
         paintInfo.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
     }
 
-    [[search cancelButtonCell] drawWithFrame:unzoomedRect inView:documentViewFor(o)];
-    [[search cancelButtonCell] setControlView:nil];
+    Color fillColor(200, 200, 200);
+
+    if (isPressed(o)) {
+        Color tintColor(0, 0, 0, 32);
+        fillColor = fillColor.blend(tintColor);
+    }
+
+    float centerX = unzoomedRect.x() + unzoomedRect.width() / 2;
+    float centerY = unzoomedRect.y() + unzoomedRect.height() / 2;
+    // The line width is 3px on a regular sized, high DPI NSCancelButtonCell
+    // (which is 28px wide).
+    float lineWidth = unzoomedRect.width() * 3 / 28;
+    // The line length is 16px on a regular sized, high DPI NSCancelButtonCell.
+    float lineLength = unzoomedRect.width() * 16 / 28;
+
+    Path xPath;
+    FloatSize lineRectRadius(lineWidth / 2, lineWidth / 2);
+    xPath.addRoundedRect(FloatRect(-lineLength / 2, -lineWidth / 2, lineLength, lineWidth),
+        lineRectRadius, lineRectRadius, lineRectRadius, lineRectRadius);
+    xPath.addRoundedRect(FloatRect(-lineWidth / 2, -lineLength / 2, lineWidth, lineLength),
+        lineRectRadius, lineRectRadius, lineRectRadius, lineRectRadius);
+
+    paintInfo.context->translate(centerX, centerY);
+    paintInfo.context->rotate(deg2rad(45.0));
+    paintInfo.context->clipOut(xPath);
+    paintInfo.context->rotate(deg2rad(-45.0));
+    paintInfo.context->translate(-centerX, -centerY);
+
+    paintInfo.context->setFillColor(fillColor);
+    paintInfo.context->fillEllipse(unzoomedRect);
+
     return false;
 }
 
 const IntSize* RenderThemeChromiumMac::cancelButtonSizes() const
 {
-    static const IntSize sizes[3] = { IntSize(16, 14), IntSize(13, 11), IntSize(13, 9) };
+    static const IntSize sizes[3] = { IntSize(14, 14), IntSize(11, 11), IntSize(9, 9) };
     return sizes;
 }
 
@@ -1665,16 +1740,17 @@
 
 const IntSize* RenderThemeChromiumMac::resultsButtonSizes() const
 {
-    static const IntSize sizes[3] = { IntSize(19, 13), IntSize(17, 11), IntSize(17, 9) };
+    static const IntSize sizes[3] = { IntSize(15, 14), IntSize(16, 13), IntSize(14, 11) };
     return sizes;
 }
 
-const int emptyResultsOffset = 9;
 void RenderThemeChromiumMac::adjustSearchFieldDecorationStyle(RenderStyle* style, Element*) const
 {
-    IntSize size = sizeForSystemFont(style, resultsButtonSizes());
-    style->setWidth(Length(size.width() - emptyResultsOffset, Fixed));
-    style->setHeight(Length(size.height(), Fixed));
+    NSControlSize controlSize = controlSizeForSystemFont(style);
+    IntSize searchFieldSize = searchFieldSizes()[controlSize];
+    int width = searchFieldSize.height() / 2 - searchFieldBorderWidth - searchFieldHorizontalPaddings()[controlSize];
+    style->setWidth(Length(width, Fixed));
+    style->setHeight(Length(0, Fixed));
     style->setBoxShadow(nullptr);
 }
 
@@ -1699,21 +1775,29 @@
     if (!input->renderer()->isBox())
         return false;
 
+    GraphicsContextStateSaver stateSaver(*paintInfo.context);
+
+    float zoomLevel = o->style()->effectiveZoom();
+    FloatRect unzoomedRect(r);
+    if (zoomLevel != 1) {
+        unzoomedRect.setWidth(unzoomedRect.width() / zoomLevel);
+        unzoomedRect.setHeight(unzoomedRect.height() / zoomLevel);
+        paintInfo.context->translate(unzoomedRect.x(), unzoomedRect.y());
+        paintInfo.context->scale(FloatSize(zoomLevel, zoomLevel));
+        paintInfo.context->translate(-unzoomedRect.x(), -unzoomedRect.y());
+    }
+
     LocalCurrentGraphicsContext localContext(paintInfo.context);
 
     NSSearchFieldCell* search = this->search();
     setSearchCellState(input->renderer(), r);
-    [search setControlSize:controlSizeForFont(o->style())];
-
+    [search setControlSize:searchFieldControlSizeForFont(o->style())];
     if ([search searchMenuTemplate] != nil)
         [search setSearchMenuTemplate:nil];
 
     updateActiveState([search searchButtonCell], o);
 
-    FloatRect localBounds = [search searchButtonRectForBounds:NSRect(input->renderBox()->pixelSnappedBorderBoxRect())];
-    localBounds = convertToPaintingRect(input->renderer(), o, localBounds, r);
-
-    [[search searchButtonCell] drawWithFrame:localBounds inView:documentViewFor(o)];
+    [[search searchButtonCell] drawWithFrame:unzoomedRect inView:documentViewFor(o)];
     [[search searchButtonCell] setControlView:nil];
     return false;
 }
@@ -1728,9 +1812,6 @@
     return -9;
 }
 
-const int sliderThumbWidth = 15;
-const int sliderThumbHeight = 15;
-
 void RenderThemeChromiumMac::adjustSliderThumbSize(RenderStyle* style, Element*) const
 {
     float zoomLevel = style->effectiveZoom();
@@ -1774,30 +1855,6 @@
     return m_searchMenuTemplate.get();
 }
 
-NSSliderCell* RenderThemeChromiumMac::sliderThumbHorizontal() const
-{
-    if (!m_sliderThumbHorizontal) {
-        m_sliderThumbHorizontal.adoptNS([[NSSliderCell alloc] init]);
-        [m_sliderThumbHorizontal.get() setSliderType:NSLinearSlider];
-        [m_sliderThumbHorizontal.get() setControlSize:NSSmallControlSize];
-        [m_sliderThumbHorizontal.get() setFocusRingType:NSFocusRingTypeExterior];
-    }
-
-    return m_sliderThumbHorizontal.get();
-}
-
-NSSliderCell* RenderThemeChromiumMac::sliderThumbVertical() const
-{
-    if (!m_sliderThumbVertical) {
-        m_sliderThumbVertical.adoptNS([[NSSliderCell alloc] init]);
-        [m_sliderThumbVertical.get() setSliderType:NSLinearSlider];
-        [m_sliderThumbVertical.get() setControlSize:NSSmallControlSize];
-        [m_sliderThumbVertical.get() setFocusRingType:NSFocusRingTypeExterior];
-    }
-
-    return m_sliderThumbVertical.get();
-}
-
 NSTextFieldCell* RenderThemeChromiumMac::textField() const
 {
     if (!m_textField) {
diff --git a/Source/core/rendering/RenderTreeAsText.cpp b/Source/core/rendering/RenderTreeAsText.cpp
index 668b008..1b18a15 100644
--- a/Source/core/rendering/RenderTreeAsText.cpp
+++ b/Source/core/rendering/RenderTreeAsText.cpp
@@ -405,11 +405,11 @@
 
             if (node->hasClass()) {
                 ts << " class=\"";
-                StyledElement* styledElement = static_cast<StyledElement*>(node);
-                for (size_t i = 0; i < styledElement->classNames().size(); ++i) {
+                Element* element = toElement(node);
+                for (size_t i = 0; i < element->classNames().size(); ++i) {
                     if (i > 0)
                         ts << " ";
-                    ts << styledElement->classNames()[i];
+                    ts << element->classNames()[i];
                 }
                 ts << "\"";
             }
diff --git a/Source/core/rendering/RenderView.cpp b/Source/core/rendering/RenderView.cpp
index 32d63a0..0501515 100644
--- a/Source/core/rendering/RenderView.cpp
+++ b/Source/core/rendering/RenderView.cpp
@@ -42,6 +42,7 @@
 #include "core/rendering/RenderLazyBlock.h"
 #include "core/rendering/RenderSelectionInfo.h"
 #include "core/rendering/RenderWidget.h"
+#include "wtf/MemoryInstrumentationHashSet.h"
 
 namespace WebCore {
 
@@ -268,7 +269,8 @@
                     || child->style()->logicalMaxHeight().isPercent()
                     || child->style()->logicalHeight().isViewportPercentage()
                     || child->style()->logicalMinHeight().isViewportPercentage()
-                    || child->style()->logicalMaxHeight().isViewportPercentage())
+                    || child->style()->logicalMaxHeight().isViewportPercentage()
+                    || child->isSVGRoot())
                 child->setChildNeedsLayout(true, MarkOnlyThis);
         }
     }
diff --git a/Source/core/rendering/RenderView.h b/Source/core/rendering/RenderView.h
index 3b93e29..340a3e2 100644
--- a/Source/core/rendering/RenderView.h
+++ b/Source/core/rendering/RenderView.h
@@ -218,8 +218,8 @@
         // We push LayoutState even if layoutState is disabled because it stores layoutDelta too.
         if (!doingFullRepaint() || m_layoutState->isPaginated() || renderer->hasColumns() || renderer->flowThreadContainingBlock()
             || m_layoutState->lineGrid() || (renderer->style()->lineGrid() != RenderStyle::initialLineGrid() && renderer->isBlockFlow())
-            || (renderer->isRenderBlock() && toRenderBlock(renderer)->exclusionShapeInsideInfo())
-            || (m_layoutState->exclusionShapeInsideInfo() && renderer->isRenderBlock() && !toRenderBlock(renderer)->allowsExclusionShapeInsideInfoSharing())
+            || (renderer->isRenderBlock() && toRenderBlock(renderer)->shapeInsideInfo())
+            || (m_layoutState->shapeInsideInfo() && renderer->isRenderBlock() && !toRenderBlock(renderer)->allowsShapeInsideInfoSharing())
             ) {
             m_layoutState = new (renderArena()) LayoutState(m_layoutState, renderer, offset, pageHeight, pageHeightChanged, colInfo);
             return true;
diff --git a/Source/core/rendering/TextAutosizer.cpp b/Source/core/rendering/TextAutosizer.cpp
index a794fbf..04e4956 100644
--- a/Source/core/rendering/TextAutosizer.cpp
+++ b/Source/core/rendering/TextAutosizer.cpp
@@ -26,6 +26,7 @@
 #include "core/html/HTMLElement.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/page/Settings.h"
+#include "core/platform/chromium/TraceEvent.h"
 #include "core/platform/graphics/IntSize.h"
 #include "core/rendering/RenderListItem.h"
 #include "core/rendering/RenderObject.h"
@@ -90,6 +91,18 @@
     return (ancestor && ancestor->isListItem()) ? toRenderListItem(ancestor) : 0;
 }
 
+static RenderObject* getAncestorList(const RenderObject* renderer)
+{
+    // FIXME: Add support for <menu> elements as a possible ancestor of an <li> element,
+    // see http://www.whatwg.org/specs/web-apps/current-work/multipage/grouping-content.html#the-li-element
+    for (RenderObject* ancestor = renderer->parent(); ancestor; ancestor = ancestor->parent()) {
+        Node* parentNode = ancestor->generatingNode();
+        if (parentNode && (parentNode->hasTagName(olTag) || parentNode->hasTagName(ulTag)))
+            return ancestor;
+    }
+    return 0;
+}
+
 TextAutosizer::TextAutosizer(Document* document)
     : m_document(document)
 {
@@ -111,6 +124,8 @@
 
 bool TextAutosizer::processSubtree(RenderObject* layoutRoot)
 {
+    TRACE_EVENT0("webkit", "TextAutosizer::processSubtree");
+
     // FIXME: Text Autosizing should only be enabled when m_document->page()->mainFrame()->view()->useFixedLayout()
     // is true, but for now it's useful to ignore this so that it can be tested on desktop.
     if (!m_document->settings() || !m_document->settings()->textAutosizingEnabled() || layoutRoot->view()->printing() || !m_document->page())
@@ -216,9 +231,12 @@
             if (localMultiplier != 1 && descendant->style()->textAutosizingMultiplier() == 1) {
                 setMultiplier(descendant, localMultiplier);
                 setMultiplier(descendant->parent(), localMultiplier); // Parent does line spacing.
+
                 if (RenderListItem* listItemAncestor = getAncestorListItem(descendant)) {
-                    if (listItemAncestor->style()->textAutosizingMultiplier() == 1)
-                        setMultiplier(listItemAncestor, localMultiplier);
+                    if (RenderObject* list = getAncestorList(listItemAncestor)) {
+                        if (list->style()->textAutosizingMultiplier() == 1)
+                            setMultiplierForList(list, localMultiplier);
+                    }
                 }
             }
         } else if (isAutosizingContainer(descendant)) {
@@ -239,11 +257,28 @@
 
 void TextAutosizer::setMultiplier(RenderObject* renderer, float multiplier)
 {
+    // FIXME: Investigate if a clone() is needed and whether it does the right thing w.r.t. style sharing.
     RefPtr<RenderStyle> newStyle = RenderStyle::clone(renderer->style());
     newStyle->setTextAutosizingMultiplier(multiplier);
     renderer->setStyle(newStyle.release());
 }
 
+void TextAutosizer::setMultiplierForList(RenderObject* renderer, float multiplier)
+{
+#ifndef NDEBUG
+    Node* parentNode = renderer->generatingNode();
+    ASSERT(parentNode);
+    ASSERT(parentNode->hasTagName(olTag) || parentNode->hasTagName(ulTag));
+#endif
+    setMultiplier(renderer, multiplier);
+
+    // Make sure all list items are autosized consistently.
+    for (RenderObject* child = renderer->firstChild(); child; child = child->nextSibling()) {
+        if (child->isListItem() && child->style()->textAutosizingMultiplier() == 1)
+            setMultiplier(child, multiplier);
+    }
+}
+
 float TextAutosizer::computeAutosizedFontSize(float specifiedSize, float multiplier)
 {
     // Somewhat arbitrary "pleasant" font size.
diff --git a/Source/core/rendering/TextAutosizer.h b/Source/core/rendering/TextAutosizer.h
index 5b38d07..d1beecd 100644
--- a/Source/core/rendering/TextAutosizer.h
+++ b/Source/core/rendering/TextAutosizer.h
@@ -69,6 +69,7 @@
     void processContainer(float multiplier, RenderBlock* container, TextAutosizingClusterInfo&, RenderObject* subtreeRoot, const TextAutosizingWindowInfo&);
 
     void setMultiplier(RenderObject*, float);
+    void setMultiplierForList(RenderObject* renderer, float multiplier);
 
     static bool isAutosizingContainer(const RenderObject*);
     static bool isNarrowDescendant(const RenderBlock*, TextAutosizingClusterInfo& parentClusterInfo);
diff --git a/Source/core/rendering/exclusions/ExclusionPolygon.cpp b/Source/core/rendering/shapes/PolygonShape.cpp
similarity index 90%
rename from Source/core/rendering/exclusions/ExclusionPolygon.cpp
rename to Source/core/rendering/shapes/PolygonShape.cpp
index 2e042f2..06f525a 100644
--- a/Source/core/rendering/exclusions/ExclusionPolygon.cpp
+++ b/Source/core/rendering/shapes/PolygonShape.cpp
@@ -28,7 +28,7 @@
  */
 
 #include "config.h"
-#include "core/rendering/exclusions/ExclusionPolygon.h"
+#include "core/rendering/shapes/PolygonShape.h"
 
 #include "core/platform/graphics/LayoutPoint.h"
 #include "wtf/MathExtras.h"
@@ -178,7 +178,7 @@
     return adoptPtr(new FloatPolygon(marginVertices.release(), fillRule));
 }
 
-const FloatPolygon& ExclusionPolygon::shapePaddingBounds() const
+const FloatPolygon& PolygonShape::shapePaddingBounds() const
 {
     ASSERT(shapePadding() >= 0);
     if (!shapePadding())
@@ -190,7 +190,7 @@
     return *m_paddingBounds;
 }
 
-const FloatPolygon& ExclusionPolygon::shapeMarginBounds() const
+const FloatPolygon& PolygonShape::shapeMarginBounds() const
 {
     ASSERT(shapeMargin() >= 0);
     if (!shapeMargin())
@@ -225,10 +225,10 @@
     return true;
 }
 
-static inline bool appendIntervalX(float x, bool inside, Vector<ExclusionInterval>& result)
+static inline bool appendIntervalX(float x, bool inside, Vector<ShapeInterval>& result)
 {
     if (!inside)
-        result.append(ExclusionInterval(x));
+        result.append(ShapeInterval(x));
     else
         result[result.size() - 1].x2 = x;
 
@@ -242,7 +242,7 @@
     return (x1 == x2) ? intersection1.type < intersection2.type : x1 < x2;
 }
 
-static void computeXIntersections(const FloatPolygon& polygon, float y, bool isMinY, Vector<ExclusionInterval>& result)
+static void computeXIntersections(const FloatPolygon& polygon, float y, bool isMinY, Vector<ShapeInterval>& result)
 {
     Vector<const FloatPolygonEdge*> edges;
     if (!polygon.overlappingEdges(y, y, edges))
@@ -312,7 +312,7 @@
     }
 }
 
-static void computeOverlappingEdgeXProjections(const FloatPolygon& polygon, float y1, float y2, Vector<ExclusionInterval>& result)
+static void computeOverlappingEdgeXProjections(const FloatPolygon& polygon, float y1, float y2, Vector<ShapeInterval>& result)
 {
     Vector<const FloatPolygonEdge*> edges;
     if (!polygon.overlappingEdges(y1, y2, edges))
@@ -327,26 +327,28 @@
         if (edge->minY() < y1) {
             computeXIntersection(edge, y1, intersection);
             x1 = intersection.point.x();
-        } else
+        } else {
             x1 = (edge->vertex1().y() < edge->vertex2().y()) ? edge->vertex1().x() : edge->vertex2().x();
+        }
 
         if (edge->maxY() > y2) {
             computeXIntersection(edge, y2, intersection);
             x2 = intersection.point.x();
-        } else
+        } else {
             x2 = (edge->vertex1().y() > edge->vertex2().y()) ? edge->vertex1().x() : edge->vertex2().x();
+        }
 
         if (x1 > x2)
             std::swap(x1, x2);
 
         if (x2 > x1)
-            result.append(ExclusionInterval(x1, x2));
+            result.append(ShapeInterval(x1, x2));
     }
 
-    sortExclusionIntervals(result);
+    sortShapeIntervals(result);
 }
 
-void ExclusionPolygon::getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
+void PolygonShape::getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
 {
     const FloatPolygon& polygon = shapeMarginBounds();
     if (polygon.isEmpty())
@@ -355,26 +357,26 @@
     float y1 = logicalTop;
     float y2 = logicalTop + logicalHeight;
 
-    Vector<ExclusionInterval> y1XIntervals, y2XIntervals;
+    Vector<ShapeInterval> y1XIntervals, y2XIntervals;
     computeXIntersections(polygon, y1, true, y1XIntervals);
     computeXIntersections(polygon, y2, false, y2XIntervals);
 
-    Vector<ExclusionInterval> mergedIntervals;
-    mergeExclusionIntervals(y1XIntervals, y2XIntervals, mergedIntervals);
+    Vector<ShapeInterval> mergedIntervals;
+    mergeShapeIntervals(y1XIntervals, y2XIntervals, mergedIntervals);
 
-    Vector<ExclusionInterval> edgeIntervals;
+    Vector<ShapeInterval> edgeIntervals;
     computeOverlappingEdgeXProjections(polygon, y1, y2, edgeIntervals);
 
-    Vector<ExclusionInterval> excludedIntervals;
-    mergeExclusionIntervals(mergedIntervals, edgeIntervals, excludedIntervals);
+    Vector<ShapeInterval> excludedIntervals;
+    mergeShapeIntervals(mergedIntervals, edgeIntervals, excludedIntervals);
 
     for (unsigned i = 0; i < excludedIntervals.size(); ++i) {
-        ExclusionInterval interval = excludedIntervals[i];
+        ShapeInterval interval = excludedIntervals[i];
         result.append(LineSegment(interval.x1, interval.x2));
     }
 }
 
-void ExclusionPolygon::getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
+void PolygonShape::getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
 {
     const FloatPolygon& polygon = shapePaddingBounds();
     if (polygon.isEmpty())
@@ -383,21 +385,21 @@
     float y1 = logicalTop;
     float y2 = logicalTop + logicalHeight;
 
-    Vector<ExclusionInterval> y1XIntervals, y2XIntervals;
+    Vector<ShapeInterval> y1XIntervals, y2XIntervals;
     computeXIntersections(polygon, y1, true, y1XIntervals);
     computeXIntersections(polygon, y2, false, y2XIntervals);
 
-    Vector<ExclusionInterval> commonIntervals;
-    intersectExclusionIntervals(y1XIntervals, y2XIntervals, commonIntervals);
+    Vector<ShapeInterval> commonIntervals;
+    intersectShapeIntervals(y1XIntervals, y2XIntervals, commonIntervals);
 
-    Vector<ExclusionInterval> edgeIntervals;
+    Vector<ShapeInterval> edgeIntervals;
     computeOverlappingEdgeXProjections(polygon, y1, y2, edgeIntervals);
 
-    Vector<ExclusionInterval> includedIntervals;
-    subtractExclusionIntervals(commonIntervals, edgeIntervals, includedIntervals);
+    Vector<ShapeInterval> includedIntervals;
+    subtractShapeIntervals(commonIntervals, edgeIntervals, includedIntervals);
 
     for (unsigned i = 0; i < includedIntervals.size(); ++i) {
-        ExclusionInterval interval = includedIntervals[i];
+        ShapeInterval interval = includedIntervals[i];
         result.append(LineSegment(interval.x1, interval.x2));
     }
 }
@@ -426,7 +428,7 @@
     return false;
 }
 
-bool ExclusionPolygon::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit& result) const
+bool PolygonShape::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit& result) const
 {
     float minIntervalTop = minLogicalIntervalTop;
     float minIntervalHeight = minLogicalIntervalSize.height();
@@ -476,9 +478,10 @@
                 offsetEdgeBuffer.append(OffsetPolygonEdge(vertex1, FloatSize(-dx, -dy), FloatSize(dx, -dy)));
         }
 
-        for (unsigned j = 0; j < offsetEdgeBuffer.size(); ++j)
+        for (unsigned j = 0; j < offsetEdgeBuffer.size(); ++j) {
             if (offsetEdgeBuffer[j].maxY() >= minY)
                 offsetEdges.append(offsetEdgeBuffer[j]);
+        }
     }
 
     offsetEdges.append(OffsetPolygonEdge(polygon, minIntervalTop, FloatSize(0, dy)));
diff --git a/Source/core/rendering/exclusions/ExclusionPolygon.h b/Source/core/rendering/shapes/PolygonShape.h
similarity index 90%
rename from Source/core/rendering/exclusions/ExclusionPolygon.h
rename to Source/core/rendering/shapes/PolygonShape.h
index 350e1bf..ea7241f 100644
--- a/Source/core/rendering/exclusions/ExclusionPolygon.h
+++ b/Source/core/rendering/shapes/PolygonShape.h
@@ -27,12 +27,12 @@
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ExclusionPolygon_h
-#define ExclusionPolygon_h
+#ifndef PolygonShape_h
+#define PolygonShape_h
 
 #include "core/platform/graphics/FloatPolygon.h"
-#include "core/rendering/exclusions/ExclusionInterval.h"
-#include "core/rendering/exclusions/ExclusionShape.h"
+#include "core/rendering/shapes/Shape.h"
+#include "core/rendering/shapes/ShapeInterval.h"
 
 namespace WebCore {
 
@@ -80,11 +80,11 @@
     Basis m_basis;
 };
 
-class ExclusionPolygon : public ExclusionShape {
-    WTF_MAKE_NONCOPYABLE(ExclusionPolygon);
+class PolygonShape : public Shape {
+    WTF_MAKE_NONCOPYABLE(PolygonShape);
 public:
-    ExclusionPolygon(PassOwnPtr<Vector<FloatPoint> > vertices, WindRule fillRule)
-        : ExclusionShape()
+    PolygonShape(PassOwnPtr<Vector<FloatPoint> > vertices, WindRule fillRule)
+        : Shape()
         , m_polygon(vertices, fillRule)
         , m_marginBounds(nullptr)
         , m_paddingBounds(nullptr)
@@ -109,4 +109,4 @@
 
 } // namespace WebCore
 
-#endif // ExclusionPolygon_h
+#endif // PolygonShape_h
diff --git a/Source/core/rendering/exclusions/ExclusionRectangle.cpp b/Source/core/rendering/shapes/RectangleShape.cpp
similarity index 91%
rename from Source/core/rendering/exclusions/ExclusionRectangle.cpp
rename to Source/core/rendering/shapes/RectangleShape.cpp
index 333958c..b2b26aa 100644
--- a/Source/core/rendering/exclusions/ExclusionRectangle.cpp
+++ b/Source/core/rendering/shapes/RectangleShape.cpp
@@ -28,9 +28,9 @@
  */
 
 #include "config.h"
-#include "core/rendering/exclusions/ExclusionRectangle.h"
+#include "core/rendering/shapes/RectangleShape.h"
 
-#include <wtf/MathExtras.h>
+#include "wtf/MathExtras.h"
 
 namespace WebCore {
 
@@ -83,7 +83,7 @@
     return FloatPoint(xi, yi);
 }
 
-FloatRoundedRect ExclusionRectangle::shapePaddingBounds() const
+FloatRoundedRect RectangleShape::shapePaddingBounds() const
 {
     if (!m_haveInitializedPaddingBounds) {
         m_haveInitializedPaddingBounds = true;
@@ -92,7 +92,7 @@
     return m_paddingBounds;
 }
 
-FloatRoundedRect ExclusionRectangle::shapeMarginBounds() const
+FloatRoundedRect RectangleShape::shapeMarginBounds() const
 {
     if (!m_haveInitializedMarginBounds) {
         m_haveInitializedMarginBounds = true;
@@ -101,7 +101,7 @@
     return m_marginBounds;
 }
 
-void ExclusionRectangle::getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
+void RectangleShape::getExcludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
 {
     const FloatRoundedRect& bounds = shapeMarginBounds();
     if (bounds.isEmpty())
@@ -133,7 +133,7 @@
     result.append(LineSegment(x1, x2));
 }
 
-void ExclusionRectangle::getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
+void RectangleShape::getIncludedIntervals(LayoutUnit logicalTop, LayoutUnit logicalHeight, SegmentList& result) const
 {
     const FloatRoundedRect& bounds = shapePaddingBounds();
     if (bounds.isEmpty())
@@ -178,7 +178,7 @@
     result.append(LineSegment(x1, x2));
 }
 
-bool ExclusionRectangle::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit& result) const
+bool RectangleShape::firstIncludedIntervalLogicalTop(LayoutUnit minLogicalIntervalTop, const LayoutSize& minLogicalIntervalSize, LayoutUnit& result) const
 {
     float minIntervalTop = minLogicalIntervalTop;
     float minIntervalHeight = minLogicalIntervalSize.height();
diff --git a/Source/core/rendering/exclusions/ExclusionRectangle.h b/Source/core/rendering/shapes/RectangleShape.h
similarity index 89%
rename from Source/core/rendering/exclusions/ExclusionRectangle.h
rename to Source/core/rendering/shapes/RectangleShape.h
index 7ed5def..cd512d1 100644
--- a/Source/core/rendering/exclusions/ExclusionRectangle.h
+++ b/Source/core/rendering/shapes/RectangleShape.h
@@ -27,15 +27,15 @@
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ExclusionRectangle_h
-#define ExclusionRectangle_h
+#ifndef RectangleShape_h
+#define RectangleShape_h
 
 #include "core/platform/graphics/FloatPoint.h"
 #include "core/platform/graphics/FloatRect.h"
 #include "core/platform/graphics/FloatSize.h"
-#include "core/rendering/exclusions/ExclusionShape.h"
-#include <wtf/Assertions.h>
-#include <wtf/Vector.h>
+#include "core/rendering/shapes/Shape.h"
+#include "wtf/Assertions.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -58,10 +58,10 @@
     FloatSize m_radii;
 };
 
-class ExclusionRectangle : public ExclusionShape {
+class RectangleShape : public Shape {
 public:
-    ExclusionRectangle(const FloatRect& bounds, const FloatSize& radii)
-        : ExclusionShape()
+    RectangleShape(const FloatRect& bounds, const FloatSize& radii)
+        : Shape()
         , m_bounds(bounds, radii)
         , m_haveInitializedMarginBounds(false)
         , m_haveInitializedPaddingBounds(false)
@@ -88,4 +88,4 @@
 
 } // namespace WebCore
 
-#endif // ExclusionRectangle_h
+#endif // RectangleShape_h
diff --git a/Source/core/rendering/exclusions/ExclusionShape.cpp b/Source/core/rendering/shapes/Shape.cpp
similarity index 75%
rename from Source/core/rendering/exclusions/ExclusionShape.cpp
rename to Source/core/rendering/shapes/Shape.cpp
index 23d216d..11fec13 100644
--- a/Source/core/rendering/exclusions/ExclusionShape.cpp
+++ b/Source/core/rendering/shapes/Shape.cpp
@@ -28,40 +28,40 @@
  */
 
 #include "config.h"
-#include "core/rendering/exclusions/ExclusionShape.h"
+#include "core/rendering/shapes/Shape.h"
 
 #include "core/css/LengthFunctions.h"
 #include "core/platform/graphics/FloatSize.h"
 #include "core/platform/graphics/WindRule.h"
-#include "core/rendering/exclusions/ExclusionPolygon.h"
-#include "core/rendering/exclusions/ExclusionRectangle.h"
-#include <wtf/MathExtras.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassOwnPtr.h>
+#include "core/rendering/shapes/PolygonShape.h"
+#include "core/rendering/shapes/RectangleShape.h"
+#include "wtf/MathExtras.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
-static PassOwnPtr<ExclusionShape> createExclusionRectangle(const FloatRect& bounds, const FloatSize& radii)
+static PassOwnPtr<Shape> createRectangleShape(const FloatRect& bounds, const FloatSize& radii)
 {
     ASSERT(bounds.width() >= 0 && bounds.height() >= 0 && radii.width() >= 0 && radii.height() >= 0);
-    return adoptPtr(new ExclusionRectangle(bounds, radii));
+    return adoptPtr(new RectangleShape(bounds, radii));
 }
 
-static PassOwnPtr<ExclusionShape> createExclusionCircle(const FloatPoint& center, float radius)
+static PassOwnPtr<Shape> createCircleShape(const FloatPoint& center, float radius)
 {
     ASSERT(radius >= 0);
-    return adoptPtr(new ExclusionRectangle(FloatRect(center.x() - radius, center.y() - radius, radius*2, radius*2), FloatSize(radius, radius)));
+    return adoptPtr(new RectangleShape(FloatRect(center.x() - radius, center.y() - radius, radius*2, radius*2), FloatSize(radius, radius)));
 }
 
-static PassOwnPtr<ExclusionShape> createExclusionEllipse(const FloatPoint& center, const FloatSize& radii)
+static PassOwnPtr<Shape> createEllipseShape(const FloatPoint& center, const FloatSize& radii)
 {
     ASSERT(radii.width() >= 0 && radii.height() >= 0);
-    return adoptPtr(new ExclusionRectangle(FloatRect(center.x() - radii.width(), center.y() - radii.height(), radii.width()*2, radii.height()*2), radii));
+    return adoptPtr(new RectangleShape(FloatRect(center.x() - radii.width(), center.y() - radii.height(), radii.width()*2, radii.height()*2), radii));
 }
 
-static PassOwnPtr<ExclusionShape> createExclusionPolygon(PassOwnPtr<Vector<FloatPoint> > vertices, WindRule fillRule)
+static PassOwnPtr<Shape> createPolygonShape(PassOwnPtr<Vector<FloatPoint> > vertices, WindRule fillRule)
 {
-    return adoptPtr(new ExclusionPolygon(vertices, fillRule));
+    return adoptPtr(new PolygonShape(vertices, fillRule));
 }
 
 static inline FloatRect physicalRectToLogical(const FloatRect& rect, float logicalBoxHeight, WritingMode writingMode)
@@ -89,14 +89,14 @@
     return size.transposedSize();
 }
 
-PassOwnPtr<ExclusionShape> ExclusionShape::createExclusionShape(const BasicShape* basicShape, const LayoutSize& logicalBoxSize, WritingMode writingMode, Length margin, Length padding)
+PassOwnPtr<Shape> Shape::createShape(const BasicShape* basicShape, const LayoutSize& logicalBoxSize, WritingMode writingMode, Length margin, Length padding)
 {
     ASSERT(basicShape);
 
     bool horizontalWritingMode = isHorizontalWritingMode(writingMode);
     float boxWidth = horizontalWritingMode ? logicalBoxSize.width() : logicalBoxSize.height();
     float boxHeight = horizontalWritingMode ? logicalBoxSize.height() : logicalBoxSize.width();
-    OwnPtr<ExclusionShape> exclusionShape;
+    OwnPtr<Shape> shape;
 
     switch (basicShape->type()) {
 
@@ -114,7 +114,7 @@
             radiusYLength.isUndefined() ? 0 : floatValueForLength(radiusYLength, boxHeight));
         FloatRect logicalBounds = physicalRectToLogical(bounds, logicalBoxSize.height(), writingMode);
 
-        exclusionShape = createExclusionRectangle(logicalBounds, physicalSizeToLogical(cornerRadii, writingMode));
+        shape = createRectangleShape(logicalBounds, physicalSizeToLogical(cornerRadii, writingMode));
         break;
     }
 
@@ -125,7 +125,7 @@
         float radius = floatValueForLength(circle->radius(), std::min(boxHeight, boxWidth));
         FloatPoint logicalCenter = physicalPointToLogical(FloatPoint(centerX, centerY), logicalBoxSize.height(), writingMode);
 
-        exclusionShape = createExclusionCircle(logicalCenter, radius);
+        shape = createCircleShape(logicalCenter, radius);
         break;
     }
 
@@ -138,7 +138,7 @@
         FloatPoint logicalCenter = physicalPointToLogical(FloatPoint(centerX, centerY), logicalBoxSize.height(), writingMode);
         FloatSize logicalRadii = physicalSizeToLogical(FloatSize(radiusX, radiusY), writingMode);
 
-        exclusionShape = createExclusionEllipse(logicalCenter, logicalRadii);
+        shape = createEllipseShape(logicalCenter, logicalRadii);
         break;
     }
 
@@ -154,7 +154,7 @@
                 floatValueForLength(values.at(i + 1), boxHeight));
             (*vertices)[i / 2] = physicalPointToLogical(vertex, logicalBoxSize.height(), writingMode);
         }
-        exclusionShape = createExclusionPolygon(vertices.release(), polygon->windRule());
+        shape = createPolygonShape(vertices.release(), polygon->windRule());
         break;
     }
 
@@ -162,11 +162,11 @@
         ASSERT_NOT_REACHED();
     }
 
-    exclusionShape->m_writingMode = writingMode;
-    exclusionShape->m_margin = floatValueForLength(margin, 0);
-    exclusionShape->m_padding = floatValueForLength(padding, 0);
+    shape->m_writingMode = writingMode;
+    shape->m_margin = floatValueForLength(margin, 0);
+    shape->m_padding = floatValueForLength(padding, 0);
 
-    return exclusionShape.release();
+    return shape.release();
 }
 
 } // namespace WebCore
diff --git a/Source/core/rendering/exclusions/ExclusionShape.h b/Source/core/rendering/shapes/Shape.h
similarity index 89%
rename from Source/core/rendering/exclusions/ExclusionShape.h
rename to Source/core/rendering/shapes/Shape.h
index b433fc7..6e257c9 100644
--- a/Source/core/rendering/exclusions/ExclusionShape.h
+++ b/Source/core/rendering/shapes/Shape.h
@@ -27,14 +27,14 @@
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ExclusionShape_h
-#define ExclusionShape_h
+#ifndef Shape_h
+#define Shape_h
 
 #include "core/platform/graphics/LayoutRect.h"
 #include "core/platform/text/WritingMode.h"
 #include "core/rendering/style/BasicShapes.h"
-#include <wtf/PassOwnPtr.h>
-#include <wtf/Vector.h>
+#include "wtf/PassOwnPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -57,11 +57,11 @@
 // computed segments are returned as pairs of logical X coordinates. The BasicShape itself is defined in
 // physical coordinates.
 
-class ExclusionShape {
+class Shape {
 public:
-    static PassOwnPtr<ExclusionShape> createExclusionShape(const BasicShape*, const LayoutSize& logicalBoxSize, WritingMode, Length margin, Length padding);
+    static PassOwnPtr<Shape> createShape(const BasicShape*, const LayoutSize& logicalBoxSize, WritingMode, Length margin, Length padding);
 
-    virtual ~ExclusionShape() { }
+    virtual ~Shape() { }
 
     virtual LayoutRect shapeMarginLogicalBoundingBox() const = 0;
     virtual LayoutRect shapePaddingLogicalBoundingBox() const = 0;
@@ -82,4 +82,4 @@
 
 } // namespace WebCore
 
-#endif // ExclusionShape_h
+#endif // Shape_h
diff --git a/Source/core/rendering/exclusions/ExclusionShapeInfo.cpp b/Source/core/rendering/shapes/ShapeInfo.cpp
similarity index 60%
rename from Source/core/rendering/exclusions/ExclusionShapeInfo.cpp
rename to Source/core/rendering/shapes/ShapeInfo.cpp
index 69e2a41..8ee0273 100644
--- a/Source/core/rendering/exclusions/ExclusionShapeInfo.cpp
+++ b/Source/core/rendering/shapes/ShapeInfo.cpp
@@ -28,31 +28,31 @@
  */
 
 #include "config.h"
-#include "core/rendering/exclusions/ExclusionShapeInfo.h"
+#include "core/rendering/shapes/ShapeInfo.h"
 
 #include "core/rendering/RenderRegion.h"
-#include "core/rendering/exclusions/ExclusionShape.h"
+#include "core/rendering/shapes/Shape.h"
 #include "core/rendering/style/RenderStyle.h"
 
 namespace WebCore {
-template<class RenderType, ExclusionShapeValue* (RenderStyle::*shapeGetter)() const, void (ExclusionShape::*intervalGetter)(LayoutUnit, LayoutUnit, SegmentList&) const>
-const ExclusionShape* ExclusionShapeInfo<RenderType, shapeGetter, intervalGetter>::computedShape() const
+template<class RenderType, ShapeValue* (RenderStyle::*shapeGetter)() const, void (Shape::*intervalGetter)(LayoutUnit, LayoutUnit, SegmentList&) const>
+const Shape* ShapeInfo<RenderType, shapeGetter, intervalGetter>::computedShape() const
 {
-    if (ExclusionShape* exclusionShape = m_shape.get())
-        return exclusionShape;
+    if (Shape* shape = m_shape.get())
+        return shape;
 
-    ExclusionShapeValue* shapeValue = (m_renderer->style()->*shapeGetter)();
-    BasicShape* shape = (shapeValue && shapeValue->type() == ExclusionShapeValue::Shape) ? shapeValue->shape() : 0;
+    ShapeValue* shapeValue = (m_renderer->style()->*shapeGetter)();
+    BasicShape* shape = (shapeValue && shapeValue->type() == ShapeValue::Shape) ? shapeValue->shape() : 0;
 
     ASSERT(shape);
 
-    m_shape = ExclusionShape::createExclusionShape(shape, LayoutSize(m_shapeLogicalWidth, m_shapeLogicalHeight), m_renderer->style()->writingMode(), m_renderer->style()->shapeMargin(), m_renderer->style()->shapePadding());
+    m_shape = Shape::createShape(shape, LayoutSize(m_shapeLogicalWidth, m_shapeLogicalHeight), m_renderer->style()->writingMode(), m_renderer->style()->shapeMargin(), m_renderer->style()->shapePadding());
     ASSERT(m_shape);
     return m_shape.get();
 }
 
-template<class RenderType, ExclusionShapeValue* (RenderStyle::*shapeGetter)() const, void (ExclusionShape::*intervalGetter)(LayoutUnit, LayoutUnit, SegmentList&) const>
-LayoutUnit ExclusionShapeInfo<RenderType, shapeGetter, intervalGetter>::logicalTopOffset() const
+template<class RenderType, ShapeValue* (RenderStyle::*shapeGetter)() const, void (Shape::*intervalGetter)(LayoutUnit, LayoutUnit, SegmentList&) const>
+LayoutUnit ShapeInfo<RenderType, shapeGetter, intervalGetter>::logicalTopOffset() const
 {
     LayoutUnit logicalTopOffset = m_renderer->style()->boxSizing() == CONTENT_BOX ? m_renderer->borderBefore() + m_renderer->paddingBefore() : LayoutUnit();
     // Content in a flow thread is relative to the beginning of the thread, but the shape calculation should be relative to the current region.
@@ -61,8 +61,8 @@
     return logicalTopOffset;
 }
 
-template<class RenderType, ExclusionShapeValue* (RenderStyle::*shapeGetter)() const, void (ExclusionShape::*intervalGetter)(LayoutUnit, LayoutUnit, SegmentList&) const>
-bool ExclusionShapeInfo<RenderType, shapeGetter, intervalGetter>::computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight)
+template<class RenderType, ShapeValue* (RenderStyle::*shapeGetter)() const, void (Shape::*intervalGetter)(LayoutUnit, LayoutUnit, SegmentList&) const>
+bool ShapeInfo<RenderType, shapeGetter, intervalGetter>::computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight)
 {
     ASSERT(lineHeight >= 0);
     m_shapeLineTop = lineTop - logicalTopOffset();
@@ -81,6 +81,6 @@
     return m_segments.size();
 }
 
-template class ExclusionShapeInfo<RenderBlock, &RenderStyle::resolvedShapeInside, &ExclusionShape::getIncludedIntervals>;
-template class ExclusionShapeInfo<RenderBox, &RenderStyle::shapeOutside, &ExclusionShape::getExcludedIntervals>;
+template class ShapeInfo<RenderBlock, &RenderStyle::resolvedShapeInside, &Shape::getIncludedIntervals>;
+template class ShapeInfo<RenderBox, &RenderStyle::shapeOutside, &Shape::getExcludedIntervals>;
 }
diff --git a/Source/core/rendering/exclusions/ExclusionShapeInfo.h b/Source/core/rendering/shapes/ShapeInfo.h
similarity index 87%
rename from Source/core/rendering/exclusions/ExclusionShapeInfo.h
rename to Source/core/rendering/shapes/ShapeInfo.h
index dc9e35d..3812d10 100644
--- a/Source/core/rendering/exclusions/ExclusionShapeInfo.h
+++ b/Source/core/rendering/shapes/ShapeInfo.h
@@ -27,16 +27,16 @@
 * SUCH DAMAGE.
 */
 
-#ifndef ExclusionShapeInfo_h
-#define ExclusionShapeInfo_h
+#ifndef ShapeInfo_h
+#define ShapeInfo_h
 
 #include "core/platform/LayoutUnit.h"
 #include "core/platform/graphics/FloatRect.h"
-#include "core/rendering/exclusions/ExclusionShape.h"
-#include "core/rendering/style/ExclusionShapeValue.h"
+#include "core/rendering/shapes/Shape.h"
 #include "core/rendering/style/RenderStyle.h"
-#include <wtf/OwnPtr.h>
-#include <wtf/Vector.h>
+#include "core/rendering/style/ShapeValue.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -62,11 +62,11 @@
     }
 };
 
-template<class RenderType, ExclusionShapeValue* (RenderStyle::*shapeGetter)() const, void (ExclusionShape::*intervalGetter)(LayoutUnit, LayoutUnit, SegmentList&) const>
-class ExclusionShapeInfo {
+template<class RenderType, ShapeValue* (RenderStyle::*shapeGetter)() const, void (Shape::*intervalGetter)(LayoutUnit, LayoutUnit, SegmentList&) const>
+class ShapeInfo {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    virtual ~ExclusionShapeInfo() { }
+    virtual ~ShapeInfo() { }
 
     void setShapeSize(LayoutUnit logicalWidth, LayoutUnit logicalHeight)
     {
@@ -101,9 +101,9 @@
     const RenderType* owner() const { return m_renderer; }
 
 protected:
-    ExclusionShapeInfo(const RenderType* renderer): m_renderer(renderer) { }
+    ShapeInfo(const RenderType* renderer): m_renderer(renderer) { }
 
-    const ExclusionShape* computedShape() const;
+    const Shape* computedShape() const;
     virtual LayoutRect computedShapeLogicalBoundingBox() const = 0;
 
     LayoutUnit logicalTopOffset() const;
@@ -114,7 +114,7 @@
     SegmentList m_segments;
 
 private:
-    mutable OwnPtr<ExclusionShape> m_shape;
+    mutable OwnPtr<Shape> m_shape;
 
     LayoutUnit m_shapeLogicalWidth;
     LayoutUnit m_shapeLogicalHeight;
diff --git a/Source/core/rendering/exclusions/ExclusionShapeInsideInfo.cpp b/Source/core/rendering/shapes/ShapeInsideInfo.cpp
similarity index 84%
rename from Source/core/rendering/exclusions/ExclusionShapeInsideInfo.cpp
rename to Source/core/rendering/shapes/ShapeInsideInfo.cpp
index 210649a..01dff49 100644
--- a/Source/core/rendering/exclusions/ExclusionShapeInsideInfo.cpp
+++ b/Source/core/rendering/shapes/ShapeInsideInfo.cpp
@@ -28,7 +28,7 @@
  */
 
 #include "config.h"
-#include "core/rendering/exclusions/ExclusionShapeInsideInfo.h"
+#include "core/rendering/shapes/ShapeInsideInfo.h"
 
 #include "core/rendering/InlineIterator.h"
 #include "core/rendering/RenderBlock.h"
@@ -41,19 +41,19 @@
     {
     }
 
-bool ExclusionShapeInsideInfo::isEnabledFor(const RenderBlock* renderer)
+bool ShapeInsideInfo::isEnabledFor(const RenderBlock* renderer)
 {
-    ExclusionShapeValue* shapeValue = renderer->style()->resolvedShapeInside();
-    if (!shapeValue || shapeValue->type() != ExclusionShapeValue::Shape)
+    ShapeValue* shapeValue = renderer->style()->resolvedShapeInside();
+    if (!shapeValue || shapeValue->type() != ShapeValue::Shape)
         return false;
 
     BasicShape* shape = shapeValue->shape();
     return shape && shape->type() != BasicShape::BasicShapeInsetRectangleType;
 }
 
-bool ExclusionShapeInsideInfo::adjustLogicalLineTop(float minSegmentWidth)
+bool ShapeInsideInfo::adjustLogicalLineTop(float minSegmentWidth)
 {
-    const ExclusionShape* shape = computedShape();
+    const Shape* shape = computedShape();
     if (!shape || m_lineHeight <= 0 || logicalLineTop() > shapeLogicalBottom())
         return false;
 
diff --git a/Source/core/rendering/exclusions/ExclusionShapeInsideInfo.h b/Source/core/rendering/shapes/ShapeInsideInfo.h
similarity index 79%
rename from Source/core/rendering/exclusions/ExclusionShapeInsideInfo.h
rename to Source/core/rendering/shapes/ShapeInsideInfo.h
index ab60456..4c410f2 100644
--- a/Source/core/rendering/exclusions/ExclusionShapeInsideInfo.h
+++ b/Source/core/rendering/shapes/ShapeInsideInfo.h
@@ -27,12 +27,12 @@
  * SUCH DAMAGE.
  */
 
-#ifndef ExclusionShapeInsideInfo_h
-#define ExclusionShapeInsideInfo_h
+#ifndef ShapeInsideInfo_h
+#define ShapeInsideInfo_h
 
-#include "core/rendering/exclusions/ExclusionShapeInfo.h"
-#include <wtf/PassOwnPtr.h>
-#include <wtf/Vector.h>
+#include "core/rendering/shapes/ShapeInfo.h"
+#include "wtf/PassOwnPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -60,16 +60,16 @@
 
 typedef Vector<LineSegmentRange> SegmentRangeList;
 
-class ExclusionShapeInsideInfo : public ExclusionShapeInfo<RenderBlock, &RenderStyle::resolvedShapeInside, &ExclusionShape::getIncludedIntervals> {
+class ShapeInsideInfo : public ShapeInfo<RenderBlock, &RenderStyle::resolvedShapeInside, &Shape::getIncludedIntervals> {
 public:
-    static PassOwnPtr<ExclusionShapeInsideInfo> createInfo(const RenderBlock* renderer) { return adoptPtr(new ExclusionShapeInsideInfo(renderer)); }
+    static PassOwnPtr<ShapeInsideInfo> createInfo(const RenderBlock* renderer) { return adoptPtr(new ShapeInsideInfo(renderer)); }
 
     static bool isEnabledFor(const RenderBlock* renderer);
 
     virtual bool computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight) OVERRIDE
     {
         m_segmentRanges.clear();
-        return ExclusionShapeInfo<RenderBlock, &RenderStyle::resolvedShapeInside, &ExclusionShape::getIncludedIntervals>::computeSegmentsForLine(lineTop, lineHeight);
+        return ShapeInfo<RenderBlock, &RenderStyle::resolvedShapeInside, &Shape::getIncludedIntervals>::computeSegmentsForLine(lineTop, lineHeight);
     }
 
     bool hasSegments() const
@@ -99,8 +99,8 @@
     virtual LayoutRect computedShapeLogicalBoundingBox() const OVERRIDE { return computedShape()->shapePaddingLogicalBoundingBox(); }
 
 private:
-    ExclusionShapeInsideInfo(const RenderBlock* renderer)
-    : ExclusionShapeInfo<RenderBlock, &RenderStyle::resolvedShapeInside, &ExclusionShape::getIncludedIntervals> (renderer)
+    ShapeInsideInfo(const RenderBlock* renderer)
+    : ShapeInfo<RenderBlock, &RenderStyle::resolvedShapeInside, &Shape::getIncludedIntervals> (renderer)
     , m_needsLayout(false)
     { }
 
diff --git a/Source/core/rendering/exclusions/ExclusionInterval.cpp b/Source/core/rendering/shapes/ShapeInterval.cpp
similarity index 71%
rename from Source/core/rendering/exclusions/ExclusionInterval.cpp
rename to Source/core/rendering/shapes/ShapeInterval.cpp
index 35fa2fa..071005b 100644
--- a/Source/core/rendering/exclusions/ExclusionInterval.cpp
+++ b/Source/core/rendering/shapes/ShapeInterval.cpp
@@ -28,20 +28,20 @@
  */
 
 #include "config.h"
-#include "core/rendering/exclusions/ExclusionInterval.h"
+#include "core/rendering/shapes/ShapeInterval.h"
 
-#include <wtf/MathExtras.h>
+#include "wtf/MathExtras.h"
 
 namespace WebCore {
 
 struct IntervalX1Comparator {
-    bool operator() (const ExclusionInterval& i1, const ExclusionInterval& i2) const
+    bool operator() (const ShapeInterval& i1, const ShapeInterval& i2) const
     {
         return i1.x1 < i2.x1;
     }
 };
 
-bool ExclusionInterval::intersect(const ExclusionInterval& i, ExclusionInterval& rv) const
+bool ShapeInterval::intersect(const ShapeInterval& i, ShapeInterval& rv) const
 {
     if (x2 < i.x1 || x1 > i.x2)
         return false;
@@ -50,29 +50,29 @@
     return true;
 }
 
-void sortExclusionIntervals(Vector<ExclusionInterval>& v)
+void sortShapeIntervals(Vector<ShapeInterval>& v)
 {
     std::sort(v.begin(), v.end(), IntervalX1Comparator());
 }
 
-void mergeExclusionIntervals(const Vector<ExclusionInterval>& v1, const Vector<ExclusionInterval>& v2, Vector<ExclusionInterval>& rv)
+void mergeShapeIntervals(const Vector<ShapeInterval>& v1, const Vector<ShapeInterval>& v2, Vector<ShapeInterval>& rv)
 {
-    if (!v1.size())
+    if (!v1.size()) {
         rv.appendRange(v2.begin(), v2.end());
-    else if (!v2.size())
+    } else if (!v2.size()) {
         rv.appendRange(v1.begin(), v1.end());
-    else {
-        Vector<ExclusionInterval> v(v1.size() + v2.size());
-        ExclusionInterval* interval = 0;
+    } else {
+        Vector<ShapeInterval> v(v1.size() + v2.size());
+        ShapeInterval* interval = 0;
 
         std::merge(v1.begin(), v1.end(), v2.begin(), v2.end(), v.begin(), IntervalX1Comparator());
 
         for (size_t i = 0; i < v.size(); i++) {
-            if (!interval)
+            if (!interval) {
                 interval = &v[i];
-            else if (v[i].x1 >= interval->x1 && v[i].x1 <= interval->x2) // FIXME: 1st <= test not needed?
+            } else if (v[i].x1 >= interval->x1 && v[i].x1 <= interval->x2) { // FIXME: 1st <= test not needed?
                 interval->x2 = std::max(interval->x2, v[i].x2);
-            else {
+            } else {
                 rv.append(*interval);
                 interval = &v[i];
             }
@@ -83,7 +83,7 @@
     }
 }
 
-void intersectExclusionIntervals(const Vector<ExclusionInterval>& v1, const Vector<ExclusionInterval>& v2, Vector<ExclusionInterval>& rv)
+void intersectShapeIntervals(const Vector<ShapeInterval>& v1, const Vector<ShapeInterval>& v2, Vector<ShapeInterval>& rv)
 {
     size_t v1Size = v1.size();
     size_t v2Size = v2.size();
@@ -91,13 +91,13 @@
     if (!v1Size || !v2Size)
         return;
 
-    ExclusionInterval interval;
+    ShapeInterval interval;
     bool overlap = false;
     size_t i1 = 0;
     size_t i2 = 0;
 
     while (i1 < v1Size && i2 < v2Size) {
-        ExclusionInterval v12;
+        ShapeInterval v12;
         if (v1[i1].intersect(v2[i2], v12)) {
             if (!overlap || !v12.intersect(interval, interval)) {
                 if (overlap)
@@ -124,7 +124,7 @@
         rv.append(interval);
 }
 
-void subtractExclusionIntervals(const Vector<ExclusionInterval>& v1, const Vector<ExclusionInterval>& v2, Vector<ExclusionInterval>& rv)
+void subtractShapeIntervals(const Vector<ShapeInterval>& v1, const Vector<ShapeInterval>& v2, Vector<ShapeInterval>& rv)
 {
     size_t v1Size = v1.size();
     size_t v2Size = v2.size();
@@ -132,24 +132,24 @@
     if (!v1Size)
         return;
 
-    if (!v2Size)
+    if (!v2Size) {
         rv.appendRange(v1.begin(), v1.end());
-    else {
+    } else {
         size_t i1 = 0, i2 = 0;
         rv.appendRange(v1.begin(), v1.end());
 
         while (i1 < rv.size() && i2 < v2Size) {
-            ExclusionInterval& interval1 = rv[i1];
-            const ExclusionInterval& interval2 = v2[i2];
+            ShapeInterval& interval1 = rv[i1];
+            const ShapeInterval& interval2 = v2[i2];
 
-            if (interval2.x1 <= interval1.x1 && interval2.x2 >= interval1.x2)
+            if (interval2.x1 <= interval1.x1 && interval2.x2 >= interval1.x2) {
                 rv.remove(i1);
-            else if (interval2.x2 < interval1.x1)
+            } else if (interval2.x2 < interval1.x1) {
                 i2 += 1;
-            else if (interval2.x1 > interval1.x2)
+            } else if (interval2.x1 > interval1.x2) {
                 i1 += 1;
-            else if (interval2.x1 > interval1.x1 && interval2.x2 < interval1.x2) {
-                rv.insert(i1, ExclusionInterval(interval1.x1, interval2.x1));
+            } else if (interval2.x1 > interval1.x1 && interval2.x2 < interval1.x2) {
+                rv.insert(i1, ShapeInterval(interval1.x1, interval2.x1));
                 interval1.x1 = interval2.x2;
                 i2 += 1;
             } else if (interval2.x1 <= interval1.x1) {
diff --git a/Source/core/rendering/exclusions/ExclusionInterval.h b/Source/core/rendering/shapes/ShapeInterval.h
similarity index 68%
rename from Source/core/rendering/exclusions/ExclusionInterval.h
rename to Source/core/rendering/shapes/ShapeInterval.h
index 1e8e59f..e0c165e 100644
--- a/Source/core/rendering/exclusions/ExclusionInterval.h
+++ b/Source/core/rendering/shapes/ShapeInterval.h
@@ -27,32 +27,32 @@
  * OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef ExclusionInterval_h
-#define ExclusionInterval_h
+#ifndef ShapeInterval_h
+#define ShapeInterval_h
 
-#include <wtf/Vector.h>
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
-struct ExclusionInterval {
+struct ShapeInterval {
 public:
     float x1;
     float x2;
 
-    ExclusionInterval(float x1 = 0, float x2 = 0)
+    ShapeInterval(float x1 = 0, float x2 = 0)
         : x1(x1)
         , x2(x2)
     {
     }
 
-    bool intersect(const ExclusionInterval&, ExclusionInterval&) const;
+    bool intersect(const ShapeInterval&, ShapeInterval&) const;
 };
 
-void sortExclusionIntervals(Vector<ExclusionInterval>&);
-void mergeExclusionIntervals(const Vector<ExclusionInterval>&, const Vector<ExclusionInterval>&, Vector<ExclusionInterval>&);
-void intersectExclusionIntervals(const Vector<ExclusionInterval>&, const Vector<ExclusionInterval>&, Vector<ExclusionInterval>&);
-void subtractExclusionIntervals(const Vector<ExclusionInterval>&, const Vector<ExclusionInterval>&, Vector<ExclusionInterval>&);
+void sortShapeIntervals(Vector<ShapeInterval>&);
+void mergeShapeIntervals(const Vector<ShapeInterval>&, const Vector<ShapeInterval>&, Vector<ShapeInterval>&);
+void intersectShapeIntervals(const Vector<ShapeInterval>&, const Vector<ShapeInterval>&, Vector<ShapeInterval>&);
+void subtractShapeIntervals(const Vector<ShapeInterval>&, const Vector<ShapeInterval>&, Vector<ShapeInterval>&);
 
 } // namespace WebCore
 
-#endif // ExclusionInterval_h
+#endif // ShapeInterval_h
diff --git a/Source/core/rendering/exclusions/ExclusionShapeOutsideInfo.cpp b/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
similarity index 79%
rename from Source/core/rendering/exclusions/ExclusionShapeOutsideInfo.cpp
rename to Source/core/rendering/shapes/ShapeOutsideInfo.cpp
index 3e2b631..d209a5e 100644
--- a/Source/core/rendering/exclusions/ExclusionShapeOutsideInfo.cpp
+++ b/Source/core/rendering/shapes/ShapeOutsideInfo.cpp
@@ -28,25 +28,25 @@
  */
 
 #include "config.h"
-#include "core/rendering/exclusions/ExclusionShapeOutsideInfo.h"
+#include "core/rendering/shapes/ShapeOutsideInfo.h"
 
 #include "core/rendering/RenderBox.h"
 
 namespace WebCore {
-bool ExclusionShapeOutsideInfo::isEnabledFor(const RenderBox* box)
+bool ShapeOutsideInfo::isEnabledFor(const RenderBox* box)
 {
-    ExclusionShapeValue* value = box->style()->shapeOutside();
-    if (!box->isFloatingWithShapeOutside() || value->type() != ExclusionShapeValue::Shape)
+    ShapeValue* value = box->style()->shapeOutside();
+    if (!box->isFloatingWithShapeOutside() || value->type() != ShapeValue::Shape)
         return false;
 
     BasicShape* shape = value->shape();
     return shape && shape->type() != BasicShape::BasicShapeInsetRectangleType;
 }
 
-bool ExclusionShapeOutsideInfo::computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight)
+bool ShapeOutsideInfo::computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight)
 {
     if (shapeSizeDirty() || m_lineTop != lineTop || m_lineHeight != lineHeight) {
-        if (ExclusionShapeInfo<RenderBox, &RenderStyle::shapeOutside, &ExclusionShape::getExcludedIntervals>::computeSegmentsForLine(lineTop, lineHeight)) {
+        if (ShapeInfo<RenderBox, &RenderStyle::shapeOutside, &Shape::getExcludedIntervals>::computeSegmentsForLine(lineTop, lineHeight)) {
             m_leftSegmentShapeBoundingBoxDelta = m_segments[0].logicalLeft - shapeLogicalLeft();
             m_rightSegmentShapeBoundingBoxDelta = m_segments[m_segments.size()-1].logicalRight - shapeLogicalRight();
         } else {
diff --git a/Source/core/rendering/exclusions/ExclusionShapeOutsideInfo.h b/Source/core/rendering/shapes/ShapeOutsideInfo.h
similarity index 77%
rename from Source/core/rendering/exclusions/ExclusionShapeOutsideInfo.h
rename to Source/core/rendering/shapes/ShapeOutsideInfo.h
index 07296c7..5e8de8b 100644
--- a/Source/core/rendering/exclusions/ExclusionShapeOutsideInfo.h
+++ b/Source/core/rendering/shapes/ShapeOutsideInfo.h
@@ -27,17 +27,17 @@
  * SUCH DAMAGE.
  */
 
-#ifndef ExclusionShapeOutsideInfo_h
-#define ExclusionShapeOutsideInfo_h
+#ifndef ShapeOutsideInfo_h
+#define ShapeOutsideInfo_h
 
 #include "core/platform/graphics/LayoutSize.h"
-#include "core/rendering/exclusions/ExclusionShapeInfo.h"
+#include "core/rendering/shapes/ShapeInfo.h"
 
 namespace WebCore {
 
 class RenderBox;
 
-class ExclusionShapeOutsideInfo : public ExclusionShapeInfo<RenderBox, &RenderStyle::shapeOutside, &ExclusionShape::getExcludedIntervals>, public MappedInfo<RenderBox, ExclusionShapeOutsideInfo> {
+class ShapeOutsideInfo : public ShapeInfo<RenderBox, &RenderStyle::shapeOutside, &Shape::getExcludedIntervals>, public MappedInfo<RenderBox, ShapeOutsideInfo> {
 public:
     LayoutSize shapeLogicalOffset() const { return LayoutSize(shapeLogicalLeft(), shapeLogicalTop()); }
 
@@ -46,14 +46,14 @@
 
     virtual bool computeSegmentsForLine(LayoutUnit lineTop, LayoutUnit lineHeight) OVERRIDE;
 
-    static PassOwnPtr<ExclusionShapeOutsideInfo> createInfo(const RenderBox* renderer) { return adoptPtr(new ExclusionShapeOutsideInfo(renderer)); }
+    static PassOwnPtr<ShapeOutsideInfo> createInfo(const RenderBox* renderer) { return adoptPtr(new ShapeOutsideInfo(renderer)); }
     static bool isEnabledFor(const RenderBox*);
 
 protected:
     virtual LayoutRect computedShapeLogicalBoundingBox() const OVERRIDE { return computedShape()->shapeMarginLogicalBoundingBox(); }
 
 private:
-    ExclusionShapeOutsideInfo(const RenderBox* renderer) : ExclusionShapeInfo<RenderBox, &RenderStyle::shapeOutside, &ExclusionShape::getExcludedIntervals>(renderer) { }
+    ShapeOutsideInfo(const RenderBox* renderer) : ShapeInfo<RenderBox, &RenderStyle::shapeOutside, &Shape::getExcludedIntervals>(renderer) { }
 
     LayoutUnit m_leftSegmentShapeBoundingBoxDelta;
     LayoutUnit m_rightSegmentShapeBoundingBoxDelta;
diff --git a/Source/core/rendering/style/GridCoordinate.h b/Source/core/rendering/style/GridCoordinate.h
new file mode 100644
index 0000000..a55b7fb
--- /dev/null
+++ b/Source/core/rendering/style/GridCoordinate.h
@@ -0,0 +1,79 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef GridCoordinate_h
+#define GridCoordinate_h
+
+#include "wtf/PassOwnPtr.h"
+
+namespace WebCore {
+
+// A span in a single direction (either rows or columns). Note that |initialPositionIndex|
+// and |finalPositionIndex| are grid areas' indexes, NOT grid lines'. Iterating over the
+// span should include both |initialPositionIndex| and |finalPositionIndex| to be correct.
+struct GridSpan {
+    static PassOwnPtr<GridSpan> create(size_t initialPosition, size_t finalPosition)
+    {
+        return adoptPtr(new GridSpan(initialPosition, finalPosition));
+    }
+
+    GridSpan(size_t initialPosition, size_t finalPosition)
+        : initialPositionIndex(initialPosition)
+        , finalPositionIndex(finalPosition)
+    {
+        ASSERT(initialPositionIndex <= finalPositionIndex);
+    }
+
+    size_t initialPositionIndex;
+    size_t finalPositionIndex;
+};
+
+// This represents a grid area that spans in both rows' and columns' direction.
+struct GridCoordinate {
+    // HashMap requires a default constuctor.
+    GridCoordinate()
+        : columns(0, 0)
+        , rows(0, 0)
+    {
+    }
+
+    GridCoordinate(const GridSpan& r, const GridSpan& c)
+        : columns(c)
+        , rows(r)
+    {
+    }
+
+    GridSpan columns;
+    GridSpan rows;
+};
+
+} // namespace WebCore
+
+#endif // GridCoordinate_h
diff --git a/Source/core/rendering/style/RenderStyle.cpp b/Source/core/rendering/style/RenderStyle.cpp
index 3b9f963..f8a4e32 100644
--- a/Source/core/rendering/style/RenderStyle.cpp
+++ b/Source/core/rendering/style/RenderStyle.cpp
@@ -1553,9 +1553,9 @@
     surround.access()->border.m_image.setOutset(outset);
 }
 
-ExclusionShapeValue* RenderStyle::initialShapeInside()
+ShapeValue* RenderStyle::initialShapeInside()
 {
-    DEFINE_STATIC_LOCAL(RefPtr<ExclusionShapeValue>, sOutsideValue, (ExclusionShapeValue::createOutsideValue()));
+    DEFINE_STATIC_LOCAL(RefPtr<ShapeValue>, sOutsideValue, (ShapeValue::createOutsideValue()));
     return sOutsideValue.get();
 }
 
diff --git a/Source/core/rendering/style/RenderStyle.h b/Source/core/rendering/style/RenderStyle.h
index ff5e92f..c31dfcf 100644
--- a/Source/core/rendering/style/RenderStyle.h
+++ b/Source/core/rendering/style/RenderStyle.h
@@ -46,13 +46,13 @@
 #include "core/rendering/style/BorderValue.h"
 #include "core/rendering/style/CounterDirectives.h"
 #include "core/rendering/style/DataRef.h"
-#include "core/rendering/style/ExclusionShapeValue.h"
 #include "core/rendering/style/LineClampValue.h"
 #include "core/rendering/style/NinePieceImage.h"
 #include "core/rendering/style/OutlineValue.h"
 #include "core/rendering/style/RenderStyleConstants.h"
 #include "core/rendering/style/SVGRenderStyle.h"
 #include "core/rendering/style/ShadowData.h"
+#include "core/rendering/style/ShapeValue.h"
 #include "core/rendering/style/StyleBackgroundData.h"
 #include "core/rendering/style/StyleBoxData.h"
 #include "core/rendering/style/StyleDeprecatedFlexibleBoxData.h"
@@ -739,18 +739,18 @@
     EFlexWrap flexWrap() const { return static_cast<EFlexWrap>(rareNonInheritedData->m_flexibleBox->m_flexWrap); }
     EJustifyContent justifyContent() const { return static_cast<EJustifyContent>(rareNonInheritedData->m_justifyContent); }
 
-    const Vector<GridTrackSize>& gridColumns() const { return rareNonInheritedData->m_grid->m_gridColumns; }
-    const Vector<GridTrackSize>& gridRows() const { return rareNonInheritedData->m_grid->m_gridRows; }
+    const Vector<GridTrackSize>& gridDefinitionColumns() const { return rareNonInheritedData->m_grid->m_gridDefinitionColumns; }
+    const Vector<GridTrackSize>& gridDefinitionRows() const { return rareNonInheritedData->m_grid->m_gridDefinitionRows; }
     const NamedGridLinesMap& namedGridColumnLines() const { return rareNonInheritedData->m_grid->m_namedGridColumnLines; }
     const NamedGridLinesMap& namedGridRowLines() const { return rareNonInheritedData->m_grid->m_namedGridRowLines; }
     GridAutoFlow gridAutoFlow() const { return rareNonInheritedData->m_grid->m_gridAutoFlow; }
     const GridTrackSize& gridAutoColumns() const { return rareNonInheritedData->m_grid->m_gridAutoColumns; }
     const GridTrackSize& gridAutoRows() const { return rareNonInheritedData->m_grid->m_gridAutoRows; }
 
-    const GridPosition& gridStart() const { return rareNonInheritedData->m_gridItem->m_gridStart; }
-    const GridPosition& gridEnd() const { return rareNonInheritedData->m_gridItem->m_gridEnd; }
-    const GridPosition& gridBefore() const { return rareNonInheritedData->m_gridItem->m_gridBefore; }
-    const GridPosition& gridAfter() const { return rareNonInheritedData->m_gridItem->m_gridAfter; }
+    const GridPosition& gridColumnStart() const { return rareNonInheritedData->m_gridItem->m_gridColumnStart; }
+    const GridPosition& gridColumnEnd() const { return rareNonInheritedData->m_gridItem->m_gridColumnEnd; }
+    const GridPosition& gridRowStart() const { return rareNonInheritedData->m_gridItem->m_gridRowStart; }
+    const GridPosition& gridRowEnd() const { return rareNonInheritedData->m_gridItem->m_gridRowEnd; }
 
     const ShadowData* boxShadow() const { return rareNonInheritedData->m_boxShadow.get(); }
     void getBoxShadowExtent(LayoutUnit& top, LayoutUnit& right, LayoutUnit& bottom, LayoutUnit& left) const { getShadowExtent(boxShadow(), top, right, bottom, left); }
@@ -1190,16 +1190,16 @@
     void setJustifyContent(EJustifyContent p) { SET_VAR(rareNonInheritedData, m_justifyContent, p); }
     void setGridAutoColumns(const GridTrackSize& length) { SET_VAR(rareNonInheritedData.access()->m_grid, m_gridAutoColumns, length); }
     void setGridAutoRows(const GridTrackSize& length) { SET_VAR(rareNonInheritedData.access()->m_grid, m_gridAutoRows, length); }
-    void setGridColumns(const Vector<GridTrackSize>& lengths) { SET_VAR(rareNonInheritedData.access()->m_grid, m_gridColumns, lengths); }
-    void setGridRows(const Vector<GridTrackSize>& lengths) { SET_VAR(rareNonInheritedData.access()->m_grid, m_gridRows, lengths); }
+    void setGridDefinitionColumns(const Vector<GridTrackSize>& lengths) { SET_VAR(rareNonInheritedData.access()->m_grid, m_gridDefinitionColumns, lengths); }
+    void setGridDefinitionRows(const Vector<GridTrackSize>& lengths) { SET_VAR(rareNonInheritedData.access()->m_grid, m_gridDefinitionRows, lengths); }
     void setNamedGridColumnLines(const NamedGridLinesMap& namedGridColumnLines) { SET_VAR(rareNonInheritedData.access()->m_grid, m_namedGridColumnLines, namedGridColumnLines); }
     void setNamedGridRowLines(const NamedGridLinesMap& namedGridRowLines) { SET_VAR(rareNonInheritedData.access()->m_grid, m_namedGridRowLines, namedGridRowLines); }
     void setGridAutoFlow(GridAutoFlow flow) { SET_VAR(rareNonInheritedData.access()->m_grid, m_gridAutoFlow, flow); }
 
-    void setGridStart(const GridPosition& startPosition) { SET_VAR(rareNonInheritedData.access()->m_gridItem, m_gridStart, startPosition); }
-    void setGridEnd(const GridPosition& endPosition) { SET_VAR(rareNonInheritedData.access()->m_gridItem, m_gridEnd, endPosition); }
-    void setGridBefore(const GridPosition& beforePosition) { SET_VAR(rareNonInheritedData.access()->m_gridItem, m_gridBefore, beforePosition); }
-    void setGridAfter(const GridPosition& afterPosition) { SET_VAR(rareNonInheritedData.access()->m_gridItem, m_gridAfter, afterPosition); }
+    void setGridColumnStart(const GridPosition& columnStartPosition) { SET_VAR(rareNonInheritedData.access()->m_gridItem, m_gridColumnStart, columnStartPosition); }
+    void setGridColumnEnd(const GridPosition& columnEndPosition) { SET_VAR(rareNonInheritedData.access()->m_gridItem, m_gridColumnEnd, columnEndPosition); }
+    void setGridRowStart(const GridPosition& rowStartPosition) { SET_VAR(rareNonInheritedData.access()->m_gridItem, m_gridRowStart, rowStartPosition); }
+    void setGridRowEnd(const GridPosition& rowEndPosition) { SET_VAR(rareNonInheritedData.access()->m_gridItem, m_gridRowEnd, rowEndPosition); }
 
     void setMarqueeIncrement(Length f) { SET_VAR(rareNonInheritedData.access()->m_marquee, increment, f); }
     void setMarqueeSpeed(int f) { SET_VAR(rareNonInheritedData.access()->m_marquee, speed, f); }
@@ -1349,31 +1349,31 @@
     SVGLength kerning() const { return svgStyle()->kerning(); }
     void setKerning(SVGLength k) { accessSVGStyle()->setKerning(k); }
 
-    void setShapeInside(PassRefPtr<ExclusionShapeValue> value)
+    void setShapeInside(PassRefPtr<ShapeValue> value)
     {
         if (rareNonInheritedData->m_shapeInside == value)
             return;
         rareNonInheritedData.access()->m_shapeInside = value;
     }
-    ExclusionShapeValue* shapeInside() const { return rareNonInheritedData->m_shapeInside.get(); }
-    ExclusionShapeValue* resolvedShapeInside() const
+    ShapeValue* shapeInside() const { return rareNonInheritedData->m_shapeInside.get(); }
+    ShapeValue* resolvedShapeInside() const
     {
-        ExclusionShapeValue* shapeInside = this->shapeInside();
-        if (shapeInside && shapeInside->type() == ExclusionShapeValue::Outside)
+        ShapeValue* shapeInside = this->shapeInside();
+        if (shapeInside && shapeInside->type() == ShapeValue::Outside)
             return shapeOutside();
         return shapeInside;
     }
 
-    void setShapeOutside(PassRefPtr<ExclusionShapeValue> value)
+    void setShapeOutside(PassRefPtr<ShapeValue> value)
     {
         if (rareNonInheritedData->m_shapeOutside == value)
             return;
         rareNonInheritedData.access()->m_shapeOutside = value;
     }
-    ExclusionShapeValue* shapeOutside() const { return rareNonInheritedData->m_shapeOutside.get(); }
+    ShapeValue* shapeOutside() const { return rareNonInheritedData->m_shapeOutside.get(); }
 
-    static ExclusionShapeValue* initialShapeInside();
-    static ExclusionShapeValue* initialShapeOutside() { return 0; }
+    static ShapeValue* initialShapeInside();
+    static ShapeValue* initialShapeOutside() { return 0; }
 
     void setClipPath(PassRefPtr<ClipPathOperation> operation)
     {
@@ -1595,8 +1595,8 @@
     static TouchAction initialTouchAction() { return TouchActionAuto; }
 
     // The initial value is 'none' for grid tracks.
-    static Vector<GridTrackSize> initialGridColumns() { return Vector<GridTrackSize>(); }
-    static Vector<GridTrackSize> initialGridRows() { return Vector<GridTrackSize>(); }
+    static Vector<GridTrackSize> initialGridDefinitionColumns() { return Vector<GridTrackSize>(); }
+    static Vector<GridTrackSize> initialGridDefinitionRows() { return Vector<GridTrackSize>(); }
 
     static GridAutoFlow initialGridAutoFlow() { return AutoFlowNone; }
 
@@ -1607,10 +1607,10 @@
     static NamedGridLinesMap initialNamedGridRowLines() { return NamedGridLinesMap(); }
 
     // 'auto' is the default.
-    static GridPosition initialGridStart() { return GridPosition(); }
-    static GridPosition initialGridEnd() { return GridPosition(); }
-    static GridPosition initialGridBefore() { return GridPosition(); }
-    static GridPosition initialGridAfter() { return GridPosition(); }
+    static GridPosition initialGridColumnStart() { return GridPosition(); }
+    static GridPosition initialGridColumnEnd() { return GridPosition(); }
+    static GridPosition initialGridRowStart() { return GridPosition(); }
+    static GridPosition initialGridRowEnd() { return GridPosition(); }
 
     static unsigned initialTabSize() { return 8; }
 
diff --git a/Source/core/rendering/style/RenderStyleConstants.h b/Source/core/rendering/style/RenderStyleConstants.h
index 9039098..7dd5c70 100644
--- a/Source/core/rendering/style/RenderStyleConstants.h
+++ b/Source/core/rendering/style/RenderStyleConstants.h
@@ -75,7 +75,7 @@
     SCROLLBAR_THUMB, SCROLLBAR_BUTTON, SCROLLBAR_TRACK, SCROLLBAR_TRACK_PIECE, SCROLLBAR_CORNER, RESIZER,
     INPUT_LIST_BUTTON,
     AFTER_LAST_INTERNAL_PSEUDOID,
-    FULL_SCREEN, FULL_SCREEN_DOCUMENT, FULL_SCREEN_ANCESTOR, ANIMATING_FULL_SCREEN_TRANSITION,
+    FULL_SCREEN, FULL_SCREEN_DOCUMENT, FULL_SCREEN_ANCESTOR,
     FIRST_PUBLIC_PSEUDOID = FIRST_LINE,
     FIRST_INTERNAL_PSEUDOID = SCROLLBAR_THUMB,
     PUBLIC_PSEUDOID_MASK = ((1 << FIRST_INTERNAL_PSEUDOID) - 1) & ~((1 << FIRST_PUBLIC_PSEUDOID) - 1)
diff --git a/Source/core/rendering/style/ExclusionShapeValue.h b/Source/core/rendering/style/ShapeValue.h
similarity index 67%
rename from Source/core/rendering/style/ExclusionShapeValue.h
rename to Source/core/rendering/style/ShapeValue.h
index c7ee9fa..b72d251 100644
--- a/Source/core/rendering/style/ExclusionShapeValue.h
+++ b/Source/core/rendering/style/ShapeValue.h
@@ -27,8 +27,8 @@
  * SUCH DAMAGE.
  */
 
-#ifndef ExclusionShapeValue_h
-#define ExclusionShapeValue_h
+#ifndef ShapeValue_h
+#define ShapeValue_h
 
 #include "core/rendering/style/BasicShapes.h"
 #include "core/rendering/style/StyleImage.h"
@@ -36,31 +36,31 @@
 
 namespace WebCore {
 
-class ExclusionShapeValue : public RefCounted<ExclusionShapeValue> {
+class ShapeValue : public RefCounted<ShapeValue> {
 public:
-    enum ExclusionShapeValueType {
-        // The Auto value is defined by a null ExclusionShapeValue*
+    enum ShapeValueType {
+        // The Auto value is defined by a null ShapeValue*
         Shape,
         Outside,
         Image
     };
 
-    static PassRefPtr<ExclusionShapeValue> createShapeValue(PassRefPtr<BasicShape> shape)
+    static PassRefPtr<ShapeValue> createShapeValue(PassRefPtr<BasicShape> shape)
     {
-        return adoptRef(new ExclusionShapeValue(shape));
+        return adoptRef(new ShapeValue(shape));
     }
 
-    static PassRefPtr<ExclusionShapeValue> createOutsideValue()
+    static PassRefPtr<ShapeValue> createOutsideValue()
     {
-        return adoptRef(new ExclusionShapeValue(Outside));
+        return adoptRef(new ShapeValue(Outside));
     }
 
-    static PassRefPtr<ExclusionShapeValue> createImageValue(PassRefPtr<StyleImage> image)
+    static PassRefPtr<ShapeValue> createImageValue(PassRefPtr<StyleImage> image)
     {
-        return adoptRef(new ExclusionShapeValue(image));
+        return adoptRef(new ShapeValue(image));
     }
 
-    ExclusionShapeValueType type() const { return m_type; }
+    ShapeValueType type() const { return m_type; }
     BasicShape* shape() const { return m_shape.get(); }
     StyleImage* image() const { return m_image.get(); }
     void setImage(PassRefPtr<StyleImage> image)
@@ -68,24 +68,24 @@
         if (m_image != image)
             m_image = image;
     }
-    bool operator==(const ExclusionShapeValue& other) const { return type() == other.type(); }
+    bool operator==(const ShapeValue& other) const { return type() == other.type(); }
 
 private:
-    ExclusionShapeValue(PassRefPtr<BasicShape> shape)
+    ShapeValue(PassRefPtr<BasicShape> shape)
         : m_type(Shape)
         , m_shape(shape)
     {
     }
-    ExclusionShapeValue(ExclusionShapeValueType type)
+    ShapeValue(ShapeValueType type)
         : m_type(type)
     {
     }
-    ExclusionShapeValue(PassRefPtr<StyleImage> image)
+    ShapeValue(PassRefPtr<StyleImage> image)
         : m_type(Image)
         , m_image(image)
     {
     }
-    ExclusionShapeValueType m_type;
+    ShapeValueType m_type;
     RefPtr<BasicShape> m_shape;
     RefPtr<StyleImage> m_image;
 };
diff --git a/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp b/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp
index 90d43b0..be1d79a 100644
--- a/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp
+++ b/Source/core/rendering/style/StyleCustomFilterProgramCache.cpp
@@ -43,8 +43,9 @@
         program->programType(), program->mixSettings(), program->meshType());
 }
 
-StyleCustomFilterProgramCache::StyleCustomFilterProgramCache()
+PassOwnPtr<StyleCustomFilterProgramCache> StyleCustomFilterProgramCache::create()
 {
+    return adoptPtr(new StyleCustomFilterProgramCache());
 }
 
 StyleCustomFilterProgramCache::~StyleCustomFilterProgramCache()
diff --git a/Source/core/rendering/style/StyleCustomFilterProgramCache.h b/Source/core/rendering/style/StyleCustomFilterProgramCache.h
index eb30517..999ecb2 100644
--- a/Source/core/rendering/style/StyleCustomFilterProgramCache.h
+++ b/Source/core/rendering/style/StyleCustomFilterProgramCache.h
@@ -42,7 +42,7 @@
 class StyleCustomFilterProgramCache {
     WTF_MAKE_FAST_ALLOCATED;
 public:
-    StyleCustomFilterProgramCache();
+    static PassOwnPtr<StyleCustomFilterProgramCache> create();
     ~StyleCustomFilterProgramCache();
 
     // Lookups a StyleCustomFilterProgram that has similar parameters with the specified program.
@@ -53,6 +53,8 @@
     void remove(StyleCustomFilterProgram*);
 
 private:
+    StyleCustomFilterProgramCache() { }
+
     typedef HashMap<CustomFilterProgramInfo, StyleCustomFilterProgram*> CacheMap;
     CacheMap m_cache;
 };
diff --git a/Source/core/rendering/style/StyleGridData.cpp b/Source/core/rendering/style/StyleGridData.cpp
index 84511e8..5a11326 100644
--- a/Source/core/rendering/style/StyleGridData.cpp
+++ b/Source/core/rendering/style/StyleGridData.cpp
@@ -31,8 +31,8 @@
 namespace WebCore {
 
 StyleGridData::StyleGridData()
-    : m_gridColumns(RenderStyle::initialGridColumns())
-    , m_gridRows(RenderStyle::initialGridRows())
+    : m_gridDefinitionColumns(RenderStyle::initialGridDefinitionColumns())
+    , m_gridDefinitionRows(RenderStyle::initialGridDefinitionRows())
     , m_gridAutoFlow(RenderStyle::initialGridAutoFlow())
     , m_gridAutoRows(RenderStyle::initialGridAutoRows())
     , m_gridAutoColumns(RenderStyle::initialGridAutoColumns())
@@ -43,8 +43,8 @@
 
 StyleGridData::StyleGridData(const StyleGridData& o)
     : RefCounted<StyleGridData>()
-    , m_gridColumns(o.m_gridColumns)
-    , m_gridRows(o.m_gridRows)
+    , m_gridDefinitionColumns(o.m_gridDefinitionColumns)
+    , m_gridDefinitionRows(o.m_gridDefinitionRows)
     , m_namedGridColumnLines(o.m_namedGridColumnLines)
     , m_namedGridRowLines(o.m_namedGridRowLines)
     , m_gridAutoFlow(o.m_gridAutoFlow)
diff --git a/Source/core/rendering/style/StyleGridData.h b/Source/core/rendering/style/StyleGridData.h
index 4ff9175..3b602ad 100644
--- a/Source/core/rendering/style/StyleGridData.h
+++ b/Source/core/rendering/style/StyleGridData.h
@@ -44,7 +44,7 @@
 
     bool operator==(const StyleGridData& o) const
     {
-        return m_gridColumns == o.m_gridColumns && m_gridRows == o.m_gridRows && m_gridAutoFlow == o.m_gridAutoFlow && m_gridAutoRows == o.m_gridAutoRows && m_gridAutoColumns == o.m_gridAutoColumns && m_namedGridColumnLines == o.m_namedGridColumnLines && m_namedGridRowLines == o.m_namedGridRowLines;
+        return m_gridDefinitionColumns == o.m_gridDefinitionColumns && m_gridDefinitionRows == o.m_gridDefinitionRows && m_gridAutoFlow == o.m_gridAutoFlow && m_gridAutoRows == o.m_gridAutoRows && m_gridAutoColumns == o.m_gridAutoColumns && m_namedGridColumnLines == o.m_namedGridColumnLines && m_namedGridRowLines == o.m_namedGridRowLines;
     }
 
     bool operator!=(const StyleGridData& o) const
@@ -52,9 +52,8 @@
         return !(*this == o);
     }
 
-    // FIXME: Update the naming of the following variables.
-    Vector<GridTrackSize> m_gridColumns;
-    Vector<GridTrackSize> m_gridRows;
+    Vector<GridTrackSize> m_gridDefinitionColumns;
+    Vector<GridTrackSize> m_gridDefinitionRows;
 
     NamedGridLinesMap m_namedGridColumnLines;
     NamedGridLinesMap m_namedGridRowLines;
diff --git a/Source/core/rendering/style/StyleGridItemData.cpp b/Source/core/rendering/style/StyleGridItemData.cpp
index ea93804..3dd830d 100644
--- a/Source/core/rendering/style/StyleGridItemData.cpp
+++ b/Source/core/rendering/style/StyleGridItemData.cpp
@@ -35,19 +35,19 @@
 namespace WebCore {
 
 StyleGridItemData::StyleGridItemData()
-    : m_gridStart(RenderStyle::initialGridStart())
-    , m_gridEnd(RenderStyle::initialGridEnd())
-    , m_gridBefore(RenderStyle::initialGridBefore())
-    , m_gridAfter(RenderStyle::initialGridAfter())
+    : m_gridColumnStart(RenderStyle::initialGridColumnStart())
+    , m_gridColumnEnd(RenderStyle::initialGridColumnEnd())
+    , m_gridRowStart(RenderStyle::initialGridRowStart())
+    , m_gridRowEnd(RenderStyle::initialGridRowEnd())
 {
 }
 
 StyleGridItemData::StyleGridItemData(const StyleGridItemData& o)
     : RefCounted<StyleGridItemData>()
-    , m_gridStart(o.m_gridStart)
-    , m_gridEnd(o.m_gridEnd)
-    , m_gridBefore(o.m_gridBefore)
-    , m_gridAfter(o.m_gridAfter)
+    , m_gridColumnStart(o.m_gridColumnStart)
+    , m_gridColumnEnd(o.m_gridColumnEnd)
+    , m_gridRowStart(o.m_gridRowStart)
+    , m_gridRowEnd(o.m_gridRowEnd)
 {
 }
 
diff --git a/Source/core/rendering/style/StyleGridItemData.h b/Source/core/rendering/style/StyleGridItemData.h
index d68ffd4..76214b5 100644
--- a/Source/core/rendering/style/StyleGridItemData.h
+++ b/Source/core/rendering/style/StyleGridItemData.h
@@ -46,8 +46,8 @@
 
     bool operator==(const StyleGridItemData& o) const
     {
-        return m_gridStart == o.m_gridStart && m_gridEnd == o.m_gridEnd
-            && m_gridBefore == o.m_gridBefore && m_gridAfter == o.m_gridAfter;
+        return m_gridColumnStart == o.m_gridColumnStart && m_gridColumnEnd == o.m_gridColumnEnd
+            && m_gridRowStart == o.m_gridRowStart && m_gridRowEnd == o.m_gridRowEnd;
     }
 
     bool operator!=(const StyleGridItemData& o) const
@@ -55,10 +55,10 @@
         return !(*this == o);
     }
 
-    GridPosition m_gridStart;
-    GridPosition m_gridEnd;
-    GridPosition m_gridBefore;
-    GridPosition m_gridAfter;
+    GridPosition m_gridColumnStart;
+    GridPosition m_gridColumnEnd;
+    GridPosition m_gridRowStart;
+    GridPosition m_gridRowEnd;
 
 private:
     StyleGridItemData();
diff --git a/Source/core/rendering/style/StyleRareNonInheritedData.h b/Source/core/rendering/style/StyleRareNonInheritedData.h
index e092771..bf42f544 100644
--- a/Source/core/rendering/style/StyleRareNonInheritedData.h
+++ b/Source/core/rendering/style/StyleRareNonInheritedData.h
@@ -30,13 +30,13 @@
 #include "core/rendering/style/CounterDirectives.h"
 #include "core/rendering/style/CursorData.h"
 #include "core/rendering/style/DataRef.h"
-#include "core/rendering/style/ExclusionShapeValue.h"
 #include "core/rendering/style/FillLayer.h"
 #include "core/rendering/style/LineClampValue.h"
 #include "core/rendering/style/NinePieceImage.h"
-#include <wtf/OwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/Vector.h>
+#include "core/rendering/style/ShapeValue.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/Vector.h"
 
 namespace WebCore {
 
@@ -125,8 +125,8 @@
 
     LengthSize m_pageSize;
 
-    RefPtr<ExclusionShapeValue> m_shapeInside;
-    RefPtr<ExclusionShapeValue> m_shapeOutside;
+    RefPtr<ShapeValue> m_shapeInside;
+    RefPtr<ShapeValue> m_shapeOutside;
     Length m_shapeMargin;
     Length m_shapePadding;
 
diff --git a/Source/core/rendering/svg/RenderSVGBlock.h b/Source/core/rendering/svg/RenderSVGBlock.h
index 72a57c7..4468a20 100644
--- a/Source/core/rendering/svg/RenderSVGBlock.h
+++ b/Source/core/rendering/svg/RenderSVGBlock.h
@@ -39,6 +39,8 @@
     virtual void setStyle(PassRefPtr<RenderStyle>) OVERRIDE FINAL;
     virtual void updateFromStyle() OVERRIDE FINAL;
 
+    virtual bool isRenderSVGBlock() const OVERRIDE FINAL { return true; };
+
     virtual void absoluteRects(Vector<IntRect>&, const LayoutPoint& accumulatedOffset) const OVERRIDE FINAL;
 
     virtual void styleWillChange(StyleDifference, const RenderStyle* newStyle) OVERRIDE FINAL;
diff --git a/Source/core/rendering/svg/RenderSVGEllipse.cpp b/Source/core/rendering/svg/RenderSVGEllipse.cpp
index 980a355..be5ea3f 100644
--- a/Source/core/rendering/svg/RenderSVGEllipse.cpp
+++ b/Source/core/rendering/svg/RenderSVGEllipse.cpp
@@ -34,7 +34,7 @@
 
 namespace WebCore {
 
-RenderSVGEllipse::RenderSVGEllipse(SVGStyledTransformableElement* node)
+RenderSVGEllipse::RenderSVGEllipse(SVGGraphicsElement* node)
     : RenderSVGShape(node)
     , m_usePathFallback(false)
 {
diff --git a/Source/core/rendering/svg/RenderSVGEllipse.h b/Source/core/rendering/svg/RenderSVGEllipse.h
index bbf85c3..f06e5c1 100644
--- a/Source/core/rendering/svg/RenderSVGEllipse.h
+++ b/Source/core/rendering/svg/RenderSVGEllipse.h
@@ -33,7 +33,7 @@
 
 class RenderSVGEllipse FINAL : public RenderSVGShape {
 public:
-    explicit RenderSVGEllipse(SVGStyledTransformableElement*);
+    explicit RenderSVGEllipse(SVGGraphicsElement*);
     virtual ~RenderSVGEllipse();
 
 private:
diff --git a/Source/core/rendering/svg/RenderSVGInlineText.cpp b/Source/core/rendering/svg/RenderSVGInlineText.cpp
index 6b620aa..865e569 100644
--- a/Source/core/rendering/svg/RenderSVGInlineText.cpp
+++ b/Source/core/rendering/svg/RenderSVGInlineText.cpp
@@ -179,7 +179,7 @@
         if (!box->isSVGInlineTextBox())
             continue;
 
-        SVGInlineTextBox* textBox = static_cast<SVGInlineTextBox*>(box);
+        SVGInlineTextBox* textBox = toSVGInlineTextBox(box);
         Vector<SVGTextFragment>& fragments = textBox->textFragments();
 
         unsigned textFragmentsSize = fragments.size();
diff --git a/Source/core/rendering/svg/RenderSVGPath.cpp b/Source/core/rendering/svg/RenderSVGPath.cpp
index ce8b421..0eadbf9 100644
--- a/Source/core/rendering/svg/RenderSVGPath.cpp
+++ b/Source/core/rendering/svg/RenderSVGPath.cpp
@@ -34,7 +34,7 @@
 
 namespace WebCore {
 
-RenderSVGPath::RenderSVGPath(SVGStyledTransformableElement* node)
+RenderSVGPath::RenderSVGPath(SVGGraphicsElement* node)
     : RenderSVGShape(node)
 {
 }
diff --git a/Source/core/rendering/svg/RenderSVGPath.h b/Source/core/rendering/svg/RenderSVGPath.h
index 4f33b44..5d83f86 100644
--- a/Source/core/rendering/svg/RenderSVGPath.h
+++ b/Source/core/rendering/svg/RenderSVGPath.h
@@ -32,7 +32,7 @@
 
 class RenderSVGPath FINAL : public RenderSVGShape {
 public:
-    explicit RenderSVGPath(SVGStyledTransformableElement*);
+    explicit RenderSVGPath(SVGGraphicsElement*);
     virtual ~RenderSVGPath();
 
 private:
diff --git a/Source/core/rendering/svg/RenderSVGResourceClipper.cpp b/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
index f2c6834..d9da9fb 100644
--- a/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceClipper.cpp
@@ -100,9 +100,9 @@
         // Only shapes or paths are supported for direct clipping. We need to fallback to masking for texts.
         if (renderer->isSVGText())
             return false;
-        if (!childNode->isSVGElement() || !toSVGElement(childNode)->isStyledTransformable())
+        if (!childNode->isSVGElement() || !toSVGElement(childNode)->isSVGGraphicsElement())
             continue;
-        SVGStyledTransformableElement* styled = toSVGStyledTransformableElement(childNode);
+        SVGGraphicsElement* styled = toSVGGraphicsElement(childNode);
         RenderStyle* style = renderer->style();
         if (!style || style->display() == NONE || style->visibility() != VISIBLE)
              continue;
diff --git a/Source/core/rendering/svg/RenderSVGResourceContainer.cpp b/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
index 1905445..f60b32b 100644
--- a/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
+++ b/Source/core/rendering/svg/RenderSVGResourceContainer.cpp
@@ -26,7 +26,7 @@
 #include "core/rendering/svg/RenderSVGRoot.h"
 #include "core/rendering/svg/SVGRenderingContext.h"
 #include "core/rendering/svg/SVGResourcesCache.h"
-#include "core/svg/SVGStyledTransformableElement.h"
+#include "core/svg/SVGGraphicsElement.h"
 
 namespace WebCore {
 
@@ -218,7 +218,7 @@
     if (!object->isSVGShape())
         return resourceTransform;
 
-    SVGStyledTransformableElement* element = toSVGStyledTransformableElement(object->node());
+    SVGGraphicsElement* element = toSVGGraphicsElement(object->node());
     AffineTransform transform = element->getScreenCTM(SVGLocatable::DisallowStyleUpdate);
     transform *= resourceTransform;
     return transform;
diff --git a/Source/core/rendering/svg/RenderSVGShape.cpp b/Source/core/rendering/svg/RenderSVGShape.cpp
index aed12c3..f84b85e 100644
--- a/Source/core/rendering/svg/RenderSVGShape.cpp
+++ b/Source/core/rendering/svg/RenderSVGShape.cpp
@@ -40,16 +40,16 @@
 #include "core/rendering/svg/SVGRenderingContext.h"
 #include "core/rendering/svg/SVGResources.h"
 #include "core/rendering/svg/SVGResourcesCache.h"
-#include "core/svg/SVGStyledTransformableElement.h"
+#include "core/svg/SVGGraphicsElement.h"
 #include <wtf/MathExtras.h>
 
 namespace WebCore {
 
-RenderSVGShape::RenderSVGShape(SVGStyledTransformableElement* node)
+RenderSVGShape::RenderSVGShape(SVGGraphicsElement* node)
     : RenderSVGModelObject(node)
     , m_needsBoundariesUpdate(false) // Default is false, the cached rects are empty from the beginning.
-    , m_needsShapeUpdate(true) // Default is true, so we grab a Path object once from SVGStyledTransformableElement.
-    , m_needsTransformUpdate(true) // Default is true, so we grab a AffineTransform object once from SVGStyledTransformableElement.
+    , m_needsShapeUpdate(true) // Default is true, so we grab a Path object once from SVGGraphicsElement.
+    , m_needsTransformUpdate(true) // Default is true, so we grab a AffineTransform object once from SVGGraphicsElement.
 {
 }
 
@@ -63,7 +63,7 @@
     m_path = adoptPtr(new Path);
     ASSERT(RenderSVGShape::isEmpty());
 
-    SVGStyledTransformableElement* element = toSVGStyledTransformableElement(node());
+    SVGGraphicsElement* element = toSVGGraphicsElement(node());
     updatePathFromGraphicsElement(element, path());
     processMarkerPositions();
 
@@ -141,7 +141,7 @@
 {
     StackStats::LayoutCheckPoint layoutCheckPoint;
     LayoutRepainter repainter(*this, SVGRenderSupport::checkForSVGRepaintDuringLayout(this) && selfNeedsLayout());
-    SVGStyledTransformableElement* element = toSVGStyledTransformableElement(node());
+    SVGGraphicsElement* element = toSVGGraphicsElement(node());
 
     bool updateCachedBoundariesInParents = false;
 
@@ -193,7 +193,7 @@
 
 AffineTransform RenderSVGShape::nonScalingStrokeTransform() const
 {
-    SVGStyledTransformableElement* element = toSVGStyledTransformableElement(node());
+    SVGGraphicsElement* element = toSVGGraphicsElement(node());
     return element->getScreenCTM(SVGLocatable::DisallowStyleUpdate);
 }
 
@@ -202,7 +202,7 @@
     if (!style()->svgStyle()->hasMarkers())
         return false;
 
-    SVGStyledTransformableElement* element = toSVGStyledTransformableElement(node());
+    SVGGraphicsElement* element = toSVGGraphicsElement(node());
     if (!element->supportsMarkers())
         return false;
 
diff --git a/Source/core/rendering/svg/RenderSVGShape.h b/Source/core/rendering/svg/RenderSVGShape.h
index e2645f6..5c01796 100644
--- a/Source/core/rendering/svg/RenderSVGShape.h
+++ b/Source/core/rendering/svg/RenderSVGShape.h
@@ -40,12 +40,12 @@
 class RenderSVGContainer;
 class RenderSVGPath;
 class RenderSVGResource;
-class SVGStyledTransformableElement;
+class SVGGraphicsElement;
 
 class RenderSVGShape : public RenderSVGModelObject {
 public:
-    explicit RenderSVGShape(SVGStyledTransformableElement*);
-    RenderSVGShape(SVGStyledTransformableElement*, Path*, bool);
+    explicit RenderSVGShape(SVGGraphicsElement*);
+    RenderSVGShape(SVGGraphicsElement*, Path*, bool);
     virtual ~RenderSVGShape();
 
     void setNeedsShapeUpdate() { m_needsShapeUpdate = true; }
diff --git a/Source/core/rendering/svg/RenderSVGTransformableContainer.cpp b/Source/core/rendering/svg/RenderSVGTransformableContainer.cpp
index b2eef63..2a29b00 100644
--- a/Source/core/rendering/svg/RenderSVGTransformableContainer.cpp
+++ b/Source/core/rendering/svg/RenderSVGTransformableContainer.cpp
@@ -25,12 +25,12 @@
 
 #include "SVGNames.h"
 #include "core/rendering/svg/SVGRenderSupport.h"
-#include "core/svg/SVGStyledTransformableElement.h"
+#include "core/svg/SVGGraphicsElement.h"
 #include "core/svg/SVGUseElement.h"
 
 namespace WebCore {
     
-RenderSVGTransformableContainer::RenderSVGTransformableContainer(SVGStyledTransformableElement* node)
+RenderSVGTransformableContainer::RenderSVGTransformableContainer(SVGGraphicsElement* node)
     : RenderSVGContainer(node)
     , m_needsTransformUpdate(true)
     , m_didTransformToRootUpdate(false)
@@ -39,7 +39,7 @@
 
 bool RenderSVGTransformableContainer::calculateLocalTransform()
 {
-    SVGStyledTransformableElement* element = toSVGStyledTransformableElement(node());
+    SVGGraphicsElement* element = toSVGGraphicsElement(node());
 
     // If we're either the renderer for a <use> element, or for any <g> element inside the shadow
     // tree, that was created during the use/symbol/svg expansion in SVGUseElement. These containers
diff --git a/Source/core/rendering/svg/RenderSVGTransformableContainer.h b/Source/core/rendering/svg/RenderSVGTransformableContainer.h
index 5833207..e6f8ef4 100644
--- a/Source/core/rendering/svg/RenderSVGTransformableContainer.h
+++ b/Source/core/rendering/svg/RenderSVGTransformableContainer.h
@@ -25,10 +25,10 @@
 
 namespace WebCore {
     
-class SVGStyledTransformableElement;
+class SVGGraphicsElement;
 class RenderSVGTransformableContainer FINAL : public RenderSVGContainer {
 public:
-    explicit RenderSVGTransformableContainer(SVGStyledTransformableElement*);
+    explicit RenderSVGTransformableContainer(SVGGraphicsElement*);
 
     virtual bool isSVGTransformableContainer() const { return true; }
     virtual const AffineTransform& localToParentTransform() const { return m_localTransform; }
diff --git a/Source/core/rendering/svg/SVGInlineFlowBox.cpp b/Source/core/rendering/svg/SVGInlineFlowBox.cpp
index 71303d6..b93687a 100644
--- a/Source/core/rendering/svg/SVGInlineFlowBox.cpp
+++ b/Source/core/rendering/svg/SVGInlineFlowBox.cpp
@@ -41,7 +41,7 @@
     PaintInfo childPaintInfo(paintInfo);
     for (InlineBox* child = firstChild(); child; child = child->nextOnLine()) {
         if (child->isSVGInlineTextBox())
-            static_cast<SVGInlineTextBox*>(child)->paintSelectionBackground(childPaintInfo);
+            toSVGInlineTextBox(child)->paintSelectionBackground(childPaintInfo);
         else if (child->isSVGInlineFlowBox())
             static_cast<SVGInlineFlowBox*>(child)->paintSelectionBackground(childPaintInfo);
     }
@@ -59,7 +59,7 @@
     if (renderingContext.isRenderingPrepared()) {
         for (InlineBox* child = firstChild(); child; child = child->nextOnLine()) {
             if (child->isSVGInlineTextBox())
-                computeTextMatchMarkerRectForRenderer(toRenderSVGInlineText(static_cast<SVGInlineTextBox*>(child)->textRenderer()));
+                computeTextMatchMarkerRectForRenderer(toRenderSVGInlineText(toSVGInlineTextBox(child)->textRenderer()));
 
             child->paint(paintInfo, LayoutPoint(), 0, 0);
         }
@@ -105,7 +105,7 @@
             if (!box->isSVGInlineTextBox())
                 continue;
 
-            SVGInlineTextBox* textBox = static_cast<SVGInlineTextBox*>(box);
+            SVGInlineTextBox* textBox = toSVGInlineTextBox(box);
 
             int markerStartPosition = max<int>(marker->startOffset() - textBox->start(), 0);
             int markerEndPosition = min<int>(marker->endOffset() - textBox->start(), textBox->len());
diff --git a/Source/core/rendering/svg/SVGInlineTextBox.h b/Source/core/rendering/svg/SVGInlineTextBox.h
index 5ef6a9a..bd85d3f 100644
--- a/Source/core/rendering/svg/SVGInlineTextBox.h
+++ b/Source/core/rendering/svg/SVGInlineTextBox.h
@@ -88,6 +88,12 @@
     Vector<SVGTextFragment> m_textFragments;
 };
 
+inline SVGInlineTextBox* toSVGInlineTextBox(InlineBox* box)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!box || box->isSVGInlineTextBox());
+    return static_cast<SVGInlineTextBox*>(box);
+}
+
 } // namespace WebCore
 
 #endif // SVGInlineTextBox_h
diff --git a/Source/core/rendering/svg/SVGRenderTreeAsText.cpp b/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
index 82931bb..952b085 100644
--- a/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
+++ b/Source/core/rendering/svg/SVGRenderTreeAsText.cpp
@@ -450,7 +450,7 @@
         if (!box->isSVGInlineTextBox())
             continue;
 
-        writeSVGInlineTextBox(ts, static_cast<SVGInlineTextBox*>(box), indent);
+        writeSVGInlineTextBox(ts, toSVGInlineTextBox(box), indent);
     }
 }
 
diff --git a/Source/core/rendering/svg/SVGRootInlineBox.cpp b/Source/core/rendering/svg/SVGRootInlineBox.cpp
index e14d299..03b364b 100644
--- a/Source/core/rendering/svg/SVGRootInlineBox.cpp
+++ b/Source/core/rendering/svg/SVGRootInlineBox.cpp
@@ -48,7 +48,7 @@
     if (hasSelection) {
         for (InlineBox* child = firstChild(); child; child = child->nextOnLine()) {
             if (child->isSVGInlineTextBox())
-                static_cast<SVGInlineTextBox*>(child)->paintSelectionBackground(childPaintInfo);
+                toSVGInlineTextBox(child)->paintSelectionBackground(childPaintInfo);
             else if (child->isSVGInlineFlowBox())
                 static_cast<SVGInlineFlowBox*>(child)->paintSelectionBackground(childPaintInfo);
         }
@@ -58,7 +58,7 @@
     if (renderingContext.isRenderingPrepared()) {
         for (InlineBox* child = firstChild(); child; child = child->nextOnLine()) {
             if (child->isSVGInlineTextBox())
-                SVGInlineFlowBox::computeTextMatchMarkerRectForRenderer(toRenderSVGInlineText(static_cast<SVGInlineTextBox*>(child)->textRenderer()));
+                SVGInlineFlowBox::computeTextMatchMarkerRectForRenderer(toRenderSVGInlineText(toSVGInlineTextBox(child)->textRenderer()));
 
             child->paint(paintInfo, LayoutPoint(), 0, 0);
         }
@@ -105,9 +105,7 @@
         if (child->isSVGInlineTextBox()) {
             ASSERT(child->renderer());
             ASSERT(child->renderer()->isSVGInlineText());
-
-            SVGInlineTextBox* textBox = static_cast<SVGInlineTextBox*>(child);
-            characterLayout.layoutInlineTextBox(textBox);
+            characterLayout.layoutInlineTextBox(toSVGInlineTextBox(child));
         } else {
             // Skip generated content.
             Node* node = child->renderer()->node();
@@ -143,7 +141,7 @@
             ASSERT(child->renderer());
             ASSERT(child->renderer()->isSVGInlineText());
 
-            SVGInlineTextBox* textBox = static_cast<SVGInlineTextBox*>(child);
+            SVGInlineTextBox* textBox = toSVGInlineTextBox(child);
             boxRect = textBox->calculateBoundaries();
             textBox->setX(boxRect.x());
             textBox->setY(boxRect.y());
@@ -283,8 +281,8 @@
             continue;
         }
 
-        SVGInlineTextBox* firstTextBox = static_cast<SVGInlineTextBox*>(*first);
-        SVGInlineTextBox* lastTextBox = static_cast<SVGInlineTextBox*>(*last);
+        SVGInlineTextBox* firstTextBox = toSVGInlineTextBox(*first);
+        SVGInlineTextBox* lastTextBox = toSVGInlineTextBox(*last);
 
         // Reordering is only necessary for BiDi text that is _absolutely_ positioned.
         if (firstTextBox->len() == 1 && firstTextBox->len() == lastTextBox->len()) {
diff --git a/Source/core/rendering/svg/SVGTextQuery.cpp b/Source/core/rendering/svg/SVGTextQuery.cpp
index 1166d35..c871f3b 100644
--- a/Source/core/rendering/svg/SVGTextQuery.cpp
+++ b/Source/core/rendering/svg/SVGTextQuery.cpp
@@ -99,7 +99,7 @@
         }
 
         if (child->isSVGInlineTextBox())
-            m_textBoxes.append(static_cast<SVGInlineTextBox*>(child));
+            m_textBoxes.append(toSVGInlineTextBox(child));
     }
 }
 
diff --git a/Source/core/scripts/StaticString.pm b/Source/core/scripts/StaticString.pm
index 11b6b78..99dfe2e 100644
--- a/Source/core/scripts/StaticString.pm
+++ b/Source/core/scripts/StaticString.pm
@@ -35,7 +35,7 @@
 
     while ( my ($name, $value) = each %strings ) {
         my $characterList = join("', '", split("", $value));
-        push(@result, "static const UChar ${name}String16[] = { '$characterList', 0 };\n");
+        push(@result, "static const UChar ${name}String16[] = { '$characterList' };\n");
     }
 
     push(@result, "\n");
diff --git a/Source/core/scripts/in_file.py b/Source/core/scripts/in_file.py
index 39a016b..d8d8235 100644
--- a/Source/core/scripts/in_file.py
+++ b/Source/core/scripts/in_file.py
@@ -75,6 +75,7 @@
 
     def _parse(self, lines):
         parsing_parameters = True
+        indices = {}
         for line in lines:
             if _is_comment(line):
                 continue
@@ -84,7 +85,40 @@
             if parsing_parameters:
                 self._parse_parameter(line)
             else:
-                self.name_dictionaries.append(self._parse_line(line))
+                entry = self._parse_line(line)
+                name = entry['name']
+                if name in indices:
+                    entry = self._merge_entries(entry, self.name_dictionaries[indices[name]])
+                    entry['name'] = name
+                    self.name_dictionaries[indices[name]] = entry
+                else:
+                    indices[name] = len(self.name_dictionaries)
+                    self.name_dictionaries.append(entry)
+
+
+    def _merge_entries(self, one, two):
+        merged = {}
+        for key in one:
+            if key not in two:
+                self._fatal("Expected key '%s' not found in entry: %s" % (key, two))
+            if one[key] and two[key]:
+                val_one = one[key]
+                val_two = two[key]
+                if isinstance(val_one, list) and isinstance(val_two, list):
+                    val = val_one + val_two
+                elif isinstance(val_one, list):
+                    val = val_one + [val_two]
+                elif isinstance(val_two, list):
+                    val = [val_one] + val_two
+                else:
+                    val = [val_one, val_two]
+                merged[key] = val
+            elif one[key]:
+                merged[key] = one[key]
+            else:
+                merged[key] = two[key]
+        return merged
+
 
     def _parse_parameter(self, line):
         if '=' in line:
diff --git a/Source/core/scripts/make_dom_exceptions.py b/Source/core/scripts/make_dom_exceptions.py
deleted file mode 100755
index 28609d7..0000000
--- a/Source/core/scripts/make_dom_exceptions.py
+++ /dev/null
@@ -1,165 +0,0 @@
-#!/usr/bin/env python
-# Copyright (C) 2013 Google Inc. All rights reserved.
-#
-# Redistribution and use in source and binary forms, with or without
-# modification, are permitted provided that the following conditions are
-# met:
-#
-#     * Redistributions of source code must retain the above copyright
-# notice, this list of conditions and the following disclaimer.
-#     * Redistributions in binary form must reproduce the above
-# copyright notice, this list of conditions and the following disclaimer
-# in the documentation and/or other materials provided with the
-# distribution.
-#     * Neither the name of Google Inc. nor the names of its
-# contributors may be used to endorse or promote products derived from
-# this software without specific prior written permission.
-#
-# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
-# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
-# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
-# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
-# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
-# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
-# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
-# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
-# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-
-import os.path
-import sys
-import shutil
-
-from in_file import InFile
-import name_macros
-import license
-
-
-HEADER_TEMPLATE = """%(license)s
-
-#ifndef %(class_name)s_h
-#define %(class_name)s_h
-
-namespace WebCore {
-
-typedef int ExceptionCode;
-
-enum ExceptionType {
-%(exception_types)s
-};
-
-struct ExceptionCodeDescription {
-    explicit ExceptionCodeDescription(ExceptionCode);
-
-    // |typeName| has spaces and is suitable for use in exception
-    // description strings; maximum length is 10 characters.
-    const char* typeName;
-
-    // |name| is the exception name, also intended for use in exception
-    // description strings; 0 if name not known; maximum length is 27
-    // characters.
-    const char* name;
-
-    // |description| is the exception description, intended for use in
-    // exception strings. It is a more readable explanation of error.
-    const char* description;
-
-    // |code| is the numeric value of the exception within a particular type.
-    int code;
-
-    ExceptionType type;
-};
-
-} // namespace WebCore
-
-#endif // %(class_name)s_h
-"""
-
-
-IMPLEMENTATION_TEMPLATE = """%(license)s
-
-#include "config.h"
-#include "%(class_name)s.h"
-
-#include "ExceptionCode.h"
-
-%(includes)s
-
-#include "modules/indexeddb/IDBDatabaseException.h"
-
-namespace WebCore {
-
-ExceptionCodeDescription::ExceptionCodeDescription(ExceptionCode ec)
-{
-    ASSERT(ec);
-
-%(description_initalizations)s
-
-    // FIXME: This special case for IDB is undesirable. It is the first usage
-    // of "new style" DOMExceptions where there is no IDL type, but there are
-    // API-specific exception names and/or messages. Consider refactoring back
-    // into the code generator when a common pattern emerges.
-    if (IDBDatabaseException::initializeDescription(ec, this))
-        return;
-
-    if (DOMCoreException::initializeDescription(ec, this))
-        return;
-
-    ASSERT_NOT_REACHED();
-}
-
-} // namespace WebCore
-"""
-
-
-class ExceptionCodeDescriptionWriter(name_macros.Writer):
-    defaults = {
-        'implementedAs': None,
-        'conditional': None,
-    }
-    default_parameters = {
-        'namespace': '',
-    }
-
-    def __init__(self, in_file_path, enabled_conditions):
-        super(ExceptionCodeDescriptionWriter, self).__init__(in_file_path, enabled_conditions)
-        self._outputs[(self.class_name + ".cpp")] = self.generate_implementation
-        self._outputs[(self.class_name + ".h")] = self.generate_header
-
-    def _exceptions(self):
-        return self.in_file.name_dictionaries
-
-    def _exception_type(self, exception):
-        return self.wrap_with_condition('    ' + self._class_name_for_entry(exception) + 'Type,', exception['conditional'])
-
-    def generate_header(self):
-        return HEADER_TEMPLATE % {
-            'license': license.license_for_generated_cpp(),
-            'class_name': self.class_name,
-            'exception_types': '\n'.join(map(self._exception_type, self._exceptions())),
-        }
-
-    def _include(self, exception):
-        include = '#include "' + self._headers_header_include_path(exception) + '"'
-        return self.wrap_with_condition(include, exception['conditional'])
-
-    def _description_initalization(self, exception):
-        name = os.path.basename(exception['name'])
-        if name == 'DOMException':
-            return ''  # DOMException needs to be last because it's a catch-all.
-        description_initalization = """    if (%(name)s::initializeDescription(ec, this))
-        return;""" % {'name': name}
-        return self.wrap_with_condition(description_initalization, exception['conditional'])
-
-    def generate_implementation(self):
-        return IMPLEMENTATION_TEMPLATE % {
-            'license': license.license_for_generated_cpp(),
-            'class_name': self.class_name,
-            'includes': '\n'.join(map(self._include, self._exceptions())),
-            'description_initalizations': '\n'.join(map(self._description_initalization, self._exceptions())),
-        }
-
-
-if __name__ == "__main__":
-    name_macros.Maker(ExceptionCodeDescriptionWriter).main(sys.argv)
diff --git a/Source/core/scripts/make_event_factory.py b/Source/core/scripts/make_event_factory.py
index 06d0880..d34e4be 100644
--- a/Source/core/scripts/make_event_factory.py
+++ b/Source/core/scripts/make_event_factory.py
@@ -57,9 +57,9 @@
 
 class EventFactoryWriter(name_macros.Writer):
     defaults = {
-        'implementedAs': None,
-        'conditional': None,
-        'runtimeConditional': None,
+        'ImplementedAs': None,
+        'Conditional': None,
+        'EnabledAtRuntime': None,
     }
     default_parameters = {
         'namespace': '',
@@ -74,8 +74,8 @@
 
     def _factory_implementation(self, event):
         runtime_condition = ''
-        if event['runtimeConditional']:
-            runtime_condition = ' && RuntimeEnabledFeatures::' + event['runtimeConditional'] + '()'
+        if event['EnabledAtRuntime']:
+            runtime_condition = ' && RuntimeEnabledFeatures::' + event['EnabledAtRuntime'] + '()'
         name = os.path.basename(event['name'])
         class_name = self._class_name_for_entry(event)
         implementation = """    if (type == "%(name)s"%(runtime_condition)s)
@@ -84,7 +84,7 @@
             'runtime_condition': runtime_condition,
             'class_name': class_name,
         }
-        return self.wrap_with_condition(implementation, event['conditional'])
+        return self.wrap_with_condition(implementation, event['Conditional'])
 
     def generate_implementation(self):
         return IMPLEMENTATION_TEMPLATE % {
diff --git a/Source/core/scripts/name_macros.py b/Source/core/scripts/name_macros.py
index 11d2228..01d3644 100644
--- a/Source/core/scripts/name_macros.py
+++ b/Source/core/scripts/name_macros.py
@@ -81,7 +81,7 @@
     def _sort_entries_by_conditional(self):
         unconditional_names = set()
         for entry in self.in_file.name_dictionaries:
-            conditional = entry['conditional']
+            conditional = entry['Conditional']
             if not conditional:
                 name = self._class_name_for_entry(entry)
                 if name in unconditional_names:
@@ -93,22 +93,22 @@
             name = self._class_name_for_entry(entry)
             if name in unconditional_names:
                 continue
-            conditional = entry['conditional']
+            conditional = entry['Conditional']
             if not conditional in self._entries_by_conditional:
                 self._entries_by_conditional[conditional] = []
             self._entries_by_conditional[conditional].append(entry)
 
     def _class_name_for_entry(self, entry):
-        if entry['implementedAs']:
-            return entry['implementedAs']
+        if entry['ImplementedAs']:
+            return entry['ImplementedAs']
         return os.path.basename(entry['name'])
 
     def _headers_header_include_path(self, entry):
-        if entry['implementedAs']:
+        if entry['ImplementedAs']:
             path = os.path.dirname(entry['name'])
             if len(path):
                 path += '/'
-            path += entry['implementedAs']
+            path += entry['ImplementedAs']
         else:
             path = entry['name']
         return path + '.h'
@@ -124,7 +124,7 @@
                 'path': self._headers_header_include_path(entry),
                 'js_name': os.path.basename(entry['name']),
             }
-            includes[class_name] = self.wrap_with_condition(include, entry['conditional'])
+            includes[class_name] = self.wrap_with_condition(include, entry['Conditional'])
         return includes.values()
 
     def generate_headers_header(self):
diff --git a/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl b/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl
index 0cd8b01..f78bc93 100644
--- a/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl
+++ b/Source/core/scripts/templates/StyleBuilderFunctions.cpp.tmpl
@@ -1,4 +1,4 @@
-{% from "macros.tmpl" import wrap_with_condition -%}
+{% from "macros.tmpl" import lower_first, wrap_with_condition -%}
 
 {#
     This file is for property handlers which use the templating engine to
@@ -33,6 +33,75 @@
 
 namespace WebCore {
 
+{%- macro apply_animation(property_id, attribute, animation) %}
+{{ apply_initial(property_id) }}
+{
+    CSSAnimationDataList* list = styleResolver->style()->access{{animation}}();
+    if (list->isEmpty())
+        list->append(CSSAnimationData::create());
+    list->animation(0)->set{{attribute}}(CSSAnimationData::initialAnimation{{attribute}}());
+    {%- if property_id == "CSSPropertyWebkitTransitionProperty" %}
+        list->animation(0)->setAnimationMode(CSSAnimationData::AnimateAll);
+    {%- endif %}
+    for (size_t i = 1; i < list->size(); ++i)
+        list->animation(i)->clear{{attribute}}();
+}
+
+{{ apply_inherit(property_id) }}
+{
+    CSSAnimationDataList* list = styleResolver->style()->access{{animation}}();
+    const CSSAnimationDataList* parentList = styleResolver->parentStyle()->{{animation|lower}}();
+    size_t i = 0, parentSize = parentList ? parentList->size() : 0;
+    for ( ; i < parentSize && parentList->animation(i)->is{{attribute}}Set(); ++i) {
+        if (list->size() <= i)
+            list->append(CSSAnimationData::create());
+        list->animation(i)->set{{attribute}}(parentList->animation(i)->{{lower_first(attribute)}}());
+        list->animation(i)->setAnimationMode(parentList->animation(i)->animationMode());
+    }
+
+    // Reset any remaining animations to not have the property set.
+    for ( ; i < list->size(); ++i)
+        list->animation(i)->clear{{attribute}}();
+}
+
+{{ apply_value(property_id) }}
+{
+    CSSAnimationDataList* list = styleResolver->style()->access{{animation}}();
+    size_t childIndex = 0;
+    if (value->isValueList()) {
+        // Walk each value and put it into an animation, creating new animations as needed.
+        for (CSSValueListIterator i = value; i.hasMore(); i.advance()) {
+            if (childIndex <= list->size())
+                list->append(CSSAnimationData::create());
+            styleResolver->styleMap()->mapAnimation{{attribute}}(list->animation(childIndex), i.value());
+            ++childIndex;
+        }
+    } else {
+        if (list->isEmpty())
+            list->append(CSSAnimationData::create());
+        styleResolver->styleMap()->mapAnimation{{attribute}}(list->animation(childIndex), value);
+        childIndex = 1;
+    }
+    for ( ; childIndex < list->size(); ++childIndex) {
+        // Reset all remaining animations to not have the property set.
+        list->animation(childIndex)->clear{{attribute}}();
+    }
+}
+{%- endmacro %}
+
+{{ apply_animation("CSSPropertyWebkitAnimationDelay", "Delay", "Animations") }}
+{{ apply_animation("CSSPropertyWebkitAnimationDirection", "Direction", "Animations") }}
+{{ apply_animation("CSSPropertyWebkitAnimationDuration", "Duration", "Animations") }}
+{{ apply_animation("CSSPropertyWebkitAnimationFillMode", "FillMode", "Animations") }}
+{{ apply_animation("CSSPropertyWebkitAnimationIterationCount", "IterationCount", "Animations") }}
+{{ apply_animation("CSSPropertyWebkitAnimationName", "Name", "Animations") }}
+{{ apply_animation("CSSPropertyWebkitAnimationPlayState", "PlayState", "Animations") }}
+{{ apply_animation("CSSPropertyWebkitAnimationTimingFunction", "TimingFunction", "Animations") }}
+{{ apply_animation("CSSPropertyWebkitTransitionDelay", "Delay", "Transitions") }}
+{{ apply_animation("CSSPropertyWebkitTransitionDuration", "Duration", "Transitions") }}
+{{ apply_animation("CSSPropertyWebkitTransitionProperty", "Property", "Transitions") }}
+{{ apply_animation("CSSPropertyWebkitTransitionTimingFunction", "TimingFunction", "Transitions") }}
+
 {%- macro apply_auto(property_id, auto_getter=none, auto_setter=none, auto_identity="CSSValueAuto", compute_length=false) %}
 {%- set property = properties[property_id] %}
 {%- set auto_getter = auto_getter or "hasAuto" + property.camel_case_name %}
@@ -130,9 +199,9 @@
 {%- endif %}
 
     if (styleResolver->applyPropertyToRegularStyle())
-        {{ set_value(property) }}(styleResolver->colorFromPrimitiveValue(primitiveValue));
+        {{ set_value(property) }}(styleResolver->resolveColorFromPrimitiveValue(primitiveValue));
     if (styleResolver->applyPropertyToVisitedLinkStyle())
-        styleResolver->style()->{{visited_link_setter}}(styleResolver->colorFromPrimitiveValue(primitiveValue, /* forVisitedLink */ true));
+        styleResolver->style()->{{visited_link_setter}}(styleResolver->resolveColorFromPrimitiveValue(primitiveValue, /* forVisitedLink */ true));
 }
 {%- endcall %}
 {%- endmacro %}
@@ -174,7 +243,7 @@
             currChild = new FillLayer({{fill_layer_type}});
             prevChild->setNext(currChild);
         }
-        currChild->set{{fill_type}}(currParent->{{(fill_type[0]|lower) + fill_type[1:]}}());
+        currChild->set{{fill_type}}(currParent->{{lower_first(fill_type)}}());
         prevChild = currChild;
         currChild = prevChild->next();
         currParent = currParent->next();
diff --git a/Source/core/scripts/templates/macros.tmpl b/Source/core/scripts/templates/macros.tmpl
index ce92743..b805c98 100644
--- a/Source/core/scripts/templates/macros.tmpl
+++ b/Source/core/scripts/templates/macros.tmpl
@@ -42,3 +42,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 {%- endmacro %}
+
+{% macro lower_first(s) -%}
+{{ (s[0]|lower) + s[1:] }}
+{%- endmacro %}
diff --git a/Source/core/storage/Storage.cpp b/Source/core/storage/Storage.cpp
index f1bdb19..c0a7e27 100644
--- a/Source/core/storage/Storage.cpp
+++ b/Source/core/storage/Storage.cpp
@@ -31,26 +31,22 @@
 
 namespace WebCore {
 
-PassRefPtr<Storage> Storage::create(Frame* frame, PassRefPtr<StorageArea> storageArea)
+PassRefPtr<Storage> Storage::create(Frame* frame, PassOwnPtr<StorageArea> storageArea)
 {
     return adoptRef(new Storage(frame, storageArea));
 }
 
-Storage::Storage(Frame* frame, PassRefPtr<StorageArea> storageArea)
+Storage::Storage(Frame* frame, PassOwnPtr<StorageArea> storageArea)
     : DOMWindowProperty(frame)
     , m_storageArea(storageArea)
 {
     ASSERT(m_frame);
     ASSERT(m_storageArea);
     ScriptWrappable::init(this);
-    if (m_storageArea)
-        m_storageArea->incrementAccessCount();
 }
 
 Storage::~Storage()
 {
-    if (m_storageArea)
-        m_storageArea->decrementAccessCount();
 }
 
 String Storage::anonymousIndexedGetter(unsigned index, ExceptionCode& ec)
diff --git a/Source/core/storage/Storage.h b/Source/core/storage/Storage.h
index 8b02e61..76d3149 100644
--- a/Source/core/storage/Storage.h
+++ b/Source/core/storage/Storage.h
@@ -40,7 +40,7 @@
 
     class Storage : public ScriptWrappable, public RefCounted<Storage>, public DOMWindowProperty {
     public:
-        static PassRefPtr<Storage> create(Frame*, PassRefPtr<StorageArea>);
+        static PassRefPtr<Storage> create(Frame*, PassOwnPtr<StorageArea>);
         ~Storage();
 
         unsigned length(ExceptionCode& ec) const { return m_storageArea->length(ec, m_frame); }
@@ -63,9 +63,9 @@
         bool namedPropertyQuery(const AtomicString&, ExceptionCode&);
 
     private:
-        Storage(Frame*, PassRefPtr<StorageArea>);
+        Storage(Frame*, PassOwnPtr<StorageArea>);
 
-        RefPtr<StorageArea> m_storageArea;
+        OwnPtr<StorageArea> m_storageArea;
     };
 
 } // namespace WebCore
diff --git a/Source/core/storage/StorageArea.h b/Source/core/storage/StorageArea.h
index 860fef2..b2f88a1 100644
--- a/Source/core/storage/StorageArea.h
+++ b/Source/core/storage/StorageArea.h
@@ -27,8 +27,6 @@
 #define StorageArea_h
 
 #include <wtf/Forward.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
 #include <wtf/text/WTFString.h>
 
 namespace WebCore {
@@ -39,7 +37,7 @@
 typedef int ExceptionCode;
 enum StorageType { LocalStorage, SessionStorage };
 
-class StorageArea : public RefCounted<StorageArea> {
+class StorageArea {
 public:
     virtual ~StorageArea() { }
 
@@ -56,10 +54,6 @@
     virtual bool canAccessStorage(Frame*) = 0;
 
     virtual size_t memoryBytesUsedByCache() = 0;
-
-    virtual void incrementAccessCount() { }
-    virtual void decrementAccessCount() { }
-    virtual void closeDatabaseIfIdle() { }
 };
 
 } // namespace WebCore
diff --git a/Source/core/storage/StorageNamespace.h b/Source/core/storage/StorageNamespace.h
index c60f09e..e3f7a9b 100644
--- a/Source/core/storage/StorageNamespace.h
+++ b/Source/core/storage/StorageNamespace.h
@@ -26,9 +26,7 @@
 #ifndef StorageNamespace_h
 #define StorageNamespace_h
 
-#include <wtf/Forward.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
+#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
@@ -36,19 +34,13 @@
 class SecurityOrigin;
 class StorageArea;
 
-class StorageNamespace : public RefCounted<StorageNamespace> {
+class StorageNamespace {
 public:
-    static PassRefPtr<StorageNamespace> localStorageNamespace(unsigned quota);
-    static PassRefPtr<StorageNamespace> sessionStorageNamespace(Page*, unsigned quota);
+    static PassOwnPtr<StorageArea> localStorageArea(SecurityOrigin*);
+    static PassOwnPtr<StorageNamespace> sessionStorageNamespace(Page*);
 
     virtual ~StorageNamespace() { }
-    virtual PassRefPtr<StorageArea> storageArea(PassRefPtr<SecurityOrigin>) = 0;
-    virtual PassRefPtr<StorageNamespace> copy() = 0;
-    virtual void close() = 0;
-    virtual void clearOriginForDeletion(SecurityOrigin*) = 0;
-    virtual void clearAllOriginsForDeletion() = 0;
-    virtual void sync() = 0;
-    virtual void closeIdleLocalStorageDatabases()  { }
+    virtual PassOwnPtr<StorageArea> storageArea(SecurityOrigin*) = 0;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/ElementTimeControl.h b/Source/core/svg/ElementTimeControl.h
deleted file mode 100644
index 041fdbd..0000000
--- a/Source/core/svg/ElementTimeControl.h
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Cameron McCormack <cam@mcc.id.au>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
- */
-
-#ifndef ElementTimeControl_h
-#define ElementTimeControl_h
-
-namespace WebCore {
-
-class ElementTimeControl {
-public:
-    virtual ~ElementTimeControl() {}
-    virtual void beginElement() = 0;
-    virtual void beginElementAt(float offset) = 0;
-    virtual void endElement() = 0;
-    virtual void endElementAt(float offset) = 0;
-};
-        
-}
-
-#endif
diff --git a/Source/core/svg/ElementTimeControl.idl b/Source/core/svg/ElementTimeControl.idl
deleted file mode 100644
index eb3047e..0000000
--- a/Source/core/svg/ElementTimeControl.idl
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2008 Apple Inc. All rights reserved.
- * Copyright (C) 2009 Cameron McCormack <cam@mcc.id.au>
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
- */
-
-interface ElementTimeControl {
-    void beginElement();
-    void beginElementAt([Default=Undefined] optional float offset);
-    void endElement();
-    void endElementAt([Default=Undefined] optional float offset);
-};
-
diff --git a/Source/core/svg/SVGAElement.cpp b/Source/core/svg/SVGAElement.cpp
index 450320f..0f360ee 100644
--- a/Source/core/svg/SVGAElement.cpp
+++ b/Source/core/svg/SVGAElement.cpp
@@ -59,15 +59,14 @@
 DEFINE_ANIMATED_BOOLEAN(SVGAElement, SVGNames::externalResourcesRequiredAttr, ExternalResourcesRequired, externalResourcesRequired)
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGAElement)
-     REGISTER_LOCAL_ANIMATED_PROPERTY(svgTarget)
-     REGISTER_LOCAL_ANIMATED_PROPERTY(href)
-     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
-     REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
+    REGISTER_LOCAL_ANIMATED_PROPERTY(svgTarget)
+    REGISTER_LOCAL_ANIMATED_PROPERTY(href)
+    REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGAElement::SVGAElement(const QualifiedName& tagName, Document* document)
-    : SVGStyledTransformableElement(tagName, document)
+    : SVGGraphicsElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::aTag));
     ScriptWrappable::init(this);
@@ -95,18 +94,17 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
         SVGURIReference::addSupportedAttributes(supportedAttributes);
-        SVGTests::addSupportedAttributes(supportedAttributes);
         SVGLangSpace::addSupportedAttributes(supportedAttributes);
         SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::targetAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGAElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
     if (!isSupportedAttribute(name)) {
-        SVGStyledTransformableElement::parseAttribute(name, value);
+        SVGGraphicsElement::parseAttribute(name, value);
         return;
     }
 
@@ -117,8 +115,6 @@
 
     if (SVGURIReference::parseAttribute(name, value))
         return;
-    if (SVGTests::parseAttribute(name, value))
-        return;
     if (SVGLangSpace::parseAttribute(name, value))
         return;
     if (SVGExternalResourcesRequired::parseAttribute(name, value))
@@ -130,7 +126,7 @@
 void SVGAElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGStyledTransformableElement::svgAttributeChanged(attrName);
+        SVGGraphicsElement::svgAttributeChanged(attrName);
         return;
     }
 
@@ -147,12 +143,12 @@
     }
 }
 
-RenderObject* SVGAElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGAElement::createRenderer(RenderStyle*)
 {
     if (parentNode() && parentNode()->isSVGElement() && toSVGElement(parentNode())->isTextContent())
-        return new (arena) RenderSVGInline(this);
+        return new (document()->renderArena()) RenderSVGInline(this);
 
-    return new (arena) RenderSVGTransformableContainer(this);
+    return new (document()->renderArena()) RenderSVGTransformableContainer(this);
 }
 
 void SVGAElement::defaultEventHandler(Event* event)
@@ -192,13 +188,13 @@
         }
     }
 
-    SVGStyledTransformableElement::defaultEventHandler(event);
+    SVGGraphicsElement::defaultEventHandler(event);
 }
 
 bool SVGAElement::supportsFocus() const
 {
     if (rendererIsEditable())
-        return SVGStyledTransformableElement::supportsFocus();
+        return SVGGraphicsElement::supportsFocus();
     return true;
 }
 
@@ -212,7 +208,7 @@
 
 bool SVGAElement::isURLAttribute(const Attribute& attribute) const
 {
-    return attribute.name().localName() == hrefAttr || SVGStyledTransformableElement::isURLAttribute(attribute);
+    return attribute.name().localName() == hrefAttr || SVGGraphicsElement::isURLAttribute(attribute);
 }
 
 bool SVGAElement::isMouseFocusable() const
diff --git a/Source/core/svg/SVGAElement.h b/Source/core/svg/SVGAElement.h
index 7417d49..5e72e1f 100644
--- a/Source/core/svg/SVGAElement.h
+++ b/Source/core/svg/SVGAElement.h
@@ -24,17 +24,13 @@
 
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGLangSpace.h"
-#include "core/svg/SVGStyledTransformableElement.h"
-#include "core/svg/SVGTests.h"
+#include "core/svg/SVGGraphicsElement.h"
 #include "core/svg/SVGURIReference.h"
 
 namespace WebCore {
 
-class SVGAElement FINAL : public SVGStyledTransformableElement,
+class SVGAElement FINAL : public SVGGraphicsElement,
                           public SVGURIReference,
-                          public SVGTests,
-                          public SVGLangSpace,
                           public SVGExternalResourcesRequired {
 public:
     static PassRefPtr<SVGAElement> create(const QualifiedName&, Document*);
@@ -51,7 +47,7 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void svgAttributeChanged(const QualifiedName&);
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     virtual void defaultEventHandler(Event*);
     
@@ -70,11 +66,6 @@
         DECLARE_ANIMATED_STRING(Href, href)
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
-
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGAElement.idl b/Source/core/svg/SVGAElement.idl
index c635c08..426b395 100644
--- a/Source/core/svg/SVGAElement.idl
+++ b/Source/core/svg/SVGAElement.idl
@@ -23,12 +23,10 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGAElement : SVGStyledElement,
-                        SVGURIReference,
-                        SVGTests,
-                        SVGLangSpace,
-                        SVGExternalResourcesRequired,
-                        SVGTransformable {
+interface SVGAElement : SVGGraphicsElement {
     readonly attribute SVGAnimatedString target;
 };
 
+SVGAElement implements SVGExternalResourcesRequired;
+SVGAElement implements SVGURIReference;
+
diff --git a/Source/core/svg/SVGAltGlyphElement.cpp b/Source/core/svg/SVGAltGlyphElement.cpp
index fd8d422..c102595 100644
--- a/Source/core/svg/SVGAltGlyphElement.cpp
+++ b/Source/core/svg/SVGAltGlyphElement.cpp
@@ -82,9 +82,9 @@
     return false;
 }
 
-RenderObject* SVGAltGlyphElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGAltGlyphElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGTSpan(this);
+    return new (document()->renderArena()) RenderSVGTSpan(this);
 }
 
 bool SVGAltGlyphElement::hasValidGlyphElements(Vector<String>& glyphNames) const
diff --git a/Source/core/svg/SVGAltGlyphElement.h b/Source/core/svg/SVGAltGlyphElement.h
index ea35aba..5febf29 100644
--- a/Source/core/svg/SVGAltGlyphElement.h
+++ b/Source/core/svg/SVGAltGlyphElement.h
@@ -46,7 +46,7 @@
 private:
     SVGAltGlyphElement(const QualifiedName&, Document*);
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGAltGlyphElement)
diff --git a/Source/core/svg/SVGAltGlyphElement.idl b/Source/core/svg/SVGAltGlyphElement.idl
index 7afc4ca..b3fe315 100644
--- a/Source/core/svg/SVGAltGlyphElement.idl
+++ b/Source/core/svg/SVGAltGlyphElement.idl
@@ -25,8 +25,10 @@
 
 [
     Conditional=SVG_FONTS
-] interface SVGAltGlyphElement : SVGTextPositioningElement, SVGURIReference {
+] interface SVGAltGlyphElement : SVGTextPositioningElement {
     [SetterRaisesException] attribute DOMString glyphRef;
     [SetterRaisesException] attribute DOMString format;
 };
 
+SVGAltGlyphElement implements SVGURIReference;
+
diff --git a/Source/core/svg/SVGAngle.cpp b/Source/core/svg/SVGAngle.cpp
index b550158..a90953b 100644
--- a/Source/core/svg/SVGAngle.cpp
+++ b/Source/core/svg/SVGAngle.cpp
@@ -70,27 +70,28 @@
     }
 }
 
-inline SVGAngle::SVGAngleType stringToAngleType(const UChar*& ptr, const UChar* end)
+template<typename CharType>
+static SVGAngle::SVGAngleType stringToAngleType(const CharType*& ptr, const CharType* end)
 {
     // If there's no unit given, the angle type is unspecified.
     if (ptr == end)
         return SVGAngle::SVG_ANGLETYPE_UNSPECIFIED;
 
-    const UChar firstChar = *ptr;
+    const CharType firstChar = *ptr;
     
     // If the unit contains only one character, the angle type is unknown.
     ++ptr;
     if (ptr == end)
         return SVGAngle::SVG_ANGLETYPE_UNKNOWN;
 
-    const UChar secondChar = *ptr;
+    const CharType secondChar = *ptr;
  
     // If the unit contains only two characters, the angle type is unknown.
     ++ptr;
     if (ptr == end)
         return SVGAngle::SVG_ANGLETYPE_UNKNOWN;
 
-    const UChar thirdChar = *ptr;
+    const CharType thirdChar = *ptr;
     if (firstChar == 'd' && secondChar == 'e' && thirdChar == 'g')
         return SVGAngle::SVG_ANGLETYPE_DEG;
     if (firstChar == 'r' && secondChar == 'a' && thirdChar == 'd')
@@ -101,7 +102,7 @@
     if (ptr == end)
         return SVGAngle::SVG_ANGLETYPE_UNKNOWN;
 
-    const UChar fourthChar = *ptr;
+    const CharType fourthChar = *ptr;
 
     if (firstChar == 'g' && secondChar == 'r' && thirdChar == 'a' && fourthChar == 'd')
         return SVGAngle::SVG_ANGLETYPE_GRAD;
@@ -133,6 +134,22 @@
     return String();
 }
 
+template<typename CharType>
+static bool parseValue(const String& value, float& valueInSpecifiedUnits, SVGAngle::SVGAngleType& unitType)
+{
+    const CharType* ptr = value.getCharacters<CharType>();
+    const CharType* end = ptr + value.length();
+
+    if (!parseNumber(ptr, end, valueInSpecifiedUnits, false))
+        return false;
+
+    unitType = stringToAngleType(ptr, end);
+    if (unitType == SVGAngle::SVG_ANGLETYPE_UNKNOWN)
+        return false;
+
+    return true;
+}
+
 void SVGAngle::setValueAsString(const String& value, ExceptionCode& ec)
 {
     if (value.isEmpty()) {
@@ -141,16 +158,11 @@
     }
 
     float valueInSpecifiedUnits = 0;
-    const UChar* ptr = value.characters();
-    const UChar* end = ptr + value.length();
+    SVGAngleType unitType = SVG_ANGLETYPE_UNKNOWN;
 
-    if (!parseNumber(ptr, end, valueInSpecifiedUnits, false)) {
-        ec = SYNTAX_ERR;
-        return;
-    }
-
-    SVGAngleType unitType = stringToAngleType(ptr, end);
-    if (unitType == SVG_ANGLETYPE_UNKNOWN) {
+    bool success = value.is8Bit() ? parseValue<LChar>(value, valueInSpecifiedUnits, unitType)
+                                  : parseValue<UChar>(value, valueInSpecifiedUnits, unitType);
+    if (!success) {
         ec = SYNTAX_ERR;
         return;
     }
diff --git a/Source/core/svg/SVGAnimateMotionElement.cpp b/Source/core/svg/SVGAnimateMotionElement.cpp
index 8f96172..1a468f3 100644
--- a/Source/core/svg/SVGAnimateMotionElement.cpp
+++ b/Source/core/svg/SVGAnimateMotionElement.cpp
@@ -60,7 +60,7 @@
         return false;
 
     // We don't have a special attribute name to verify the animation type. Check the element name instead.
-    if (!targetElement->isStyledTransformable() && !targetElement->hasTagName(SVGNames::textTag))
+    if (!targetElement->isSVGGraphicsElement())
         return false;
     // Spec: SVG 1.1 section 19.2.15
     // FIXME: svgTag is missing. Needs to be checked, if transforming <svg> could cause problems.
@@ -97,7 +97,7 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty())
         supportedAttributes.add(SVGNames::pathAttr);
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGAnimateMotionElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -152,30 +152,38 @@
     updateAnimationMode();
 }
 
-static bool parsePoint(const String& s, FloatPoint& point)
+template<typename CharType>
+static bool parsePointInternal(const String& string, FloatPoint& point)
 {
-    if (s.isEmpty())
-        return false;
-    const UChar* cur = s.characters();
-    const UChar* end = cur + s.length();
+    const CharType* ptr = string.getCharacters<CharType>();
+    const CharType* end = ptr + string.length();
     
-    if (!skipOptionalSVGSpaces(cur, end))
+    if (!skipOptionalSVGSpaces(ptr, end))
         return false;
     
     float x = 0;
-    if (!parseNumber(cur, end, x))
+    if (!parseNumber(ptr, end, x))
         return false;
     
     float y = 0;
-    if (!parseNumber(cur, end, y))
+    if (!parseNumber(ptr, end, y))
         return false;
     
     point = FloatPoint(x, y);
     
     // disallow anything except spaces at the end
-    return !skipOptionalSVGSpaces(cur, end);
+    return !skipOptionalSVGSpaces(ptr, end);
 }
-    
+
+static bool parsePoint(const String& string, FloatPoint& point)
+{
+    if (string.isEmpty())
+        return false;
+    if (string.is8Bit())
+        return parsePointInternal<LChar>(string, point);
+    return parsePointInternal<UChar>(string, point);
+}
+
 void SVGAnimateMotionElement::resetAnimatedType()
 {
     if (!hasValidAttributeType())
diff --git a/Source/core/svg/SVGAnimateTransformElement.cpp b/Source/core/svg/SVGAnimateTransformElement.cpp
index 9366d43..3f36f43 100644
--- a/Source/core/svg/SVGAnimateTransformElement.cpp
+++ b/Source/core/svg/SVGAnimateTransformElement.cpp
@@ -56,7 +56,7 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty())
         supportedAttributes.add(SVGNames::typeAttr);
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGAnimateTransformElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGAnimationElement.cpp b/Source/core/svg/SVGAnimationElement.cpp
index c97ca06..8373fbb 100644
--- a/Source/core/svg/SVGAnimationElement.cpp
+++ b/Source/core/svg/SVGAnimationElement.cpp
@@ -60,11 +60,11 @@
     registerAnimatedPropertiesForSVGAnimationElement();
 }
 
-static void parseKeyTimes(const String& parse, Vector<float>& result, bool verifyOrder)
+static void parseKeyTimes(const String& string, Vector<float>& result, bool verifyOrder)
 {
     result.clear();
     Vector<String> parseList;
-    parse.split(';', parseList);
+    string.split(';', parseList);
     for (unsigned n = 0; n < parseList.size(); ++n) {
         String timeString = parseList[n];
         bool ok;
@@ -85,57 +85,66 @@
     result.clear();
 }
 
-static void parseKeySplines(const String& parse, Vector<UnitBezier>& result)
+template<typename CharType>
+static void parseKeySplinesInternal(const String& string, Vector<UnitBezier>& result)
 {
-    result.clear();
-    if (parse.isEmpty())
-        return;
-    const UChar* cur = parse.characters();
-    const UChar* end = cur + parse.length();
+    const CharType* ptr = string.getCharacters<CharType>();
+    const CharType* end = ptr + string.length();
 
-    skipOptionalSVGSpaces(cur, end);
+    skipOptionalSVGSpaces(ptr, end);
 
     bool delimParsed = false;
-    while (cur < end) {
+    while (ptr < end) {
         delimParsed = false;
         float posA = 0;
-        if (!parseNumber(cur, end, posA)) {
+        if (!parseNumber(ptr, end, posA)) {
             result.clear();
             return;
         }
 
         float posB = 0;
-        if (!parseNumber(cur, end, posB)) {
+        if (!parseNumber(ptr, end, posB)) {
             result.clear();
             return;
         }
 
         float posC = 0;
-        if (!parseNumber(cur, end, posC)) {
+        if (!parseNumber(ptr, end, posC)) {
             result.clear();
             return;
         }
 
         float posD = 0;
-        if (!parseNumber(cur, end, posD, false)) {
+        if (!parseNumber(ptr, end, posD, false)) {
             result.clear();
             return;
         }
 
-        skipOptionalSVGSpaces(cur, end);
+        skipOptionalSVGSpaces(ptr, end);
 
-        if (cur < end && *cur == ';') {
+        if (ptr < end && *ptr == ';') {
             delimParsed = true;
-            cur++;
+            ptr++;
         }
-        skipOptionalSVGSpaces(cur, end);
+        skipOptionalSVGSpaces(ptr, end);
 
         result.append(UnitBezier(posA, posB, posC, posD));
     }
-    if (!(cur == end && !delimParsed))
+    if (!(ptr == end && !delimParsed))
         result.clear();
 }
 
+static void parseKeySplines(const String& string, Vector<UnitBezier>& result)
+{
+    result.clear();
+    if (string.isEmpty())
+        return;
+    if (string.is8Bit())
+        parseKeySplinesInternal<LChar>(string, result);
+    else
+        parseKeySplinesInternal<UChar>(string, result);
+}
+
 bool SVGAnimationElement::isSupportedAttribute(const QualifiedName& attrName)
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
@@ -152,7 +161,7 @@
         supportedAttributes.add(SVGNames::toAttr);
         supportedAttributes.add(SVGNames::byAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGAnimationElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGAnimationElement.h b/Source/core/svg/SVGAnimationElement.h
index c3c021d..5f37fe0 100644
--- a/Source/core/svg/SVGAnimationElement.h
+++ b/Source/core/svg/SVGAnimationElement.h
@@ -26,7 +26,6 @@
 #define SVGAnimationElement_h
 
 #include "core/platform/graphics/UnitBezier.h"
-#include "core/svg/ElementTimeControl.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGStringList.h"
@@ -67,19 +66,17 @@
 
 class SVGAnimationElement : public SVGSMILElement,
                             public SVGTests,
-                            public SVGExternalResourcesRequired,
-                            public ElementTimeControl {
+                            public SVGExternalResourcesRequired {
 public:
     // SVGAnimationElement
     float getStartTime() const;
     float getCurrentTime() const;
     float getSimpleDuration() const;
 
-    // ElementTimeControl
-    virtual void beginElement();
-    virtual void beginElementAt(float offset);
-    virtual void endElement();
-    virtual void endElementAt(float offset);
+    void beginElement();
+    void beginElementAt(float offset);
+    void endElement();
+    void endElementAt(float offset);
 
     static bool isTargetAttributeCSSProperty(SVGElement*, const QualifiedName&);
 
diff --git a/Source/core/svg/SVGAnimationElement.idl b/Source/core/svg/SVGAnimationElement.idl
index 503ec0b..d18998c 100644
--- a/Source/core/svg/SVGAnimationElement.idl
+++ b/Source/core/svg/SVGAnimationElement.idl
@@ -1,5 +1,6 @@
 /*
- * Copyright (C) 2006 Apple Inc. All rights reserved.
+ * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
+ * Copyright (C) 2009 Cameron McCormack <cam@mcc.id.au>
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions
@@ -23,16 +24,18 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-[
-    NoInterfaceObject
-] interface SVGAnimationElement : SVGElement,
-                                  SVGTests,
-                                  SVGExternalResourcesRequired,
-                                  ElementTimeControl {
+interface SVGAnimationElement : SVGElement {
     readonly attribute SVGElement targetElement;
 
     float getStartTime();
     float getCurrentTime();
     float getSimpleDuration();
+
+    void beginElement();
+    void beginElementAt([Default=Undefined] optional float offset);
+    void endElement();
+    void endElementAt([Default=Undefined] optional float offset);
 };
 
+SVGAnimationElement implements SVGExternalResourcesRequired;
+SVGAnimationElement implements SVGTests;
diff --git a/Source/core/svg/SVGCircleElement.cpp b/Source/core/svg/SVGCircleElement.cpp
index 813bf08..761807b 100644
--- a/Source/core/svg/SVGCircleElement.cpp
+++ b/Source/core/svg/SVGCircleElement.cpp
@@ -41,12 +41,11 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(cy)
     REGISTER_LOCAL_ANIMATED_PROPERTY(r)
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGCircleElement::SVGCircleElement(const QualifiedName& tagName, Document* document)
-    : SVGStyledTransformableElement(tagName, document)
+    : SVGGraphicsElement(tagName, document)
     , m_cx(LengthModeWidth)
     , m_cy(LengthModeHeight)
     , m_r(LengthModeOther)
@@ -65,14 +64,13 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGTests::addSupportedAttributes(supportedAttributes);
         SVGLangSpace::addSupportedAttributes(supportedAttributes);
         SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::cxAttr);
         supportedAttributes.add(SVGNames::cyAttr);
         supportedAttributes.add(SVGNames::rAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGCircleElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -80,15 +78,14 @@
     SVGParsingError parseError = NoError;
 
     if (!isSupportedAttribute(name))
-        SVGStyledTransformableElement::parseAttribute(name, value);
+        SVGGraphicsElement::parseAttribute(name, value);
     else if (name == SVGNames::cxAttr)
         setCxBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
     else if (name == SVGNames::cyAttr)
         setCyBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
     else if (name == SVGNames::rAttr)
         setRBaseValue(SVGLength::construct(LengthModeOther, value, parseError, ForbidNegativeLengths));
-    else if (SVGTests::parseAttribute(name, value)
-             || SVGLangSpace::parseAttribute(name, value)
+    else if (SVGLangSpace::parseAttribute(name, value)
              || SVGExternalResourcesRequired::parseAttribute(name, value)) {
     } else
         ASSERT_NOT_REACHED();
@@ -99,7 +96,7 @@
 void SVGCircleElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGStyledTransformableElement::svgAttributeChanged(attrName);
+        SVGGraphicsElement::svgAttributeChanged(attrName);
         return;
     }
 
@@ -112,9 +109,6 @@
     if (isLengthAttribute)
         updateRelativeLengthsInformation();
 
-    if (SVGTests::handleAttributeChange(this, attrName))
-        return;
-
     RenderSVGShape* renderer = toRenderSVGShape(this->renderer());
     if (!renderer)
         return;
@@ -140,9 +134,9 @@
         || r().isRelative();
 }
 
-RenderObject* SVGCircleElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGCircleElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGEllipse(this);
+    return new (document()->renderArena()) RenderSVGEllipse(this);
 }
 
 }
diff --git a/Source/core/svg/SVGCircleElement.h b/Source/core/svg/SVGCircleElement.h
index 6def4fa..17724fe 100644
--- a/Source/core/svg/SVGCircleElement.h
+++ b/Source/core/svg/SVGCircleElement.h
@@ -24,15 +24,11 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGLangSpace.h"
-#include "core/svg/SVGStyledTransformableElement.h"
-#include "core/svg/SVGTests.h"
+#include "core/svg/SVGGraphicsElement.h"
 
 namespace WebCore {
 
-class SVGCircleElement FINAL : public SVGStyledTransformableElement,
-                               public SVGTests,
-                               public SVGLangSpace,
+class SVGCircleElement FINAL : public SVGGraphicsElement,
                                public SVGExternalResourcesRequired {
 public:
     static PassRefPtr<SVGCircleElement> create(const QualifiedName&, Document*);
@@ -49,7 +45,7 @@
 
     virtual bool selfHasRelativeLengths() const;
 
-    RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGCircleElement)
         DECLARE_ANIMATED_LENGTH(Cx, cx)
@@ -57,11 +53,6 @@
         DECLARE_ANIMATED_LENGTH(R, r)
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
-
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGCircleElement.idl b/Source/core/svg/SVGCircleElement.idl
index 97a6e26..7041246 100644
--- a/Source/core/svg/SVGCircleElement.idl
+++ b/Source/core/svg/SVGCircleElement.idl
@@ -24,13 +24,11 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGCircleElement : SVGStyledElement,
-                             SVGTests,
-                             SVGLangSpace,
-                             SVGExternalResourcesRequired,
-                             SVGTransformable {
+interface SVGCircleElement : SVGGraphicsElement {
     readonly attribute SVGAnimatedLength cx;
     readonly attribute SVGAnimatedLength cy;
     readonly attribute SVGAnimatedLength r;
 };
 
+SVGCircleElement implements SVGExternalResourcesRequired;
+
diff --git a/Source/core/svg/SVGClipPathElement.cpp b/Source/core/svg/SVGClipPathElement.cpp
index 14524aa..23b9971 100644
--- a/Source/core/svg/SVGClipPathElement.cpp
+++ b/Source/core/svg/SVGClipPathElement.cpp
@@ -36,12 +36,11 @@
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGClipPathElement)
     REGISTER_LOCAL_ANIMATED_PROPERTY(clipPathUnits)
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGClipPathElement::SVGClipPathElement(const QualifiedName& tagName, Document* document)
-    : SVGStyledTransformableElement(tagName, document)
+    : SVGGraphicsElement(tagName, document)
     , m_clipPathUnits(SVGUnitTypes::SVG_UNIT_TYPE_USERSPACEONUSE)
 {
     ASSERT(hasTagName(SVGNames::clipPathTag));
@@ -58,18 +57,17 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGTests::addSupportedAttributes(supportedAttributes);
         SVGLangSpace::addSupportedAttributes(supportedAttributes);
         SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::clipPathUnitsAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGClipPathElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
     if (!isSupportedAttribute(name)) {
-        SVGStyledTransformableElement::parseAttribute(name, value);
+        SVGGraphicsElement::parseAttribute(name, value);
         return;
     }
 
@@ -80,8 +78,6 @@
         return;
     }
 
-    if (SVGTests::parseAttribute(name, value))
-        return;
     if (SVGLangSpace::parseAttribute(name, value))
         return;
     if (SVGExternalResourcesRequired::parseAttribute(name, value))
@@ -93,7 +89,7 @@
 void SVGClipPathElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGStyledTransformableElement::svgAttributeChanged(attrName);
+        SVGGraphicsElement::svgAttributeChanged(attrName);
         return;
     }
 
@@ -105,7 +101,7 @@
 
 void SVGClipPathElement::childrenChanged(bool changedByParser, Node* beforeChange, Node* afterChange, int childCountDelta)
 {
-    SVGStyledTransformableElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
+    SVGGraphicsElement::childrenChanged(changedByParser, beforeChange, afterChange, childCountDelta);
 
     if (changedByParser)
         return;
@@ -114,9 +110,9 @@
         object->setNeedsLayout(true);
 }
 
-RenderObject* SVGClipPathElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGClipPathElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGResourceClipper(this);
+    return new (document()->renderArena()) RenderSVGResourceClipper(this);
 }
 
 }
diff --git a/Source/core/svg/SVGClipPathElement.h b/Source/core/svg/SVGClipPathElement.h
index 7c0a501..c5bbb88 100644
--- a/Source/core/svg/SVGClipPathElement.h
+++ b/Source/core/svg/SVGClipPathElement.h
@@ -24,18 +24,14 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedEnumeration.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGLangSpace.h"
-#include "core/svg/SVGStyledTransformableElement.h"
-#include "core/svg/SVGTests.h"
+#include "core/svg/SVGGraphicsElement.h"
 #include "core/svg/SVGUnitTypes.h"
 
 namespace WebCore {
 
 class RenderObject;
 
-class SVGClipPathElement FINAL : public SVGStyledTransformableElement,
-                                 public SVGTests,
-                                 public SVGLangSpace,
+class SVGClipPathElement FINAL : public SVGGraphicsElement,
                                  public SVGExternalResourcesRequired {
 public:
     static PassRefPtr<SVGClipPathElement> create(const QualifiedName&, Document*);
@@ -51,17 +47,12 @@
     virtual void svgAttributeChanged(const QualifiedName&);
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGClipPathElement)
         DECLARE_ANIMATED_ENUMERATION(ClipPathUnits, clipPathUnits, SVGUnitTypes::SVGUnitType)
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
-
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
 };
 
 }
diff --git a/Source/core/svg/SVGClipPathElement.idl b/Source/core/svg/SVGClipPathElement.idl
index 7fee1c2..96b5af1 100644
--- a/Source/core/svg/SVGClipPathElement.idl
+++ b/Source/core/svg/SVGClipPathElement.idl
@@ -24,12 +24,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGClipPathElement : SVGStyledElement,
-                               SVGTests,
-                               SVGLangSpace,
-                               SVGExternalResourcesRequired,
-                               SVGTransformable
-                               /* SVGUnitTypes */ {
+interface SVGClipPathElement : SVGGraphicsElement {
     readonly attribute SVGAnimatedEnumeration clipPathUnits;
 };
 
+SVGClipPathElement implements SVGExternalResourcesRequired;
diff --git a/Source/core/svg/SVGComponentTransferFunctionElement.cpp b/Source/core/svg/SVGComponentTransferFunctionElement.cpp
index 39c3650..996a171 100644
--- a/Source/core/svg/SVGComponentTransferFunctionElement.cpp
+++ b/Source/core/svg/SVGComponentTransferFunctionElement.cpp
@@ -72,7 +72,7 @@
         supportedAttributes.add(SVGNames::exponentAttr);
         supportedAttributes.add(SVGNames::offsetAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGComponentTransferFunctionElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGCursorElement.cpp b/Source/core/svg/SVGCursorElement.cpp
index c720d8f..73decae 100644
--- a/Source/core/svg/SVGCursorElement.cpp
+++ b/Source/core/svg/SVGCursorElement.cpp
@@ -74,7 +74,7 @@
         supportedAttributes.add(SVGNames::xAttr);
         supportedAttributes.add(SVGNames::yAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGCursorElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGCursorElement.idl b/Source/core/svg/SVGCursorElement.idl
index 057c2b1..3d76a2d 100644
--- a/Source/core/svg/SVGCursorElement.idl
+++ b/Source/core/svg/SVGCursorElement.idl
@@ -23,11 +23,12 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGCursorElement : SVGElement,
-                             SVGURIReference,
-                             SVGTests,
-                             SVGExternalResourcesRequired {
+interface SVGCursorElement : SVGElement {
     readonly attribute SVGAnimatedLength x;
     readonly attribute SVGAnimatedLength y;
 };
 
+SVGCursorElement implements SVGExternalResourcesRequired;
+SVGCursorElement implements SVGURIReference;
+SVGCursorElement implements SVGTests;
+
diff --git a/Source/core/svg/SVGDefsElement.cpp b/Source/core/svg/SVGDefsElement.cpp
index a42aca3..5992687 100644
--- a/Source/core/svg/SVGDefsElement.cpp
+++ b/Source/core/svg/SVGDefsElement.cpp
@@ -32,12 +32,11 @@
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGDefsElement)
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGDefsElement::SVGDefsElement(const QualifiedName& tagName, Document* document)
-    : SVGStyledTransformableElement(tagName, document)
+    : SVGGraphicsElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::defsTag));
     ScriptWrappable::init(this);
@@ -54,9 +53,9 @@
     return SVGTests::isValid();
 }
 
-RenderObject* SVGDefsElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGDefsElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGHiddenContainer(this);
+    return new (document()->renderArena()) RenderSVGHiddenContainer(this);
 }
 
 }
diff --git a/Source/core/svg/SVGDefsElement.h b/Source/core/svg/SVGDefsElement.h
index 8b316c6..0b60150 100644
--- a/Source/core/svg/SVGDefsElement.h
+++ b/Source/core/svg/SVGDefsElement.h
@@ -23,15 +23,11 @@
 
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGLangSpace.h"
-#include "core/svg/SVGStyledTransformableElement.h"
-#include "core/svg/SVGTests.h"
+#include "core/svg/SVGGraphicsElement.h"
 
 namespace WebCore {
 
-class SVGDefsElement FINAL : public SVGStyledTransformableElement,
-                             public SVGTests,
-                             public SVGLangSpace,
+class SVGDefsElement FINAL : public SVGGraphicsElement,
                              public SVGExternalResourcesRequired {
 public:
     static PassRefPtr<SVGDefsElement> create(const QualifiedName&, Document*);
@@ -41,16 +37,11 @@
 
     virtual bool isValid() const;
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGDefsElement)
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
-
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGDefsElement.idl b/Source/core/svg/SVGDefsElement.idl
index 24a6d28..3af65f3 100644
--- a/Source/core/svg/SVGDefsElement.idl
+++ b/Source/core/svg/SVGDefsElement.idl
@@ -23,10 +23,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGDefsElement : SVGStyledElement,
-                           SVGTests,
-                           SVGLangSpace,
-                           SVGExternalResourcesRequired,
-                           SVGTransformable {
+interface SVGDefsElement : SVGGraphicsElement {
 };
 
+SVGDefsElement implements SVGExternalResourcesRequired;
+
diff --git a/Source/core/svg/SVGDescElement.h b/Source/core/svg/SVGDescElement.h
index 8126abb..3585247 100644
--- a/Source/core/svg/SVGDescElement.h
+++ b/Source/core/svg/SVGDescElement.h
@@ -21,13 +21,11 @@
 #ifndef SVGDescElement_h
 #define SVGDescElement_h
 
-#include "core/svg/SVGLangSpace.h"
 #include "core/svg/SVGStyledElement.h"
 
 namespace WebCore {
 
-class SVGDescElement FINAL : public SVGStyledElement,
-                             public SVGLangSpace {
+class SVGDescElement FINAL : public SVGStyledElement {
 public:
     static PassRefPtr<SVGDescElement> create(const QualifiedName&, Document*);
 
diff --git a/Source/core/svg/SVGDescElement.idl b/Source/core/svg/SVGDescElement.idl
index 2076880..0b31c7c 100644
--- a/Source/core/svg/SVGDescElement.idl
+++ b/Source/core/svg/SVGDescElement.idl
@@ -23,7 +23,6 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGDescElement : SVGStyledElement,
-                           SVGLangSpace {
+interface SVGDescElement : SVGStyledElement {
 };
 
diff --git a/Source/core/svg/SVGElement.cpp b/Source/core/svg/SVGElement.cpp
index 8e0a451..bd26841 100644
--- a/Source/core/svg/SVGElement.cpp
+++ b/Source/core/svg/SVGElement.cpp
@@ -39,16 +39,15 @@
 #include "core/svg/SVGDocumentExtensions.h"
 #include "core/svg/SVGElementInstance.h"
 #include "core/svg/SVGElementRareData.h"
+#include "core/svg/SVGGraphicsElement.h"
 #include "core/svg/SVGSVGElement.h"
-#include "core/svg/SVGStyledLocatableElement.h"
-#include "core/svg/SVGTextElement.h"
 
 namespace WebCore {
 
 using namespace HTMLNames;
 
 SVGElement::SVGElement(const QualifiedName& tagName, Document* document, ConstructionType constructionType)
-    : StyledElement(tagName, document, constructionType)
+    : Element(tagName, document, constructionType)
 {
     ScriptWrappable::init(this);
     setHasCustomStyleCallbacks();
@@ -90,7 +89,7 @@
 
 void SVGElement::willRecalcStyle(StyleChange change)
 {
-    if (!hasSVGRareData() || styleChangeType() == SyntheticStyleChange)
+    if (!hasSVGRareData() || needsLayerUpdate())
         return;
     // If the style changes because of a regular property change (not induced by SMIL animations themselves)
     // reset the "computed style without SMIL style properties", so the base value change gets reflected.
@@ -180,7 +179,7 @@
 {
     bool wasInDocument = rootParent->inDocument();
 
-    StyledElement::removedFrom(rootParent);
+    Element::removedFrom(rootParent);
 
     if (wasInDocument) {
         document()->accessSVGExtensions()->rebuildAllElementReferencesForTarget(this);
@@ -255,12 +254,8 @@
 
 bool SVGElement::getBoundingBox(FloatRect& rect, SVGLocatable::StyleUpdateStrategy styleUpdateStrategy)
 {
-    if (isStyledLocatable()) {
-        rect = toSVGStyledLocatableElement(this)->getBBox(styleUpdateStrategy);
-        return true;
-    }
-    if (hasTagName(SVGNames::textTag)) {
-        rect = static_cast<SVGTextElement*>(this)->getBBox(styleUpdateStrategy);
+    if (isSVGGraphicsElement()) {
+        rect = toSVGGraphicsElement(this)->getBBox(styleUpdateStrategy);
         return true;
     }
     return false;
@@ -334,8 +329,9 @@
         setAttributeEventListener(eventNames().focusoutEvent, createAttributeEventListener(this, name, value));
     else if (name == SVGNames::onactivateAttr)
         setAttributeEventListener(eventNames().DOMActivateEvent, createAttributeEventListener(this, name, value));
-    else
-        StyledElement::parseAttribute(name, value);
+    else if (SVGLangSpace::parseAttribute(name, value)) {
+    } else
+        Element::parseAttribute(name, value);
 }
 
 void SVGElement::animatedPropertyTypeForAttribute(const QualifiedName& attributeName, Vector<AnimatedPropertyType>& propertyTypes)
@@ -455,6 +451,12 @@
     return false;
 }
 
+bool SVGElement::shouldMoveToFlowThread(RenderStyle* styleToUse) const
+{
+    // Allow only svg root elements to be directly collected by a render flow thread.
+    return parentNode() && !parentNode()->isSVGElement() && hasTagName(SVGNames::svgTag) && Element::shouldMoveToFlowThread(styleToUse);
+}
+
 void SVGElement::sendSVGLoadEventIfPossible(bool sendParentLoadEvents)
 {
     RefPtr<SVGElement> currentTarget = this;
@@ -500,7 +502,7 @@
 
 void SVGElement::finishParsingChildren()
 {
-    StyledElement::finishParsingChildren();
+    Element::finishParsingChildren();
 
     // The outermost SVGSVGElement SVGLoad event is fired through Document::dispatchWindowLoadEvent.
     if (isOutermostSVGSVGElement())
@@ -535,7 +537,7 @@
 
 void SVGElement::attributeChanged(const QualifiedName& name, const AtomicString& newValue, AttributeModificationReason)
 {
-    StyledElement::attributeChanged(name, newValue);
+    Element::attributeChanged(name, newValue);
 
     if (isIdAttributeName(name))
         document()->accessSVGExtensions()->rebuildAllElementReferencesForTarget(this);
diff --git a/Source/core/svg/SVGElement.h b/Source/core/svg/SVGElement.h
index a01c378..12584f7 100644
--- a/Source/core/svg/SVGElement.h
+++ b/Source/core/svg/SVGElement.h
@@ -22,8 +22,9 @@
 #ifndef SVGElement_h
 #define SVGElement_h
 
-#include "core/dom/StyledElement.h"
+#include "core/dom/Element.h"
 #include "core/platform/Timer.h"
+#include "core/svg/SVGLangSpace.h"
 #include "core/svg/SVGLocatable.h"
 #include "core/svg/SVGParsingError.h"
 #include "core/svg/properties/SVGPropertyInfo.h"
@@ -41,7 +42,7 @@
 class SVGElementRareData;
 class SVGSVGElement;
 
-class SVGElement : public StyledElement {
+class SVGElement : public Element, public SVGLangSpace {
 public:
     static PassRefPtr<SVGElement> create(const QualifiedName&, Document*);
     virtual ~SVGElement();
@@ -57,8 +58,7 @@
     SVGDocumentExtensions* accessDocumentSVGExtensions();
 
     virtual bool isSVGStyledElement() const { return false; }
-    virtual bool isStyledTransformable() const { return false; }
-    virtual bool isStyledLocatable() const { return false; }
+    virtual bool isSVGGraphicsElement() const { return false; }
     virtual bool isSVGSVGElement() const { return false; }
     virtual bool isFilterEffect() const { return false; }
     virtual bool isGradientStop() const { return false; }
@@ -119,6 +119,8 @@
     virtual bool addEventListener(const AtomicString& eventType, PassRefPtr<EventListener>, bool useCapture) OVERRIDE;
     virtual bool removeEventListener(const AtomicString& eventType, EventListener*, bool useCapture) OVERRIDE;
 
+    virtual bool shouldMoveToFlowThread(RenderStyle*) const OVERRIDE;
+
 protected:
     SVGElement(const QualifiedName&, Document*, ConstructionType = CreateSVGElement);
 
diff --git a/Source/core/svg/SVGElement.idl b/Source/core/svg/SVGElement.idl
index 912a6a0..7e45efb 100644
--- a/Source/core/svg/SVGElement.idl
+++ b/Source/core/svg/SVGElement.idl
@@ -27,5 +27,8 @@
     [TreatNullAs=NullString] attribute DOMString xmlbase;
     readonly attribute SVGSVGElement ownerSVGElement;
     readonly attribute SVGElement viewportElement;
+
+    attribute DOMString xmllang;
+    attribute DOMString xmlspace;
 };
 
diff --git a/Source/core/svg/SVGEllipseElement.cpp b/Source/core/svg/SVGEllipseElement.cpp
index 56e8f87..26d1f8d 100644
--- a/Source/core/svg/SVGEllipseElement.cpp
+++ b/Source/core/svg/SVGEllipseElement.cpp
@@ -43,12 +43,11 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(rx)
     REGISTER_LOCAL_ANIMATED_PROPERTY(ry)
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGEllipseElement::SVGEllipseElement(const QualifiedName& tagName, Document* document)
-    : SVGStyledTransformableElement(tagName, document)
+    : SVGGraphicsElement(tagName, document)
     , m_cx(LengthModeWidth)
     , m_cy(LengthModeHeight)
     , m_rx(LengthModeWidth)
@@ -68,7 +67,6 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGTests::addSupportedAttributes(supportedAttributes);
         SVGLangSpace::addSupportedAttributes(supportedAttributes);
         SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::cxAttr);
@@ -76,7 +74,7 @@
         supportedAttributes.add(SVGNames::rxAttr);
         supportedAttributes.add(SVGNames::ryAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGEllipseElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -84,7 +82,7 @@
     SVGParsingError parseError = NoError;
 
     if (!isSupportedAttribute(name))
-        SVGStyledTransformableElement::parseAttribute(name, value);
+        SVGGraphicsElement::parseAttribute(name, value);
     else if (name == SVGNames::cxAttr)
         setCxBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
     else if (name == SVGNames::cyAttr)
@@ -93,8 +91,7 @@
         setRxBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
     else if (name == SVGNames::ryAttr)
         setRyBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
-    else if (SVGTests::parseAttribute(name, value)
-             || SVGLangSpace::parseAttribute(name, value)
+    else if (SVGLangSpace::parseAttribute(name, value)
              || SVGExternalResourcesRequired::parseAttribute(name, value)) {
     } else
         ASSERT_NOT_REACHED();
@@ -105,7 +102,7 @@
 void SVGEllipseElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGStyledTransformableElement::svgAttributeChanged(attrName);
+        SVGGraphicsElement::svgAttributeChanged(attrName);
         return;
     }
 
@@ -118,9 +115,6 @@
 
     if (isLengthAttribute)
         updateRelativeLengthsInformation();
- 
-    if (SVGTests::handleAttributeChange(this, attrName))
-        return;
 
     RenderSVGShape* renderer = toRenderSVGShape(this->renderer());
     if (!renderer)
@@ -148,9 +142,9 @@
         || ry().isRelative();
 }
 
-RenderObject* SVGEllipseElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGEllipseElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGEllipse(this);
+    return new (document()->renderArena()) RenderSVGEllipse(this);
 }
 
 }
diff --git a/Source/core/svg/SVGEllipseElement.h b/Source/core/svg/SVGEllipseElement.h
index 0990370..e5211af 100644
--- a/Source/core/svg/SVGEllipseElement.h
+++ b/Source/core/svg/SVGEllipseElement.h
@@ -24,15 +24,11 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGLangSpace.h"
-#include "core/svg/SVGStyledTransformableElement.h"
-#include "core/svg/SVGTests.h"
+#include "core/svg/SVGGraphicsElement.h"
 
 namespace WebCore {
 
-class SVGEllipseElement FINAL : public SVGStyledTransformableElement,
-                                public SVGTests,
-                                public SVGLangSpace,
+class SVGEllipseElement FINAL : public SVGGraphicsElement,
                                 public SVGExternalResourcesRequired {
 public:
     static PassRefPtr<SVGEllipseElement> create(const QualifiedName&, Document*);
@@ -49,7 +45,7 @@
 
     virtual bool selfHasRelativeLengths() const;
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGEllipseElement)
         DECLARE_ANIMATED_LENGTH(Cx, cx)
@@ -58,11 +54,6 @@
         DECLARE_ANIMATED_LENGTH(Ry, ry)
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
-
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGEllipseElement.idl b/Source/core/svg/SVGEllipseElement.idl
index db65f0e..22b4e02 100644
--- a/Source/core/svg/SVGEllipseElement.idl
+++ b/Source/core/svg/SVGEllipseElement.idl
@@ -23,14 +23,12 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGEllipseElement : SVGStyledElement,
-                              SVGTests,
-                              SVGLangSpace,
-                              SVGExternalResourcesRequired,
-                              SVGTransformable {
+interface SVGEllipseElement : SVGGraphicsElement {
     readonly attribute SVGAnimatedLength cx;
     readonly attribute SVGAnimatedLength cy;
     readonly attribute SVGAnimatedLength rx;
     readonly attribute SVGAnimatedLength ry;
 };
 
+SVGEllipseElement implements SVGExternalResourcesRequired;
+
diff --git a/Source/core/svg/SVGException.cpp b/Source/core/svg/SVGException.cpp
deleted file mode 100644
index 8089c93..0000000
--- a/Source/core/svg/SVGException.cpp
+++ /dev/null
@@ -1,62 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-
-#include "core/svg/SVGException.h"
-
-namespace WebCore {
-
-static struct SVGExceptionNameDescription {
-    const char* const name;
-    const char* const description;
-} svgExceptions[] = {
-    { "SVG_WRONG_TYPE_ERR", "An object of the wrong type was passed to an operation." },
-    { "SVG_INVALID_VALUE_ERR", "An invalid value was passed to an operation or assigned to an attribute." },
-    { "SVG_MATRIX_NOT_INVERTABLE", "An attempt was made to invert a matrix that is not invertible." }
-};
-
-bool SVGException::initializeDescription(ExceptionCode ec, ExceptionCodeDescription* description)
-{
-    if (ec < SVGExceptionOffset || ec > SVGExceptionMax)
-        return false;
-
-    description->typeName = "DOM SVG";
-    description->code = ec - SVGExceptionOffset;
-    description->type = SVGExceptionType;
-
-    size_t tableSize = WTF_ARRAY_LENGTH(svgExceptions);
-    size_t tableIndex = ec - SVG_WRONG_TYPE_ERR;
-
-    description->name = tableIndex < tableSize ? svgExceptions[tableIndex].name : 0;
-    description->description = tableIndex < tableSize ? svgExceptions[tableIndex].description : 0;
-
-    return true;
-}
-
-} // namespace WebCore
diff --git a/Source/core/svg/SVGException.h b/Source/core/svg/SVGException.h
deleted file mode 100644
index 86169e6..0000000
--- a/Source/core/svg/SVGException.h
+++ /dev/null
@@ -1,57 +0,0 @@
-/*
- * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
- * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef SVGException_h
-#define SVGException_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/ExceptionBase.h"
-
-namespace WebCore {
-
-class SVGException : public ExceptionBase, public ScriptWrappable {
-public:
-    static PassRefPtr<SVGException> create(const ExceptionCodeDescription& description)
-    {
-        return adoptRef(new SVGException(description));
-    }
-
-    static const int SVGExceptionOffset = 300;
-    static const int SVGExceptionMax = 399;
-
-    enum SVGExceptionCode {
-        SVG_WRONG_TYPE_ERR = SVGExceptionOffset,
-        SVG_INVALID_VALUE_ERR = SVGExceptionOffset + 1,
-        SVG_MATRIX_NOT_INVERTABLE = SVGExceptionOffset + 2
-    };
-
-    static bool initializeDescription(ExceptionCode, ExceptionCodeDescription*);
-
-private:
-    SVGException(const ExceptionCodeDescription& description)
-        : ExceptionBase(description)
-    {
-        ScriptWrappable::init(this);
-    }
-};
-
-} // namespace WebCore
-
-#endif // SVGException_h
diff --git a/Source/core/svg/SVGException.idl b/Source/core/svg/SVGException.idl
deleted file mode 100644
index 574c743..0000000
--- a/Source/core/svg/SVGException.idl
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (C) 2007 Rob Buis <buis@kde.org>
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-[
-    DoNotCheckConstants
-] exception SVGException {
-
-    readonly attribute unsigned short   code;
-    readonly attribute DOMString        name;
-    readonly attribute DOMString        message;
-
-    // Override in a Mozilla compatible format
-    [NotEnumerable] DOMString toString();
-
-    // SVGExceptionCode
-    const unsigned short SVG_WRONG_TYPE_ERR = 0;
-    const unsigned short SVG_INVALID_VALUE_ERR = 1;
-    const unsigned short SVG_MATRIX_NOT_INVERTABLE = 2;
-};
diff --git a/Source/core/svg/SVGExternalResourcesRequired.idl b/Source/core/svg/SVGExternalResourcesRequired.idl
index 2d0d402..50f8471 100644
--- a/Source/core/svg/SVGExternalResourcesRequired.idl
+++ b/Source/core/svg/SVGExternalResourcesRequired.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    DoNotGenerateToV8
+    NoInterfaceObject
 ] interface SVGExternalResourcesRequired { 
     readonly attribute SVGAnimatedBoolean externalResourcesRequired;
 };
diff --git a/Source/core/svg/SVGFEBlendElement.cpp b/Source/core/svg/SVGFEBlendElement.cpp
index 9b50de3..ab5d37a 100644
--- a/Source/core/svg/SVGFEBlendElement.cpp
+++ b/Source/core/svg/SVGFEBlendElement.cpp
@@ -63,7 +63,7 @@
         supportedAttributes.add(SVGNames::inAttr);
         supportedAttributes.add(SVGNames::in2Attr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFEBlendElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFEBlendElement.idl b/Source/core/svg/SVGFEBlendElement.idl
index 17dd692..1bad336 100644
--- a/Source/core/svg/SVGFEBlendElement.idl
+++ b/Source/core/svg/SVGFEBlendElement.idl
@@ -25,8 +25,7 @@
 
 [
     DoNotCheckConstants
-] interface SVGFEBlendElement : SVGStyledElement,
-                                SVGFilterPrimitiveStandardAttributes {
+] interface SVGFEBlendElement : SVGStyledElement {
     // Blend Mode Types
     const unsigned short SVG_FEBLEND_MODE_UNKNOWN  = 0;
     const unsigned short SVG_FEBLEND_MODE_NORMAL   = 1;
@@ -40,3 +39,4 @@
     readonly attribute SVGAnimatedEnumeration mode;
 };
 
+SVGFEBlendElement implements SVGFilterPrimitiveStandardAttributes;
diff --git a/Source/core/svg/SVGFEColorMatrixElement.cpp b/Source/core/svg/SVGFEColorMatrixElement.cpp
index 3278ce9..5a82e7a 100644
--- a/Source/core/svg/SVGFEColorMatrixElement.cpp
+++ b/Source/core/svg/SVGFEColorMatrixElement.cpp
@@ -63,7 +63,7 @@
         supportedAttributes.add(SVGNames::valuesAttr);
         supportedAttributes.add(SVGNames::inAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFEColorMatrixElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFEColorMatrixElement.idl b/Source/core/svg/SVGFEColorMatrixElement.idl
index 90cc35d..3da5528 100644
--- a/Source/core/svg/SVGFEColorMatrixElement.idl
+++ b/Source/core/svg/SVGFEColorMatrixElement.idl
@@ -25,8 +25,7 @@
 
 [
     DoNotCheckConstants
-] interface SVGFEColorMatrixElement : SVGStyledElement,
-                                      SVGFilterPrimitiveStandardAttributes {
+] interface SVGFEColorMatrixElement : SVGStyledElement {
     // Color Matrix Types
     const unsigned short SVG_FECOLORMATRIX_TYPE_UNKNOWN          = 0;
     const unsigned short SVG_FECOLORMATRIX_TYPE_MATRIX           = 1;
@@ -39,3 +38,4 @@
     readonly attribute SVGAnimatedNumberList  values;
 };
 
+SVGFEColorMatrixElement implements SVGFilterPrimitiveStandardAttributes;
diff --git a/Source/core/svg/SVGFEComponentTransferElement.cpp b/Source/core/svg/SVGFEComponentTransferElement.cpp
index c830eeb..aead2ac 100644
--- a/Source/core/svg/SVGFEComponentTransferElement.cpp
+++ b/Source/core/svg/SVGFEComponentTransferElement.cpp
@@ -58,7 +58,7 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty())
         supportedAttributes.add(SVGNames::inAttr);
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFEComponentTransferElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFEComponentTransferElement.idl b/Source/core/svg/SVGFEComponentTransferElement.idl
index b68de27..b855de4 100644
--- a/Source/core/svg/SVGFEComponentTransferElement.idl
+++ b/Source/core/svg/SVGFEComponentTransferElement.idl
@@ -23,8 +23,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGFEComponentTransferElement : SVGStyledElement,
-                                          SVGFilterPrimitiveStandardAttributes {
+interface SVGFEComponentTransferElement : SVGStyledElement {
     readonly attribute SVGAnimatedString in1;
 };
 
+SVGFEComponentTransferElement implements SVGFilterPrimitiveStandardAttributes;
diff --git a/Source/core/svg/SVGFECompositeElement.cpp b/Source/core/svg/SVGFECompositeElement.cpp
index d5389f9..9663046 100644
--- a/Source/core/svg/SVGFECompositeElement.cpp
+++ b/Source/core/svg/SVGFECompositeElement.cpp
@@ -75,7 +75,7 @@
         supportedAttributes.add(SVGNames::k3Attr);
         supportedAttributes.add(SVGNames::k4Attr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFECompositeElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFECompositeElement.idl b/Source/core/svg/SVGFECompositeElement.idl
index 1a4aa40..a8b53c4 100644
--- a/Source/core/svg/SVGFECompositeElement.idl
+++ b/Source/core/svg/SVGFECompositeElement.idl
@@ -25,8 +25,7 @@
 
 [
     DoNotCheckConstants
-] interface SVGFECompositeElement : SVGStyledElement,
-                                    SVGFilterPrimitiveStandardAttributes {
+] interface SVGFECompositeElement : SVGStyledElement {
     // Composite Operators
     const unsigned short SVG_FECOMPOSITE_OPERATOR_UNKNOWN    = 0;
     const unsigned short SVG_FECOMPOSITE_OPERATOR_OVER       = 1;
@@ -45,3 +44,4 @@
     readonly attribute SVGAnimatedNumber      k4;
 };
 
+SVGFECompositeElement implements SVGFilterPrimitiveStandardAttributes;
diff --git a/Source/core/svg/SVGFEConvolveMatrixElement.cpp b/Source/core/svg/SVGFEConvolveMatrixElement.cpp
index 9412c25..dd21761 100644
--- a/Source/core/svg/SVGFEConvolveMatrixElement.cpp
+++ b/Source/core/svg/SVGFEConvolveMatrixElement.cpp
@@ -115,7 +115,7 @@
         supportedAttributes.add(SVGNames::kernelUnitLengthAttr);
         supportedAttributes.add(SVGNames::preserveAlphaAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFEConvolveMatrixElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFEConvolveMatrixElement.idl b/Source/core/svg/SVGFEConvolveMatrixElement.idl
index 1ae8935..3196cd0 100644
--- a/Source/core/svg/SVGFEConvolveMatrixElement.idl
+++ b/Source/core/svg/SVGFEConvolveMatrixElement.idl
@@ -25,8 +25,7 @@
 
 [
     DoNotCheckConstants
-] interface SVGFEConvolveMatrixElement : SVGStyledElement,
-                                         SVGFilterPrimitiveStandardAttributes {
+] interface SVGFEConvolveMatrixElement : SVGStyledElement {
     // Edge Mode Values
     const unsigned short SVG_EDGEMODE_UNKNOWN   = 0;
     const unsigned short SVG_EDGEMODE_DUPLICATE = 1;
@@ -47,3 +46,4 @@
     readonly attribute SVGAnimatedBoolean     preserveAlpha;
 };
 
+SVGFEConvolveMatrixElement implements SVGFilterPrimitiveStandardAttributes;
diff --git a/Source/core/svg/SVGFEDiffuseLightingElement.cpp b/Source/core/svg/SVGFEDiffuseLightingElement.cpp
index aa9dcce..9a2dfaa 100644
--- a/Source/core/svg/SVGFEDiffuseLightingElement.cpp
+++ b/Source/core/svg/SVGFEDiffuseLightingElement.cpp
@@ -85,7 +85,7 @@
         supportedAttributes.add(SVGNames::kernelUnitLengthAttr);
         supportedAttributes.add(SVGNames::lighting_colorAttr); // Even though it's a SVG-CSS property, we override its handling here.
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFEDiffuseLightingElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFEDiffuseLightingElement.idl b/Source/core/svg/SVGFEDiffuseLightingElement.idl
index 5cf37d8..64ce7c6 100644
--- a/Source/core/svg/SVGFEDiffuseLightingElement.idl
+++ b/Source/core/svg/SVGFEDiffuseLightingElement.idl
@@ -23,8 +23,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGFEDiffuseLightingElement : SVGStyledElement,
-                                        SVGFilterPrimitiveStandardAttributes {
+interface SVGFEDiffuseLightingElement : SVGStyledElement {
     readonly attribute SVGAnimatedString in1;
     readonly attribute SVGAnimatedNumber surfaceScale;
     readonly attribute SVGAnimatedNumber diffuseConstant;
@@ -32,3 +31,4 @@
     readonly attribute SVGAnimatedNumber kernelUnitLengthY;
 };
 
+SVGFEDiffuseLightingElement implements SVGFilterPrimitiveStandardAttributes;
diff --git a/Source/core/svg/SVGFEDisplacementMapElement.cpp b/Source/core/svg/SVGFEDisplacementMapElement.cpp
index da7a3d6..340b180 100644
--- a/Source/core/svg/SVGFEDisplacementMapElement.cpp
+++ b/Source/core/svg/SVGFEDisplacementMapElement.cpp
@@ -69,7 +69,7 @@
         supportedAttributes.add(SVGNames::yChannelSelectorAttr);
         supportedAttributes.add(SVGNames::scaleAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFEDisplacementMapElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFEDisplacementMapElement.idl b/Source/core/svg/SVGFEDisplacementMapElement.idl
index 87570dd..a578c1c 100644
--- a/Source/core/svg/SVGFEDisplacementMapElement.idl
+++ b/Source/core/svg/SVGFEDisplacementMapElement.idl
@@ -25,8 +25,7 @@
 
 [
     DoNotCheckConstants
-] interface SVGFEDisplacementMapElement : SVGStyledElement,
-                                          SVGFilterPrimitiveStandardAttributes {
+] interface SVGFEDisplacementMapElement : SVGStyledElement {
     // Channel Selectors
     const unsigned short SVG_CHANNEL_UNKNOWN = 0;
     const unsigned short SVG_CHANNEL_R       = 1;
@@ -41,3 +40,4 @@
     readonly attribute SVGAnimatedEnumeration yChannelSelector;
 };
 
+SVGFEDisplacementMapElement implements SVGFilterPrimitiveStandardAttributes;
diff --git a/Source/core/svg/SVGFEDropShadowElement.cpp b/Source/core/svg/SVGFEDropShadowElement.cpp
index ffddfcc..64609a3 100644
--- a/Source/core/svg/SVGFEDropShadowElement.cpp
+++ b/Source/core/svg/SVGFEDropShadowElement.cpp
@@ -91,7 +91,7 @@
         supportedAttributes.add(SVGNames::dyAttr);
         supportedAttributes.add(SVGNames::stdDeviationAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFEDropShadowElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFEDropShadowElement.idl b/Source/core/svg/SVGFEDropShadowElement.idl
index 840f96f..1c047a3 100644
--- a/Source/core/svg/SVGFEDropShadowElement.idl
+++ b/Source/core/svg/SVGFEDropShadowElement.idl
@@ -17,8 +17,7 @@
  * Boston, MA 02110-1301, USA.
  */
 
-interface SVGFEDropShadowElement : SVGStyledElement,
-                                   SVGFilterPrimitiveStandardAttributes {
+interface SVGFEDropShadowElement : SVGStyledElement {
     readonly attribute SVGAnimatedString in1;
     readonly attribute SVGAnimatedNumber dx;
     readonly attribute SVGAnimatedNumber dy;
@@ -29,3 +28,4 @@
                          [Default=Undefined] optional float stdDeviationY);
 };
 
+SVGFEDropShadowElement implements SVGFilterPrimitiveStandardAttributes;
diff --git a/Source/core/svg/SVGFEFloodElement.idl b/Source/core/svg/SVGFEFloodElement.idl
index 86c973c..6af0bd1 100644
--- a/Source/core/svg/SVGFEFloodElement.idl
+++ b/Source/core/svg/SVGFEFloodElement.idl
@@ -23,6 +23,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGFEFloodElement : SVGStyledElement,
-                              SVGFilterPrimitiveStandardAttributes {
+interface SVGFEFloodElement : SVGStyledElement {
 };
+
+SVGFEFloodElement implements SVGFilterPrimitiveStandardAttributes;
diff --git a/Source/core/svg/SVGFEGaussianBlurElement.cpp b/Source/core/svg/SVGFEGaussianBlurElement.cpp
index c8c1282..30883f8 100644
--- a/Source/core/svg/SVGFEGaussianBlurElement.cpp
+++ b/Source/core/svg/SVGFEGaussianBlurElement.cpp
@@ -81,7 +81,7 @@
         supportedAttributes.add(SVGNames::inAttr);
         supportedAttributes.add(SVGNames::stdDeviationAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFEGaussianBlurElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFEGaussianBlurElement.idl b/Source/core/svg/SVGFEGaussianBlurElement.idl
index ea8b6a8..0cbbb6d 100644
--- a/Source/core/svg/SVGFEGaussianBlurElement.idl
+++ b/Source/core/svg/SVGFEGaussianBlurElement.idl
@@ -23,8 +23,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGFEGaussianBlurElement : SVGStyledElement,
-                                     SVGFilterPrimitiveStandardAttributes {
+interface SVGFEGaussianBlurElement : SVGStyledElement {
     readonly attribute SVGAnimatedString in1;
     readonly attribute SVGAnimatedNumber stdDeviationX;
     readonly attribute SVGAnimatedNumber stdDeviationY;
@@ -33,3 +32,4 @@
                          [Default=Undefined] optional float stdDeviationY);
 };
 
+SVGFEGaussianBlurElement implements SVGFilterPrimitiveStandardAttributes;
diff --git a/Source/core/svg/SVGFEImageElement.cpp b/Source/core/svg/SVGFEImageElement.cpp
index 7c4f717..3b9af6c 100644
--- a/Source/core/svg/SVGFEImageElement.cpp
+++ b/Source/core/svg/SVGFEImageElement.cpp
@@ -118,7 +118,7 @@
         SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::preserveAspectRatioAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFEImageElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFEImageElement.h b/Source/core/svg/SVGFEImageElement.h
index a1c95c0..c409f49 100644
--- a/Source/core/svg/SVGFEImageElement.h
+++ b/Source/core/svg/SVGFEImageElement.h
@@ -28,7 +28,6 @@
 #include "core/svg/SVGAnimatedPreserveAspectRatio.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGFilterPrimitiveStandardAttributes.h"
-#include "core/svg/SVGLangSpace.h"
 #include "core/svg/SVGURIReference.h"
 #include "core/svg/graphics/filters/SVGFEImage.h"
 
@@ -36,7 +35,6 @@
 
 class SVGFEImageElement FINAL : public SVGFilterPrimitiveStandardAttributes,
                                 public SVGURIReference,
-                                public SVGLangSpace,
                                 public SVGExternalResourcesRequired,
                                 public CachedImageClient {
 public:
diff --git a/Source/core/svg/SVGFEImageElement.idl b/Source/core/svg/SVGFEImageElement.idl
index 2220f7d..56eca80 100644
--- a/Source/core/svg/SVGFEImageElement.idl
+++ b/Source/core/svg/SVGFEImageElement.idl
@@ -23,11 +23,11 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGFEImageElement : SVGStyledElement,
-                              SVGURIReference,
-                              SVGLangSpace,
-                              SVGExternalResourcesRequired,
-                              SVGFilterPrimitiveStandardAttributes {
+interface SVGFEImageElement : SVGStyledElement {
     readonly attribute SVGAnimatedPreserveAspectRatio preserveAspectRatio;
 };
 
+SVGFEImageElement implements SVGExternalResourcesRequired;
+SVGFEImageElement implements SVGFilterPrimitiveStandardAttributes;
+SVGFEImageElement implements SVGURIReference;
+
diff --git a/Source/core/svg/SVGFELightElement.cpp b/Source/core/svg/SVGFELightElement.cpp
index 67a9803..56bdb8b 100644
--- a/Source/core/svg/SVGFELightElement.cpp
+++ b/Source/core/svg/SVGFELightElement.cpp
@@ -99,7 +99,7 @@
         supportedAttributes.add(SVGNames::specularExponentAttr);
         supportedAttributes.add(SVGNames::limitingConeAngleAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFELightElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFEMergeElement.idl b/Source/core/svg/SVGFEMergeElement.idl
index cbb7cdf..6688e7c 100644
--- a/Source/core/svg/SVGFEMergeElement.idl
+++ b/Source/core/svg/SVGFEMergeElement.idl
@@ -23,7 +23,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGFEMergeElement : SVGStyledElement,
-                              SVGFilterPrimitiveStandardAttributes {
+interface SVGFEMergeElement : SVGStyledElement {
 };
 
+SVGFEMergeElement implements SVGFilterPrimitiveStandardAttributes;
diff --git a/Source/core/svg/SVGFEMergeNodeElement.cpp b/Source/core/svg/SVGFEMergeNodeElement.cpp
index 77efd3f..508c60b 100644
--- a/Source/core/svg/SVGFEMergeNodeElement.cpp
+++ b/Source/core/svg/SVGFEMergeNodeElement.cpp
@@ -53,7 +53,7 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty())
         supportedAttributes.add(SVGNames::inAttr);
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFEMergeNodeElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFEMorphologyElement.cpp b/Source/core/svg/SVGFEMorphologyElement.cpp
index 2a3e5b8..4718315 100644
--- a/Source/core/svg/SVGFEMorphologyElement.cpp
+++ b/Source/core/svg/SVGFEMorphologyElement.cpp
@@ -84,7 +84,7 @@
         supportedAttributes.add(SVGNames::operatorAttr);
         supportedAttributes.add(SVGNames::radiusAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFEMorphologyElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFEMorphologyElement.idl b/Source/core/svg/SVGFEMorphologyElement.idl
index dcb1efe..47f1152 100644
--- a/Source/core/svg/SVGFEMorphologyElement.idl
+++ b/Source/core/svg/SVGFEMorphologyElement.idl
@@ -25,8 +25,7 @@
 
 [
     DoNotCheckConstants
-] interface SVGFEMorphologyElement : SVGStyledElement,
-                                     SVGFilterPrimitiveStandardAttributes {
+] interface SVGFEMorphologyElement : SVGStyledElement {
     // Morphology Operators
     const unsigned short SVG_MORPHOLOGY_OPERATOR_UNKNOWN  = 0;
     const unsigned short SVG_MORPHOLOGY_OPERATOR_ERODE    = 1;
@@ -41,3 +40,4 @@
                    [Default=Undefined] optional float radiusY);
 };
 
+SVGFEMorphologyElement implements SVGFilterPrimitiveStandardAttributes;
diff --git a/Source/core/svg/SVGFEOffsetElement.cpp b/Source/core/svg/SVGFEOffsetElement.cpp
index 7158dea..f95f2e1 100644
--- a/Source/core/svg/SVGFEOffsetElement.cpp
+++ b/Source/core/svg/SVGFEOffsetElement.cpp
@@ -62,7 +62,7 @@
         supportedAttributes.add(SVGNames::dxAttr);
         supportedAttributes.add(SVGNames::dyAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFEOffsetElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFEOffsetElement.idl b/Source/core/svg/SVGFEOffsetElement.idl
index 11d4ebe..b159c1f 100644
--- a/Source/core/svg/SVGFEOffsetElement.idl
+++ b/Source/core/svg/SVGFEOffsetElement.idl
@@ -23,10 +23,10 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGFEOffsetElement : SVGStyledElement,
-                               SVGFilterPrimitiveStandardAttributes {
+interface SVGFEOffsetElement : SVGStyledElement {
     readonly attribute SVGAnimatedString in1;
     readonly attribute SVGAnimatedNumber dx;
     readonly attribute SVGAnimatedNumber dy;
 };
 
+SVGFEOffsetElement implements SVGFilterPrimitiveStandardAttributes;
diff --git a/Source/core/svg/SVGFESpecularLightingElement.cpp b/Source/core/svg/SVGFESpecularLightingElement.cpp
index ea72216..9589032 100644
--- a/Source/core/svg/SVGFESpecularLightingElement.cpp
+++ b/Source/core/svg/SVGFESpecularLightingElement.cpp
@@ -89,7 +89,7 @@
         supportedAttributes.add(SVGNames::surfaceScaleAttr);
         supportedAttributes.add(SVGNames::kernelUnitLengthAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFESpecularLightingElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFESpecularLightingElement.idl b/Source/core/svg/SVGFESpecularLightingElement.idl
index c9b72bc..2532929 100644
--- a/Source/core/svg/SVGFESpecularLightingElement.idl
+++ b/Source/core/svg/SVGFESpecularLightingElement.idl
@@ -23,11 +23,11 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGFESpecularLightingElement : SVGStyledElement,
-                                         SVGFilterPrimitiveStandardAttributes {
+interface SVGFESpecularLightingElement : SVGStyledElement {
     readonly attribute SVGAnimatedString in1;
     readonly attribute SVGAnimatedNumber surfaceScale;
     readonly attribute SVGAnimatedNumber specularConstant;
     readonly attribute SVGAnimatedNumber specularExponent;
 };
 
+SVGFESpecularLightingElement implements SVGFilterPrimitiveStandardAttributes;
diff --git a/Source/core/svg/SVGFETileElement.cpp b/Source/core/svg/SVGFETileElement.cpp
index d2c518d..9ca6f3c 100644
--- a/Source/core/svg/SVGFETileElement.cpp
+++ b/Source/core/svg/SVGFETileElement.cpp
@@ -55,7 +55,7 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty())
         supportedAttributes.add(SVGNames::inAttr);
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFETileElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFETileElement.idl b/Source/core/svg/SVGFETileElement.idl
index 352fb75..cdff622 100644
--- a/Source/core/svg/SVGFETileElement.idl
+++ b/Source/core/svg/SVGFETileElement.idl
@@ -23,8 +23,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGFETileElement : SVGStyledElement,
-                             SVGFilterPrimitiveStandardAttributes {
+interface SVGFETileElement : SVGStyledElement {
     readonly attribute SVGAnimatedString in1;
 };
 
+SVGFETileElement implements SVGFilterPrimitiveStandardAttributes;
diff --git a/Source/core/svg/SVGFETurbulenceElement.cpp b/Source/core/svg/SVGFETurbulenceElement.cpp
index 709ee4c..2aebbb6 100644
--- a/Source/core/svg/SVGFETurbulenceElement.cpp
+++ b/Source/core/svg/SVGFETurbulenceElement.cpp
@@ -84,7 +84,7 @@
         supportedAttributes.add(SVGNames::stitchTilesAttr);
         supportedAttributes.add(SVGNames::typeAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFETurbulenceElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGFETurbulenceElement.idl b/Source/core/svg/SVGFETurbulenceElement.idl
index b4a326f..a95a534 100644
--- a/Source/core/svg/SVGFETurbulenceElement.idl
+++ b/Source/core/svg/SVGFETurbulenceElement.idl
@@ -25,8 +25,7 @@
 
 [
     DoNotCheckConstants
-] interface SVGFETurbulenceElement : SVGStyledElement,
-                                     SVGFilterPrimitiveStandardAttributes {
+] interface SVGFETurbulenceElement : SVGStyledElement {
     // Turbulence Types
     const unsigned short SVG_TURBULENCE_TYPE_UNKNOWN      = 0;
     const unsigned short SVG_TURBULENCE_TYPE_FRACTALNOISE = 1;
@@ -45,3 +44,4 @@
     readonly attribute SVGAnimatedEnumeration type;
 };
 
+SVGFETurbulenceElement implements SVGFilterPrimitiveStandardAttributes;
diff --git a/Source/core/svg/SVGFilterElement.cpp b/Source/core/svg/SVGFilterElement.cpp
index 7335c74..0f2cbb3 100644
--- a/Source/core/svg/SVGFilterElement.cpp
+++ b/Source/core/svg/SVGFilterElement.cpp
@@ -115,7 +115,7 @@
         supportedAttributes.add(SVGNames::heightAttr);
         supportedAttributes.add(SVGNames::filterResAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFilterElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -185,9 +185,9 @@
         object->setNeedsLayout(true);
 }
 
-RenderObject* SVGFilterElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGFilterElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGResourceFilter(this);
+    return new (document()->renderArena()) RenderSVGResourceFilter(this);
 }
 
 bool SVGFilterElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
@@ -226,7 +226,7 @@
         allowedChildElementTags.add(SVGNames::feTurbulenceTag);
     }
 
-    return allowedChildElementTags.contains<QualifiedName, SVGAttributeHashTranslator>(svgElement->tagQName());
+    return allowedChildElementTags.contains<SVGAttributeHashTranslator>(svgElement->tagQName());
 }
 
 bool SVGFilterElement::selfHasRelativeLengths() const
diff --git a/Source/core/svg/SVGFilterElement.h b/Source/core/svg/SVGFilterElement.h
index 8f3f155..f3429fc 100644
--- a/Source/core/svg/SVGFilterElement.h
+++ b/Source/core/svg/SVGFilterElement.h
@@ -29,7 +29,6 @@
 #include "core/svg/SVGAnimatedInteger.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGLangSpace.h"
 #include "core/svg/SVGStyledElement.h"
 #include "core/svg/SVGURIReference.h"
 #include "core/svg/SVGUnitTypes.h"
@@ -38,7 +37,6 @@
 
 class SVGFilterElement FINAL : public SVGStyledElement,
                                public SVGURIReference,
-                               public SVGLangSpace,
                                public SVGExternalResourcesRequired {
 public:
     static PassRefPtr<SVGFilterElement> create(const QualifiedName&, Document*);
@@ -55,7 +53,7 @@
     virtual void svgAttributeChanged(const QualifiedName&);
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const OVERRIDE;
 
     virtual bool selfHasRelativeLengths() const;
diff --git a/Source/core/svg/SVGFilterElement.idl b/Source/core/svg/SVGFilterElement.idl
index a33b461..fd417bb 100644
--- a/Source/core/svg/SVGFilterElement.idl
+++ b/Source/core/svg/SVGFilterElement.idl
@@ -24,11 +24,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGFilterElement : SVGStyledElement,
-                             SVGURIReference,
-                             SVGLangSpace,
-                             SVGExternalResourcesRequired
-                             /* SVGUnitTypes */ {
+interface SVGFilterElement : SVGStyledElement {
     readonly attribute SVGAnimatedEnumeration filterUnits;
     readonly attribute SVGAnimatedEnumeration primitiveUnits;
     readonly attribute SVGAnimatedLength      x;
@@ -42,3 +38,6 @@
                       [Default=Undefined] optional unsigned long filterResY);
 };
 
+SVGFilterElement implements SVGExternalResourcesRequired;
+SVGFilterElement implements SVGURIReference;
+
diff --git a/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp b/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp
index 3a283a0..67c29ee 100644
--- a/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp
+++ b/Source/core/svg/SVGFilterPrimitiveStandardAttributes.cpp
@@ -70,7 +70,7 @@
         supportedAttributes.add(SVGNames::heightAttr);
         supportedAttributes.add(SVGNames::resultAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGFilterPrimitiveStandardAttributes::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -137,9 +137,9 @@
         filterEffect->setHasHeight(true);
 }
 
-RenderObject* SVGFilterPrimitiveStandardAttributes::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGFilterPrimitiveStandardAttributes::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGResourceFilterPrimitive(this);
+    return new (document()->renderArena()) RenderSVGResourceFilterPrimitive(this);
 }
 
 bool SVGFilterPrimitiveStandardAttributes::rendererIsNeeded(const NodeRenderingContext& context)
diff --git a/Source/core/svg/SVGFilterPrimitiveStandardAttributes.h b/Source/core/svg/SVGFilterPrimitiveStandardAttributes.h
index d2b94a7..18870ab 100644
--- a/Source/core/svg/SVGFilterPrimitiveStandardAttributes.h
+++ b/Source/core/svg/SVGFilterPrimitiveStandardAttributes.h
@@ -67,7 +67,7 @@
 private:
     virtual bool isFilterEffect() const { return true; }
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*) OVERRIDE;
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
     virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const OVERRIDE { return false; }
 
diff --git a/Source/core/svg/SVGFilterPrimitiveStandardAttributes.idl b/Source/core/svg/SVGFilterPrimitiveStandardAttributes.idl
index 7c524f3..62fb567 100644
--- a/Source/core/svg/SVGFilterPrimitiveStandardAttributes.idl
+++ b/Source/core/svg/SVGFilterPrimitiveStandardAttributes.idl
@@ -24,7 +24,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGFilterPrimitiveStandardAttributes {
+[
+    NoInterfaceObject
+] interface SVGFilterPrimitiveStandardAttributes {
     readonly attribute SVGAnimatedLength x;
     readonly attribute SVGAnimatedLength y;
     readonly attribute SVGAnimatedLength width;
diff --git a/Source/core/svg/SVGFitToViewBox.cpp b/Source/core/svg/SVGFitToViewBox.cpp
index 20c52a4..a123bc1 100644
--- a/Source/core/svg/SVGFitToViewBox.cpp
+++ b/Source/core/svg/SVGFitToViewBox.cpp
@@ -34,44 +34,38 @@
 
 namespace WebCore {
 
-bool SVGFitToViewBox::parseViewBox(Document* doc, const String& s, FloatRect& viewBox)
+template<typename CharType>
+static bool parseViewBoxInternal(Document* document, const CharType*& ptr, const CharType* end, FloatRect& viewBox, bool validate)
 {
-    const UChar* c = s.characters();
-    const UChar* end = c + s.length();
-    return parseViewBox(doc, c, end, viewBox, true);
-}
+    const CharType* start = ptr;
 
-bool SVGFitToViewBox::parseViewBox(Document* doc, const UChar*& c, const UChar* end, FloatRect& viewBox, bool validate)
-{
-    String str(c, end - c);
-
-    skipOptionalSVGSpaces(c, end);
+    skipOptionalSVGSpaces(ptr, end);
 
     float x = 0.0f;
     float y = 0.0f;
     float width = 0.0f;
     float height = 0.0f;
-    bool valid = parseNumber(c, end, x) && parseNumber(c, end, y) && parseNumber(c, end, width) && parseNumber(c, end, height, false);
+    bool valid = parseNumber(ptr, end, x) && parseNumber(ptr, end, y) && parseNumber(ptr, end, width) && parseNumber(ptr, end, height, false);
     if (!validate) {
         viewBox = FloatRect(x, y, width, height);
         return true;
     }
     if (!valid) {
-        doc->accessSVGExtensions()->reportWarning("Problem parsing viewBox=\"" + str + "\"");
+        document->accessSVGExtensions()->reportWarning("Problem parsing viewBox=\"" + String(start, end - start) + "\"");
         return false;
     }
 
     if (width < 0.0) { // check that width is positive
-        doc->accessSVGExtensions()->reportError("A negative value for ViewBox width is not allowed");
+        document->accessSVGExtensions()->reportError("A negative value for ViewBox width is not allowed");
         return false;
     }
     if (height < 0.0) { // check that height is positive
-        doc->accessSVGExtensions()->reportError("A negative value for ViewBox height is not allowed");
+        document->accessSVGExtensions()->reportError("A negative value for ViewBox height is not allowed");
         return false;
     }
-    skipOptionalSVGSpaces(c, end);
-    if (c < end) { // nothing should come after the last, fourth number
-        doc->accessSVGExtensions()->reportWarning("Problem parsing viewBox=\"" + str + "\"");
+    skipOptionalSVGSpaces(ptr, end);
+    if (ptr < end) { // nothing should come after the last, fourth number
+        document->accessSVGExtensions()->reportWarning("Problem parsing viewBox=\"" + String(start, end - start) + "\"");
         return false;
     }
 
@@ -79,6 +73,32 @@
     return true;
 }
 
+bool SVGFitToViewBox::parseViewBox(Document* document, const LChar*& ptr, const LChar* end, FloatRect& viewBox, bool validate)
+{
+    return parseViewBoxInternal(document, ptr, end, viewBox, validate);
+}
+
+bool SVGFitToViewBox::parseViewBox(Document* document, const UChar*& ptr, const UChar* end, FloatRect& viewBox, bool validate)
+{
+    return parseViewBoxInternal(document, ptr, end, viewBox, validate);
+}
+
+bool SVGFitToViewBox::parseViewBox(Document* document, const String& string, FloatRect& viewBox)
+{
+    if (string.isEmpty()) {
+        const LChar* ptr = 0;
+        return parseViewBoxInternal<LChar>(document, ptr, ptr, viewBox, true);
+    }
+    if (string.is8Bit()) {
+        const LChar* ptr = string.characters8();
+        const LChar* end = ptr + string.length();
+        return parseViewBox(document, ptr, end, viewBox, true);
+    }
+    const UChar* ptr = string.characters16();
+    const UChar* end = ptr + string.length();
+    return parseViewBox(document, ptr, end, viewBox, true);
+}
+
 AffineTransform SVGFitToViewBox::viewBoxToViewTransform(const FloatRect& viewBoxRect, const SVGPreserveAspectRatio& preserveAspectRatio, float viewWidth, float viewHeight)
 {
     if (!viewBoxRect.width() || !viewBoxRect.height())
diff --git a/Source/core/svg/SVGFitToViewBox.h b/Source/core/svg/SVGFitToViewBox.h
index 6382e74..e55d271 100644
--- a/Source/core/svg/SVGFitToViewBox.h
+++ b/Source/core/svg/SVGFitToViewBox.h
@@ -62,6 +62,7 @@
         return false;
     }
 
+    static bool parseViewBox(Document*, const LChar*& start, const LChar* end, FloatRect& viewBox, bool validate = true);
     static bool parseViewBox(Document*, const UChar*& start, const UChar* end, FloatRect& viewBox, bool validate = true);
 
 private:
diff --git a/Source/core/svg/SVGFitToViewBox.idl b/Source/core/svg/SVGFitToViewBox.idl
index 261684e..a6388ab 100644
--- a/Source/core/svg/SVGFitToViewBox.idl
+++ b/Source/core/svg/SVGFitToViewBox.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    DoNotGenerateToV8
+    NoInterfaceObject
 ] interface SVGFitToViewBox {
     readonly attribute SVGAnimatedRect                viewBox;
     readonly attribute SVGAnimatedPreserveAspectRatio preserveAspectRatio;
diff --git a/Source/core/svg/SVGFontData.cpp b/Source/core/svg/SVGFontData.cpp
index a8c0b51..2dcf9f8 100644
--- a/Source/core/svg/SVGFontData.cpp
+++ b/Source/core/svg/SVGFontData.cpp
@@ -145,7 +145,7 @@
     }
 
     if (mirror)
-        remainingTextInRun = createStringWithMirroredCharacters(remainingTextInRun.characters(), remainingTextInRun.length());
+        remainingTextInRun = createStringWithMirroredCharacters(remainingTextInRun.bloatedCharacters(), remainingTextInRun.length());
     if (!currentCharacter && arabicForms.isEmpty())
         arabicForms = charactersWithArabicForm(remainingTextInRun, mirror);
 
diff --git a/Source/core/svg/SVGFontElement.cpp b/Source/core/svg/SVGFontElement.cpp
index 75735b5..1ebcdbf 100644
--- a/Source/core/svg/SVGFontElement.cpp
+++ b/Source/core/svg/SVGFontElement.cpp
@@ -99,7 +99,7 @@
         unsigned unicodeLength = unicode.length();
         ASSERT(unicodeLength > 1);
 
-        const UChar* characters = unicode.characters();
+        const UChar* characters = unicode.bloatedCharacters();
         for (unsigned i = 0; i < unicodeLength; ++i) {
             String lookupString(characters + i, 1);
             m_glyphMap.collectGlyphsForString(lookupString, glyphs);
diff --git a/Source/core/svg/SVGForeignObjectElement.cpp b/Source/core/svg/SVGForeignObjectElement.cpp
index 823dc45..bb1bf66 100644
--- a/Source/core/svg/SVGForeignObjectElement.cpp
+++ b/Source/core/svg/SVGForeignObjectElement.cpp
@@ -47,12 +47,11 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(height)
     REGISTER_LOCAL_ANIMATED_PROPERTY(href)
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGForeignObjectElement::SVGForeignObjectElement(const QualifiedName& tagName, Document* document)
-    : SVGStyledTransformableElement(tagName, document)
+    : SVGGraphicsElement(tagName, document)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
     , m_width(LengthModeWidth)
@@ -72,7 +71,6 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGTests::addSupportedAttributes(supportedAttributes);
         SVGLangSpace::addSupportedAttributes(supportedAttributes);
         SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::xAttr);
@@ -80,7 +78,7 @@
         supportedAttributes.add(SVGNames::widthAttr);
         supportedAttributes.add(SVGNames::heightAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGForeignObjectElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -88,7 +86,7 @@
     SVGParsingError parseError = NoError;
 
     if (!isSupportedAttribute(name))
-        SVGStyledTransformableElement::parseAttribute(name, value);
+        SVGGraphicsElement::parseAttribute(name, value);
     else if (name == SVGNames::xAttr)
         setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
     else if (name == SVGNames::yAttr)
@@ -97,8 +95,7 @@
         setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
     else if (name == SVGNames::heightAttr)
         setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
-    else if (SVGTests::parseAttribute(name, value)
-               || SVGLangSpace::parseAttribute(name, value)
+    else if (SVGLangSpace::parseAttribute(name, value)
                || SVGExternalResourcesRequired::parseAttribute(name, value)) {
     } else
         ASSERT_NOT_REACHED();
@@ -109,7 +106,7 @@
 void SVGForeignObjectElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGStyledTransformableElement::svgAttributeChanged(attrName);
+        SVGGraphicsElement::svgAttributeChanged(attrName);
         return;
     }
 
@@ -123,16 +120,13 @@
     if (isLengthAttribute)
         updateRelativeLengthsInformation();
 
-    if (SVGTests::handleAttributeChange(this, attrName))
-        return;
-
     if (RenderObject* renderer = this->renderer())
         RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
 }
 
-RenderObject* SVGForeignObjectElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGForeignObjectElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGForeignObject(this);
+    return new (document()->renderArena()) RenderSVGForeignObject(this);
 }
 
 bool SVGForeignObjectElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
@@ -142,7 +136,7 @@
         return childContext.node()->hasTagName(SVGNames::svgTag);
 
     // Skip over SVG rules which disallow non-SVG kids
-    return StyledElement::childShouldCreateRenderer(childContext);
+    return Element::childShouldCreateRenderer(childContext);
 }
 
 bool SVGForeignObjectElement::rendererIsNeeded(const NodeRenderingContext& context)
@@ -160,7 +154,7 @@
         ancestor = ancestor->parentElement();
     }
 
-    return SVGStyledTransformableElement::rendererIsNeeded(context);
+    return SVGGraphicsElement::rendererIsNeeded(context);
 }
 
 bool SVGForeignObjectElement::selfHasRelativeLengths() const
diff --git a/Source/core/svg/SVGForeignObjectElement.h b/Source/core/svg/SVGForeignObjectElement.h
index f658759..8b2a536 100644
--- a/Source/core/svg/SVGForeignObjectElement.h
+++ b/Source/core/svg/SVGForeignObjectElement.h
@@ -23,16 +23,12 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGLangSpace.h"
-#include "core/svg/SVGStyledTransformableElement.h"
-#include "core/svg/SVGTests.h"
+#include "core/svg/SVGGraphicsElement.h"
 #include "core/svg/SVGURIReference.h"
 
 namespace WebCore {
 
-class SVGForeignObjectElement FINAL : public SVGStyledTransformableElement,
-                                      public SVGTests,
-                                      public SVGLangSpace,
+class SVGForeignObjectElement FINAL : public SVGGraphicsElement,
                                       public SVGExternalResourcesRequired {
 public:
     static PassRefPtr<SVGForeignObjectElement> create(const QualifiedName&, Document*);
@@ -47,7 +43,7 @@
 
     virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
-    virtual RenderObject* createRenderer(RenderArena* arena, RenderStyle* style);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     virtual bool selfHasRelativeLengths() const;
 
@@ -59,11 +55,6 @@
         DECLARE_ANIMATED_STRING(Href, href)
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
-
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGForeignObjectElement.idl b/Source/core/svg/SVGForeignObjectElement.idl
index eecedf8..e8a02fc 100644
--- a/Source/core/svg/SVGForeignObjectElement.idl
+++ b/Source/core/svg/SVGForeignObjectElement.idl
@@ -23,14 +23,12 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGForeignObjectElement : SVGStyledElement,
-                                    SVGTests,
-                                    SVGLangSpace,
-                                    SVGExternalResourcesRequired,
-                                    SVGTransformable {
+interface SVGForeignObjectElement : SVGGraphicsElement {
     readonly attribute SVGAnimatedLength x;
     readonly attribute SVGAnimatedLength y;
     readonly attribute SVGAnimatedLength width;
     readonly attribute SVGAnimatedLength height;
 };
 
+SVGForeignObjectElement implements SVGExternalResourcesRequired;
+
diff --git a/Source/core/svg/SVGGElement.cpp b/Source/core/svg/SVGGElement.cpp
index 14558c0..8693bc3 100644
--- a/Source/core/svg/SVGGElement.cpp
+++ b/Source/core/svg/SVGGElement.cpp
@@ -35,12 +35,11 @@
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGGElement)
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 SVGGElement::SVGGElement(const QualifiedName& tagName, Document* document, ConstructionType constructionType)
-    : SVGStyledTransformableElement(tagName, document, constructionType)
+    : SVGGraphicsElement(tagName, document, constructionType)
 {
     ASSERT(hasTagName(SVGNames::gTag));
     ScriptWrappable::init(this);
@@ -56,22 +55,19 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGTests::addSupportedAttributes(supportedAttributes);
         SVGLangSpace::addSupportedAttributes(supportedAttributes);
         SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGGElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
     if (!isSupportedAttribute(name)) {
-        SVGStyledTransformableElement::parseAttribute(name, value);
+        SVGGraphicsElement::parseAttribute(name, value);
         return;
     }
 
-    if (SVGTests::parseAttribute(name, value))
-        return;
     if (SVGLangSpace::parseAttribute(name, value))
         return;
     if (SVGExternalResourcesRequired::parseAttribute(name, value))
@@ -83,29 +79,26 @@
 void SVGGElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGStyledTransformableElement::svgAttributeChanged(attrName);
+        SVGGraphicsElement::svgAttributeChanged(attrName);
         return;
     }
 
     SVGElementInstance::InvalidationGuard invalidationGuard(this);
-    
-    if (SVGTests::handleAttributeChange(this, attrName))
-        return;
 
     if (RenderObject* renderer = this->renderer())
         RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
 }
 
-RenderObject* SVGGElement::createRenderer(RenderArena* arena, RenderStyle* style)
+RenderObject* SVGGElement::createRenderer(RenderStyle* style)
 {
     // SVG 1.1 testsuite explicitely uses constructs like <g display="none"><linearGradient>
     // We still have to create renderers for the <g> & <linearGradient> element, though the
     // subtree may be hidden - we only want the resource renderers to exist so they can be
     // referenced from somewhere else.
     if (style->display() == NONE)
-        return new (arena) RenderSVGHiddenContainer(this);
+        return new (document()->renderArena()) RenderSVGHiddenContainer(this);
 
-    return new (arena) RenderSVGTransformableContainer(this);
+    return new (document()->renderArena()) RenderSVGTransformableContainer(this);
 }
 
 bool SVGGElement::rendererIsNeeded(const NodeRenderingContext&)
diff --git a/Source/core/svg/SVGGElement.h b/Source/core/svg/SVGGElement.h
index a3077f5..fa64a9f 100644
--- a/Source/core/svg/SVGGElement.h
+++ b/Source/core/svg/SVGGElement.h
@@ -23,15 +23,11 @@
 
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGLangSpace.h"
-#include "core/svg/SVGStyledTransformableElement.h"
-#include "core/svg/SVGTests.h"
+#include "core/svg/SVGGraphicsElement.h"
 
 namespace WebCore {
 
-class SVGGElement FINAL : public SVGStyledTransformableElement,
-                          public SVGTests,
-                          public SVGLangSpace,
+class SVGGElement FINAL : public SVGGraphicsElement,
                           public SVGExternalResourcesRequired {
 public:
     static PassRefPtr<SVGGElement> create(const QualifiedName&, Document*);
@@ -39,7 +35,7 @@
 protected:
     SVGGElement(const QualifiedName&, Document*, ConstructionType = CreateSVGElement);
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
 private:
     virtual bool isValid() const { return SVGTests::isValid(); }
@@ -54,11 +50,6 @@
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGGElement)
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
-
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGGElement.idl b/Source/core/svg/SVGGElement.idl
index a6dd6b3..ea12d15 100644
--- a/Source/core/svg/SVGGElement.idl
+++ b/Source/core/svg/SVGGElement.idl
@@ -23,10 +23,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGGElement : SVGStyledElement,
-                        SVGTests,
-                        SVGLangSpace,
-                        SVGExternalResourcesRequired,
-                        SVGTransformable {
+interface SVGGElement : SVGGraphicsElement {
 };
 
+SVGGElement implements SVGExternalResourcesRequired;
+
diff --git a/Source/core/svg/SVGGlyphMap.h b/Source/core/svg/SVGGlyphMap.h
index 1e4153b..90586a8 100644
--- a/Source/core/svg/SVGGlyphMap.h
+++ b/Source/core/svg/SVGGlyphMap.h
@@ -69,7 +69,7 @@
 
         UChar32 character = 0;
         unsigned clusterLength = 0;
-        SurrogatePairAwareTextIterator textIterator(unicodeString.characters(), 0, length, length);
+        SurrogatePairAwareTextIterator textIterator(unicodeString.bloatedCharacters(), 0, length, length);
         while (textIterator.consume(character, clusterLength)) {
             node = currentLayer->get(character);
             if (!node) {
@@ -114,7 +114,7 @@
     {
         GlyphMapLayer* currentLayer = &m_rootLayer;
 
-        const UChar* characters = string.characters();
+        const UChar* characters = string.bloatedCharacters();
         size_t length = string.length();
 
         UChar32 character = 0;
diff --git a/Source/core/svg/SVGGlyphRefElement.idl b/Source/core/svg/SVGGlyphRefElement.idl
index 123e8a5..a9d07ca 100644
--- a/Source/core/svg/SVGGlyphRefElement.idl
+++ b/Source/core/svg/SVGGlyphRefElement.idl
@@ -17,8 +17,9 @@
  * Boston, MA 02110-1301, USA.
  */
 
-[Conditional=SVG_FONTS] interface SVGGlyphRefElement : SVGStyledElement,
-                                                           SVGURIReference {
+[
+    Conditional=SVG_FONTS
+] interface SVGGlyphRefElement : SVGStyledElement {
     // FIXME: Use [Reflect] after https://bugs.webkit.org/show_bug.cgi?id=64843 is fixed.
     attribute DOMString glyphRef;
     [Reflect] attribute DOMString format;
@@ -28,3 +29,5 @@
     attribute float dy;
 };
 
+SVGGlyphRefElement implements SVGURIReference;
+
diff --git a/Source/core/svg/SVGGradientElement.cpp b/Source/core/svg/SVGGradientElement.cpp
index 64edfd3..777539d 100644
--- a/Source/core/svg/SVGGradientElement.cpp
+++ b/Source/core/svg/SVGGradientElement.cpp
@@ -71,7 +71,7 @@
         supportedAttributes.add(SVGNames::gradientTransformAttr);
         supportedAttributes.add(SVGNames::spreadMethodAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGGradientElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGGradientElement.idl b/Source/core/svg/SVGGradientElement.idl
index 50047cf..e378d7f 100644
--- a/Source/core/svg/SVGGradientElement.idl
+++ b/Source/core/svg/SVGGradientElement.idl
@@ -25,10 +25,7 @@
 
 [
     DoNotCheckConstants
-] interface SVGGradientElement : SVGStyledElement,
-                                 SVGURIReference,
-                                 SVGExternalResourcesRequired
-                                 /* SVGUnitTypes */ {
+] interface SVGGradientElement : SVGStyledElement {
     // Spread Method Types
     const unsigned short SVG_SPREADMETHOD_UNKNOWN = 0;
     const unsigned short SVG_SPREADMETHOD_PAD     = 1;
@@ -40,3 +37,6 @@
     readonly attribute SVGAnimatedEnumeration   spreadMethod;
 };
 
+SVGGradientElement implements SVGExternalResourcesRequired;
+SVGGradientElement implements SVGURIReference;
+
diff --git a/Source/core/svg/SVGStyledTransformableElement.cpp b/Source/core/svg/SVGGraphicsElement.cpp
similarity index 66%
rename from Source/core/svg/SVGStyledTransformableElement.cpp
rename to Source/core/svg/SVGGraphicsElement.cpp
index 153faab..2dfd3de 100644
--- a/Source/core/svg/SVGStyledTransformableElement.cpp
+++ b/Source/core/svg/SVGGraphicsElement.cpp
@@ -20,7 +20,7 @@
 
 #include "config.h"
 
-#include "core/svg/SVGStyledTransformableElement.h"
+#include "core/svg/SVGGraphicsElement.h"
 
 #include "SVGNames.h"
 #include "core/platform/graphics/transforms/AffineTransform.h"
@@ -32,34 +32,35 @@
 namespace WebCore {
 
 // Animated property definitions
-DEFINE_ANIMATED_TRANSFORM_LIST(SVGStyledTransformableElement, SVGNames::transformAttr, Transform, transform)
+DEFINE_ANIMATED_TRANSFORM_LIST(SVGGraphicsElement, SVGNames::transformAttr, Transform, transform)
 
-BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
+BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGGraphicsElement)
     REGISTER_LOCAL_ANIMATED_PROPERTY(transform)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledLocatableElement)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledElement)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
 END_REGISTER_ANIMATED_PROPERTIES
 
-SVGStyledTransformableElement::SVGStyledTransformableElement(const QualifiedName& tagName, Document* document, ConstructionType constructionType)
-    : SVGStyledLocatableElement(tagName, document, constructionType)
+SVGGraphicsElement::SVGGraphicsElement(const QualifiedName& tagName, Document* document, ConstructionType constructionType)
+    : SVGStyledElement(tagName, document, constructionType)
 {
-    registerAnimatedPropertiesForSVGStyledTransformableElement();
+    registerAnimatedPropertiesForSVGGraphicsElement();
 }
 
-SVGStyledTransformableElement::~SVGStyledTransformableElement()
+SVGGraphicsElement::~SVGGraphicsElement()
 {
 }
 
-AffineTransform SVGStyledTransformableElement::getCTM(StyleUpdateStrategy styleUpdateStrategy)
+AffineTransform SVGGraphicsElement::getCTM(StyleUpdateStrategy styleUpdateStrategy)
 {
     return SVGLocatable::computeCTM(this, SVGLocatable::NearestViewportScope, styleUpdateStrategy);
 }
 
-AffineTransform SVGStyledTransformableElement::getScreenCTM(StyleUpdateStrategy styleUpdateStrategy)
+AffineTransform SVGGraphicsElement::getScreenCTM(StyleUpdateStrategy styleUpdateStrategy)
 {
     return SVGLocatable::computeCTM(this, SVGLocatable::ScreenScope, styleUpdateStrategy);
 }
 
-AffineTransform SVGStyledTransformableElement::animatedLocalTransform() const
+AffineTransform SVGGraphicsElement::animatedLocalTransform() const
 {
     AffineTransform matrix;
     RenderStyle* style = renderer() ? renderer()->style() : 0;
@@ -73,33 +74,36 @@
 
         // Flatten any 3D transform.
         matrix = transform.toAffineTransform();
-    } else
+    } else {
         transform().concatenate(matrix);
+    }
 
     if (m_supplementalTransform)
         return *m_supplementalTransform * matrix;
     return matrix;
 }
 
-AffineTransform* SVGStyledTransformableElement::supplementalTransform()
+AffineTransform* SVGGraphicsElement::supplementalTransform()
 {
     if (!m_supplementalTransform)
         m_supplementalTransform = adoptPtr(new AffineTransform);
     return m_supplementalTransform.get();
 }
 
-bool SVGStyledTransformableElement::isSupportedAttribute(const QualifiedName& attrName)
+bool SVGGraphicsElement::isSupportedAttribute(const QualifiedName& attrName)
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
-    if (supportedAttributes.isEmpty())
+    if (supportedAttributes.isEmpty()) {
+        SVGTests::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::transformAttr);
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    }
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
-void SVGStyledTransformableElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
+void SVGGraphicsElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
     if (!isSupportedAttribute(name)) {
-        SVGStyledLocatableElement::parseAttribute(name, value);
+        SVGStyledElement::parseAttribute(name, value);
         return;
     }
 
@@ -109,20 +113,25 @@
         detachAnimatedTransformListWrappers(newList.size());
         setTransformBaseValue(newList);
         return;
+    } else if (SVGTests::parseAttribute(name, value)) {
+        return;
     }
 
     ASSERT_NOT_REACHED();
 }
 
-void SVGStyledTransformableElement::svgAttributeChanged(const QualifiedName& attrName)
+void SVGGraphicsElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGStyledLocatableElement::svgAttributeChanged(attrName);
+        SVGStyledElement::svgAttributeChanged(attrName);
         return;
     }
 
     SVGElementInstance::InvalidationGuard invalidationGuard(this);
 
+    if (SVGTests::handleAttributeChange(this, attrName))
+        return;
+
     RenderObject* object = renderer();
     if (!object)
         return;
@@ -136,28 +145,28 @@
     ASSERT_NOT_REACHED();
 }
 
-SVGElement* SVGStyledTransformableElement::nearestViewportElement() const
+SVGElement* SVGGraphicsElement::nearestViewportElement() const
 {
     return SVGTransformable::nearestViewportElement(this);
 }
 
-SVGElement* SVGStyledTransformableElement::farthestViewportElement() const
+SVGElement* SVGGraphicsElement::farthestViewportElement() const
 {
     return SVGTransformable::farthestViewportElement(this);
 }
 
-FloatRect SVGStyledTransformableElement::getBBox(StyleUpdateStrategy styleUpdateStrategy)
+FloatRect SVGGraphicsElement::getBBox(StyleUpdateStrategy styleUpdateStrategy)
 {
     return SVGTransformable::getBBox(this, styleUpdateStrategy);
 }
 
-RenderObject* SVGStyledTransformableElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGGraphicsElement::createRenderer(RenderStyle*)
 {
     // By default, any subclass is expected to do path-based drawing
-    return new (arena) RenderSVGPath(this);
+    return new (document()->renderArena()) RenderSVGPath(this);
 }
 
-void SVGStyledTransformableElement::toClipPath(Path& path)
+void SVGGraphicsElement::toClipPath(Path& path)
 {
     updatePathFromGraphicsElement(this, path);
     // FIXME: How do we know the element has done a layout?
diff --git a/Source/core/svg/SVGStyledTransformableElement.h b/Source/core/svg/SVGGraphicsElement.h
similarity index 70%
rename from Source/core/svg/SVGStyledTransformableElement.h
rename to Source/core/svg/SVGGraphicsElement.h
index e901970..01a0ca3 100644
--- a/Source/core/svg/SVGStyledTransformableElement.h
+++ b/Source/core/svg/SVGGraphicsElement.h
@@ -18,11 +18,12 @@
  * Boston, MA 02110-1301, USA.
  */
 
-#ifndef SVGStyledTransformableElement_h
-#define SVGStyledTransformableElement_h
+#ifndef SVGGraphicsElement_h
+#define SVGGraphicsElement_h
 
 #include "core/svg/SVGAnimatedTransformList.h"
-#include "core/svg/SVGStyledLocatableElement.h"
+#include "core/svg/SVGStyledElement.h"
+#include "core/svg/SVGTests.h"
 #include "core/svg/SVGTransformable.h"
 
 namespace WebCore {
@@ -30,10 +31,9 @@
 class AffineTransform;
 class Path;
 
-class SVGStyledTransformableElement : public SVGStyledLocatableElement,
-                                      public SVGTransformable {
+class SVGGraphicsElement : public SVGStyledElement, public SVGTransformable, public SVGTests {
 public:
-    virtual ~SVGStyledTransformableElement();
+    virtual ~SVGGraphicsElement();
 
     virtual AffineTransform getCTM(StyleUpdateStrategy = AllowStyleUpdate);
     virtual AffineTransform getScreenCTM(StyleUpdateStrategy = AllowStyleUpdate);
@@ -48,33 +48,38 @@
 
     // "base class" methods for all the elements which render as paths
     virtual void toClipPath(Path&);
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
 protected:
-    SVGStyledTransformableElement(const QualifiedName&, Document*, ConstructionType = CreateSVGElement);
+    SVGGraphicsElement(const QualifiedName&, Document*, ConstructionType = CreateSVGElement);
 
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void svgAttributeChanged(const QualifiedName&);
 
-    BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
+    BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGGraphicsElement)
         DECLARE_ANIMATED_TRANSFORM_LIST(Transform, transform)
     END_DECLARE_ANIMATED_PROPERTIES
 
 private:
-    virtual bool isStyledTransformable() const OVERRIDE { return true; }
+    virtual bool isSVGGraphicsElement() const OVERRIDE { return true; }
+
+    // SVGTests
+    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
+    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
+    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
 
     // Used by <animateMotion>
     OwnPtr<AffineTransform> m_supplementalTransform;
 };
 
-inline SVGStyledTransformableElement* toSVGStyledTransformableElement(Node* node)
+inline SVGGraphicsElement* toSVGGraphicsElement(Node* node)
 {
     ASSERT_WITH_SECURITY_IMPLICATION(!node || node->isSVGElement());
-    ASSERT_WITH_SECURITY_IMPLICATION(!node || toSVGElement(node)->isStyledTransformable());
-    return static_cast<SVGStyledTransformableElement*>(node);
+    ASSERT_WITH_SECURITY_IMPLICATION(!node || toSVGElement(node)->isSVGGraphicsElement());
+    return static_cast<SVGGraphicsElement*>(node);
 }
 
 } // namespace WebCore
 
-#endif // SVGStyledTransformableElement_h
+#endif // SVGGraphicsElement_h
diff --git a/Source/core/workers/DedicatedWorkerContext.idl b/Source/core/svg/SVGGraphicsElement.idl
similarity index 74%
copy from Source/core/workers/DedicatedWorkerContext.idl
copy to Source/core/svg/SVGGraphicsElement.idl
index 3f4f45c..a0585ae 100644
--- a/Source/core/workers/DedicatedWorkerContext.idl
+++ b/Source/core/svg/SVGGraphicsElement.idl
@@ -1,5 +1,5 @@
 /*
- * Copyright (C) 2009, 2011 Google Inc. All rights reserved.
+ * Copyright (C) 2013 Samsung Electronics. All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
  * modification, are permitted provided that the following conditions are
@@ -28,10 +28,16 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-[
-    NoInterfaceObject
-] interface DedicatedWorkerContext : WorkerContext {
-    [Custom, RaisesException] void postMessage(any message, optional Array messagePorts);
-    attribute EventListener onmessage;
+interface SVGGraphicsElement : SVGStyledElement {
+    readonly attribute SVGAnimatedTransformList transform;
+
+    readonly attribute SVGElement nearestViewportElement;
+    readonly attribute SVGElement farthestViewportElement;
+
+    SVGRect   getBBox();
+    SVGMatrix getCTM();
+    SVGMatrix getScreenCTM();
+    [RaisesException] SVGMatrix getTransformToElement([Default=Undefined] optional SVGElement element);
 };
 
+SVGGraphicsElement implements SVGTests;
diff --git a/Source/core/svg/SVGImageElement.cpp b/Source/core/svg/SVGImageElement.cpp
index efeb996..5b85037 100644
--- a/Source/core/svg/SVGImageElement.cpp
+++ b/Source/core/svg/SVGImageElement.cpp
@@ -50,12 +50,11 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(preserveAspectRatio)
     REGISTER_LOCAL_ANIMATED_PROPERTY(href)
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGImageElement::SVGImageElement(const QualifiedName& tagName, Document* document)
-    : SVGStyledTransformableElement(tagName, document)
+    : SVGGraphicsElement(tagName, document)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
     , m_width(LengthModeWidth)
@@ -76,7 +75,6 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGTests::addSupportedAttributes(supportedAttributes);
         SVGLangSpace::addSupportedAttributes(supportedAttributes);
         SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         SVGURIReference::addSupportedAttributes(supportedAttributes);
@@ -86,20 +84,20 @@
         supportedAttributes.add(SVGNames::heightAttr);
         supportedAttributes.add(SVGNames::preserveAspectRatioAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 bool SVGImageElement::isPresentationAttribute(const QualifiedName& name) const
 {
     if (name == SVGNames::widthAttr || name == SVGNames::heightAttr)
         return true;
-    return SVGStyledTransformableElement::isPresentationAttribute(name);
+    return SVGGraphicsElement::isPresentationAttribute(name);
 }
 
 void SVGImageElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
 {
     if (!isSupportedAttribute(name))
-        SVGStyledTransformableElement::collectStyleForPresentationAttribute(name, value, style);
+        SVGGraphicsElement::collectStyleForPresentationAttribute(name, value, style);
     else if (name == SVGNames::widthAttr)
         addPropertyToPresentationAttributeStyle(style, CSSPropertyWidth, value);
     else if (name == SVGNames::heightAttr)
@@ -111,7 +109,7 @@
     SVGParsingError parseError = NoError;
 
     if (!isSupportedAttribute(name))
-        SVGStyledTransformableElement::parseAttribute(name, value);
+        SVGGraphicsElement::parseAttribute(name, value);
     else if (name == SVGNames::xAttr)
         setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
     else if (name == SVGNames::yAttr)
@@ -124,8 +122,7 @@
         setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
     else if (name == SVGNames::heightAttr)
         setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
-    else if (SVGTests::parseAttribute(name, value)
-             || SVGLangSpace::parseAttribute(name, value)
+    else if (SVGLangSpace::parseAttribute(name, value)
              || SVGExternalResourcesRequired::parseAttribute(name, value)
              || SVGURIReference::parseAttribute(name, value)) {
     } else
@@ -137,7 +134,7 @@
 void SVGImageElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGStyledTransformableElement::svgAttributeChanged(attrName);
+        SVGGraphicsElement::svgAttributeChanged(attrName);
         return;
     }
 
@@ -151,9 +148,6 @@
     if (isLengthAttribute)
         updateRelativeLengthsInformation();
 
-    if (SVGTests::handleAttributeChange(this, attrName))
-        return;
-
     if (SVGURIReference::isKnownAttribute(attrName)) {
         m_imageLoader.updateFromElementIgnoringPreviousError();
         return;
@@ -187,9 +181,9 @@
         || height().isRelative();
 }
 
-RenderObject* SVGImageElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGImageElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGImage(this);
+    return new (document()->renderArena()) RenderSVGImage(this);
 }
 
 bool SVGImageElement::haveLoadedRequiredResources()
@@ -199,7 +193,7 @@
 
 void SVGImageElement::attach(const AttachContext& context)
 {
-    SVGStyledTransformableElement::attach(context);
+    SVGGraphicsElement::attach(context);
 
     if (RenderSVGImage* imageObj = toRenderSVGImage(renderer())) {
         if (imageObj->imageResource()->hasImage())
@@ -211,7 +205,7 @@
 
 Node::InsertionNotificationRequest SVGImageElement::insertedInto(ContainerNode* rootParent)
 {
-    SVGStyledTransformableElement::insertedInto(rootParent);
+    SVGGraphicsElement::insertedInto(rootParent);
     if (!rootParent->inDocument())
         return InsertionDone;
     // Update image loader, as soon as we're living in the tree.
@@ -227,7 +221,7 @@
 
 void SVGImageElement::addSubresourceAttributeURLs(ListHashSet<KURL>& urls) const
 {
-    SVGStyledTransformableElement::addSubresourceAttributeURLs(urls);
+    SVGGraphicsElement::addSubresourceAttributeURLs(urls);
 
     addSubresourceURL(urls, document()->completeURL(href()));
 }
@@ -235,7 +229,7 @@
 void SVGImageElement::didMoveToNewDocument(Document* oldDocument)
 {
     m_imageLoader.elementDidMoveToNewDocument();
-    SVGStyledTransformableElement::didMoveToNewDocument(oldDocument);
+    SVGGraphicsElement::didMoveToNewDocument(oldDocument);
 }
 
 }
diff --git a/Source/core/svg/SVGImageElement.h b/Source/core/svg/SVGImageElement.h
index cd0536d..9dd3f42 100644
--- a/Source/core/svg/SVGImageElement.h
+++ b/Source/core/svg/SVGImageElement.h
@@ -25,17 +25,13 @@
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGAnimatedPreserveAspectRatio.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
+#include "core/svg/SVGGraphicsElement.h"
 #include "core/svg/SVGImageLoader.h"
-#include "core/svg/SVGLangSpace.h"
-#include "core/svg/SVGStyledTransformableElement.h"
-#include "core/svg/SVGTests.h"
 #include "core/svg/SVGURIReference.h"
 
 namespace WebCore {
 
-class SVGImageElement FINAL : public SVGStyledTransformableElement,
-                              public SVGTests,
-                              public SVGLangSpace,
+class SVGImageElement FINAL : public SVGGraphicsElement,
                               public SVGExternalResourcesRequired,
                               public SVGURIReference {
 public:
@@ -56,7 +52,7 @@
     virtual void attach(const AttachContext& = AttachContext()) OVERRIDE;
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     virtual const AtomicString& imageSourceURL() const OVERRIDE;
     virtual void addSubresourceAttributeURLs(ListHashSet<KURL>&) const;
@@ -76,11 +72,6 @@
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
-
     SVGImageLoader m_imageLoader;
 };
 
diff --git a/Source/core/svg/SVGImageElement.idl b/Source/core/svg/SVGImageElement.idl
index e063778..da33d4d 100644
--- a/Source/core/svg/SVGImageElement.idl
+++ b/Source/core/svg/SVGImageElement.idl
@@ -23,12 +23,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGImageElement : SVGStyledElement,
-                            SVGURIReference,
-                            SVGTests,
-                            SVGLangSpace,
-                            SVGExternalResourcesRequired,
-                            SVGTransformable {
+interface SVGImageElement : SVGGraphicsElement {
     readonly attribute SVGAnimatedLength x;
     readonly attribute SVGAnimatedLength y;
     readonly attribute SVGAnimatedLength width;
@@ -36,3 +31,6 @@
     readonly attribute SVGAnimatedPreserveAspectRatio preserveAspectRatio;
 };
 
+SVGImageElement implements SVGExternalResourcesRequired;
+SVGImageElement implements SVGURIReference;
+
diff --git a/Source/core/svg/SVGLangSpace.idl b/Source/core/svg/SVGLangSpace.idl
deleted file mode 100644
index 1bc44be..0000000
--- a/Source/core/svg/SVGLangSpace.idl
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
- * Copyright (C) 2006 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
- */
-
-[
-    DoNotGenerateToV8
-] interface SVGLangSpace {
-             attribute DOMString xmllang;
-             attribute DOMString xmlspace;
-};
-
diff --git a/Source/core/svg/SVGLength.cpp b/Source/core/svg/SVGLength.cpp
index e708b76..c2f879c 100644
--- a/Source/core/svg/SVGLength.cpp
+++ b/Source/core/svg/SVGLength.cpp
@@ -28,13 +28,11 @@
 #include "core/dom/ExceptionCode.h"
 #include "core/dom/ExceptionCodePlaceholder.h"
 #include "core/svg/SVGParserUtilities.h"
-
-#include <wtf/MathExtras.h>
-#include <wtf/text/WTFString.h>
+#include "wtf/MathExtras.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
-// Helper functions
 static inline unsigned int storeUnit(SVGLengthMode mode, SVGLengthType type)
 {
     return (mode << 4) | type;
@@ -83,7 +81,8 @@
     return String();
 }
 
-inline SVGLengthType stringToLengthType(const UChar*& ptr, const UChar* end)
+template<typename CharType>
+static SVGLengthType stringToLengthType(const CharType*& ptr, const CharType* end)
 {
     if (ptr == end)
         return LengthTypeNumber;
@@ -217,23 +216,36 @@
     return m_valueInSpecifiedUnits;
 }
 
+template<typename CharType>
+static bool parseValueInternal(const String& string, float& convertedNumber, SVGLengthType& type)
+{
+    const CharType* ptr = string.getCharacters<CharType>();
+    const CharType* end = ptr + string.length();
+
+    if (!parseNumber(ptr, end, convertedNumber, false))
+        return false;
+
+    type = stringToLengthType(ptr, end);
+    ASSERT(ptr <= end);
+    if (type == LengthTypeUnknown)
+        return false;
+
+    return true;
+}
+
 void SVGLength::setValueAsString(const String& string, ExceptionCode& ec)
 {
     if (string.isEmpty())
         return;
 
     float convertedNumber = 0;
-    const UChar* ptr = string.characters();
-    const UChar* end = ptr + string.length();
+    SVGLengthType type = LengthTypeUnknown;
 
-    if (!parseNumber(ptr, end, convertedNumber, false)) {
-        ec = SYNTAX_ERR;
-        return;
-    }
+    bool success = string.is8Bit() ?
+        parseValueInternal<LChar>(string, convertedNumber, type) :
+        parseValueInternal<UChar>(string, convertedNumber, type);
 
-    SVGLengthType type = stringToLengthType(ptr, end);
-    ASSERT(ptr <= end);
-    if (type == LengthTypeUnknown) {
+    if (!success) {
         ec = SYNTAX_ERR;
         return;
     }
diff --git a/Source/core/svg/SVGLengthList.cpp b/Source/core/svg/SVGLengthList.cpp
index 0cf8346..87bbfc3 100644
--- a/Source/core/svg/SVGLengthList.cpp
+++ b/Source/core/svg/SVGLengthList.cpp
@@ -27,15 +27,13 @@
 
 namespace WebCore {
 
-void SVGLengthList::parse(const String& value, SVGLengthMode mode)
+template<typename CharType>
+void SVGLengthList::parseInternal(const CharType*& ptr, const CharType* end, SVGLengthMode mode)
 {
-    clear();
     ExceptionCode ec = 0;
 
-    const UChar* ptr = value.characters();
-    const UChar* end = ptr + value.length();
     while (ptr < end) {
-        const UChar* start = ptr;
+        const CharType* start = ptr;
         while (ptr < end && *ptr != ',' && !isSVGSpace(*ptr))
             ptr++;
         if (ptr == start)
@@ -53,6 +51,22 @@
     }
 }
 
+void SVGLengthList::parse(const String& value, SVGLengthMode mode)
+{
+    clear();
+    if (value.isEmpty())
+        return;
+    if (value.is8Bit()) {
+        const LChar* ptr = value.characters8();
+        const LChar* end = ptr + value.length();
+        parseInternal(ptr, end, mode);
+    } else {
+        const UChar* ptr = value.characters16();
+        const UChar* end = ptr + value.length();
+        parseInternal(ptr, end, mode);
+    }
+}
+
 String SVGLengthList::valueAsString() const
 {
     StringBuilder builder;
diff --git a/Source/core/svg/SVGLengthList.h b/Source/core/svg/SVGLengthList.h
index e60c6ee..1544943 100644
--- a/Source/core/svg/SVGLengthList.h
+++ b/Source/core/svg/SVGLengthList.h
@@ -32,6 +32,10 @@
 
     void parse(const String& value, SVGLengthMode); 
     String valueAsString() const;
+
+private:
+    template<typename CharType>
+    void parseInternal(const CharType*& ptr, const CharType* end, SVGLengthMode);
 };
 
 template<>
diff --git a/Source/core/svg/SVGLineElement.cpp b/Source/core/svg/SVGLineElement.cpp
index 2180f9a..6f50d20 100644
--- a/Source/core/svg/SVGLineElement.cpp
+++ b/Source/core/svg/SVGLineElement.cpp
@@ -42,12 +42,11 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(x2)
     REGISTER_LOCAL_ANIMATED_PROPERTY(y2)
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGLineElement::SVGLineElement(const QualifiedName& tagName, Document* document)
-    : SVGStyledTransformableElement(tagName, document)
+    : SVGGraphicsElement(tagName, document)
     , m_x1(LengthModeWidth)
     , m_y1(LengthModeHeight)
     , m_x2(LengthModeWidth)
@@ -67,7 +66,6 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGTests::addSupportedAttributes(supportedAttributes);
         SVGLangSpace::addSupportedAttributes(supportedAttributes);
         SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::x1Attr);
@@ -75,7 +73,7 @@
         supportedAttributes.add(SVGNames::y1Attr);
         supportedAttributes.add(SVGNames::y2Attr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGLineElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -83,7 +81,7 @@
     SVGParsingError parseError = NoError;
 
     if (!isSupportedAttribute(name))
-        SVGStyledTransformableElement::parseAttribute(name, value);
+        SVGGraphicsElement::parseAttribute(name, value);
     else if (name == SVGNames::x1Attr)
         setX1BaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
     else if (name == SVGNames::y1Attr)
@@ -92,8 +90,7 @@
         setX2BaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
     else if (name == SVGNames::y2Attr)
         setY2BaseValue(SVGLength::construct(LengthModeHeight, value, parseError));
-    else if (SVGTests::parseAttribute(name, value)
-             || SVGLangSpace::parseAttribute(name, value)
+    else if (SVGLangSpace::parseAttribute(name, value)
              || SVGExternalResourcesRequired::parseAttribute(name, value)) {
     } else
         ASSERT_NOT_REACHED();
@@ -104,7 +101,7 @@
 void SVGLineElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGStyledTransformableElement::svgAttributeChanged(attrName);
+        SVGGraphicsElement::svgAttributeChanged(attrName);
         return;
     }
 
@@ -118,9 +115,6 @@
     if (isLengthAttribute)
         updateRelativeLengthsInformation();
 
-    if (SVGTests::handleAttributeChange(this, attrName))
-        return;
-
     RenderSVGShape* renderer = toRenderSVGShape(this->renderer());
     if (!renderer)
         return;
diff --git a/Source/core/svg/SVGLineElement.h b/Source/core/svg/SVGLineElement.h
index 1027644..110da59 100644
--- a/Source/core/svg/SVGLineElement.h
+++ b/Source/core/svg/SVGLineElement.h
@@ -24,15 +24,11 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGLangSpace.h"
-#include "core/svg/SVGStyledTransformableElement.h"
-#include "core/svg/SVGTests.h"
+#include "core/svg/SVGGraphicsElement.h"
 
 namespace WebCore {
 
-class SVGLineElement FINAL : public SVGStyledTransformableElement,
-                             public SVGTests,
-                             public SVGLangSpace,
+class SVGLineElement FINAL : public SVGGraphicsElement,
                              public SVGExternalResourcesRequired {
 public:
     static PassRefPtr<SVGLineElement> create(const QualifiedName&, Document*);
@@ -58,11 +54,6 @@
         DECLARE_ANIMATED_LENGTH(Y2, y2)
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
-
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGLineElement.idl b/Source/core/svg/SVGLineElement.idl
index 2ecbc2d..14ae43e 100644
--- a/Source/core/svg/SVGLineElement.idl
+++ b/Source/core/svg/SVGLineElement.idl
@@ -23,14 +23,12 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGLineElement : SVGStyledElement,
-                           SVGTests,
-                           SVGLangSpace,
-                           SVGExternalResourcesRequired,
-                           SVGTransformable {
+interface SVGLineElement : SVGGraphicsElement {
     readonly attribute SVGAnimatedLength x1;
     readonly attribute SVGAnimatedLength y1;
     readonly attribute SVGAnimatedLength x2;
     readonly attribute SVGAnimatedLength y2;
 };
 
+SVGLineElement implements SVGExternalResourcesRequired;
+
diff --git a/Source/core/svg/SVGLinearGradientElement.cpp b/Source/core/svg/SVGLinearGradientElement.cpp
index 8eb6dec..2362070 100644
--- a/Source/core/svg/SVGLinearGradientElement.cpp
+++ b/Source/core/svg/SVGLinearGradientElement.cpp
@@ -75,7 +75,7 @@
         supportedAttributes.add(SVGNames::y1Attr);
         supportedAttributes.add(SVGNames::y2Attr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGLinearGradientElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -113,9 +113,9 @@
         object->setNeedsLayout(true);
 }
 
-RenderObject* SVGLinearGradientElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGLinearGradientElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGResourceLinearGradient(this);
+    return new (document()->renderArena()) RenderSVGResourceLinearGradient(this);
 }
 
 bool SVGLinearGradientElement::collectGradientAttributes(LinearGradientAttributes& attributes)
diff --git a/Source/core/svg/SVGLinearGradientElement.h b/Source/core/svg/SVGLinearGradientElement.h
index e61e464..21bd87c 100644
--- a/Source/core/svg/SVGLinearGradientElement.h
+++ b/Source/core/svg/SVGLinearGradientElement.h
@@ -41,7 +41,7 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void svgAttributeChanged(const QualifiedName&);
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     virtual bool selfHasRelativeLengths() const;
 
diff --git a/Source/core/svg/SVGLocatable.cpp b/Source/core/svg/SVGLocatable.cpp
index e1f4d45..20cd2dd 100644
--- a/Source/core/svg/SVGLocatable.cpp
+++ b/Source/core/svg/SVGLocatable.cpp
@@ -25,9 +25,9 @@
 #include "core/svg/SVGLocatable.h"
 
 #include "SVGNames.h"
+#include "core/dom/ExceptionCode.h"
 #include "core/rendering/RenderObject.h"
-#include "core/svg/SVGException.h"
-#include "core/svg/SVGStyledLocatableElement.h"
+#include "core/svg/SVGGraphicsElement.h"
 
 namespace WebCore {
 
@@ -102,10 +102,10 @@
 {
     AffineTransform ctm = getCTM(styleUpdateStrategy);
 
-    if (target && target->isStyledLocatable()) {
-        AffineTransform targetCTM = toSVGStyledLocatableElement(target)->getCTM(styleUpdateStrategy);
+    if (target && target->isSVGGraphicsElement()) {
+        AffineTransform targetCTM = toSVGGraphicsElement(target)->getCTM(styleUpdateStrategy);
         if (!targetCTM.isInvertible()) {
-            ec = SVGException::SVG_MATRIX_NOT_INVERTABLE;
+            ec = INVALID_STATE_ERR;
             return ctm;
         }
         ctm = targetCTM.inverse() * ctm;
diff --git a/Source/core/svg/SVGLocatable.idl b/Source/core/svg/SVGLocatable.idl
deleted file mode 100644
index d5a5363..0000000
--- a/Source/core/svg/SVGLocatable.idl
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
- * Copyright (C) 2006 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
- */
-
-[
-    DoNotGenerateToV8
-] interface SVGLocatable {
-    readonly attribute SVGElement nearestViewportElement;
-    readonly attribute SVGElement farthestViewportElement;
-
-    SVGRect   getBBox();
-    SVGMatrix getCTM();
-    SVGMatrix getScreenCTM();
-    [RaisesException] SVGMatrix getTransformToElement([Default=Undefined] optional SVGElement element);
-};
-
diff --git a/Source/core/svg/SVGMPathElement.cpp b/Source/core/svg/SVGMPathElement.cpp
index f1e6533..f28e4be 100644
--- a/Source/core/svg/SVGMPathElement.cpp
+++ b/Source/core/svg/SVGMPathElement.cpp
@@ -110,7 +110,7 @@
         SVGURIReference::addSupportedAttributes(supportedAttributes);
         SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGMPathElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGMPathElement.idl b/Source/core/svg/SVGMPathElement.idl
index c3a72ac..3fb56ec 100644
--- a/Source/core/svg/SVGMPathElement.idl
+++ b/Source/core/svg/SVGMPathElement.idl
@@ -23,8 +23,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGMPathElement : SVGElement,
-                            SVGURIReference,
-                            SVGExternalResourcesRequired {
+interface SVGMPathElement : SVGElement {
 };
 
+SVGMPathElement implements SVGExternalResourcesRequired;
+SVGMPathElement implements SVGURIReference;
+
diff --git a/Source/core/svg/SVGMarkerElement.cpp b/Source/core/svg/SVGMarkerElement.cpp
index f6eeedc..a101cbe 100644
--- a/Source/core/svg/SVGMarkerElement.cpp
+++ b/Source/core/svg/SVGMarkerElement.cpp
@@ -121,7 +121,7 @@
         supportedAttributes.add(SVGNames::markerHeightAttr);
         supportedAttributes.add(SVGNames::orientAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGMarkerElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -212,9 +212,9 @@
     svgAttributeChanged(orientAnglePropertyInfo()->attributeName);
 }
 
-RenderObject* SVGMarkerElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGMarkerElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGResourceMarker(this);
+    return new (document()->renderArena()) RenderSVGResourceMarker(this);
 }
 
 bool SVGMarkerElement::selfHasRelativeLengths() const
diff --git a/Source/core/svg/SVGMarkerElement.h b/Source/core/svg/SVGMarkerElement.h
index 902bad8..07ac433 100644
--- a/Source/core/svg/SVGMarkerElement.h
+++ b/Source/core/svg/SVGMarkerElement.h
@@ -29,7 +29,6 @@
 #include "core/svg/SVGAnimatedRect.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGFitToViewBox.h"
-#include "core/svg/SVGLangSpace.h"
 #include "core/svg/SVGStyledElement.h"
 
 namespace WebCore {
@@ -95,7 +94,6 @@
 };
 
 class SVGMarkerElement FINAL : public SVGStyledElement,
-                               public SVGLangSpace,
                                public SVGExternalResourcesRequired,
                                public SVGFitToViewBox {
 public:
@@ -131,7 +129,7 @@
     virtual void svgAttributeChanged(const QualifiedName&);
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool rendererIsNeeded(const NodeRenderingContext&) { return true; }
 
     virtual bool selfHasRelativeLengths() const;
diff --git a/Source/core/svg/SVGMarkerElement.idl b/Source/core/svg/SVGMarkerElement.idl
index 757abc1..f5da729 100644
--- a/Source/core/svg/SVGMarkerElement.idl
+++ b/Source/core/svg/SVGMarkerElement.idl
@@ -23,10 +23,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGMarkerElement : SVGStyledElement,
-                             SVGLangSpace,
-                             SVGExternalResourcesRequired,
-                             SVGFitToViewBox {
+interface SVGMarkerElement : SVGStyledElement {
     // Marker Unit Types
     const unsigned short SVG_MARKERUNITS_UNKNOWN        = 0;
     const unsigned short SVG_MARKERUNITS_USERSPACEONUSE = 1;
@@ -49,3 +46,6 @@
     void setOrientToAngle([Default=Undefined] optional SVGAngle angle);
 };
 
+SVGMarkerElement implements SVGExternalResourcesRequired;
+SVGMarkerElement implements SVGFitToViewBox;
+
diff --git a/Source/core/svg/SVGMaskElement.cpp b/Source/core/svg/SVGMaskElement.cpp
index c9a17ad..df45587 100644
--- a/Source/core/svg/SVGMaskElement.cpp
+++ b/Source/core/svg/SVGMaskElement.cpp
@@ -88,7 +88,7 @@
         supportedAttributes.add(SVGNames::widthAttr);
         supportedAttributes.add(SVGNames::heightAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGMaskElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -154,9 +154,9 @@
         object->setNeedsLayout(true);
 }
 
-RenderObject* SVGMaskElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGMaskElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGResourceMasker(this);
+    return new (document()->renderArena()) RenderSVGResourceMasker(this);
 }
 
 bool SVGMaskElement::selfHasRelativeLengths() const
diff --git a/Source/core/svg/SVGMaskElement.h b/Source/core/svg/SVGMaskElement.h
index f8ef8a9..ec063e0 100644
--- a/Source/core/svg/SVGMaskElement.h
+++ b/Source/core/svg/SVGMaskElement.h
@@ -24,7 +24,6 @@
 #include "core/svg/SVGAnimatedEnumeration.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGLangSpace.h"
 #include "core/svg/SVGStyledElement.h"
 #include "core/svg/SVGTests.h"
 #include "core/svg/SVGUnitTypes.h"
@@ -33,7 +32,6 @@
 
 class SVGMaskElement FINAL : public SVGStyledElement,
                              public SVGTests,
-                             public SVGLangSpace,
                              public SVGExternalResourcesRequired {
 public:
     static PassRefPtr<SVGMaskElement> create(const QualifiedName&, Document*);
@@ -49,7 +47,7 @@
     virtual void svgAttributeChanged(const QualifiedName&);
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     virtual bool selfHasRelativeLengths() const;
 
diff --git a/Source/core/svg/SVGMaskElement.idl b/Source/core/svg/SVGMaskElement.idl
index 66cad0c..2c10a93 100644
--- a/Source/core/svg/SVGMaskElement.idl
+++ b/Source/core/svg/SVGMaskElement.idl
@@ -23,10 +23,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGMaskElement : SVGStyledElement,
-                           SVGTests,
-                           SVGLangSpace,
-                           SVGExternalResourcesRequired {
+interface SVGMaskElement : SVGStyledElement {
     readonly attribute SVGAnimatedEnumeration maskUnits;
     readonly attribute SVGAnimatedEnumeration maskContentUnits;
 
@@ -36,3 +33,6 @@
     readonly attribute SVGAnimatedLength height;
 };
 
+SVGMaskElement implements SVGExternalResourcesRequired;
+SVGMaskElement implements SVGTests;
+
diff --git a/Source/core/svg/SVGMatrix.h b/Source/core/svg/SVGMatrix.h
index 57deb4c..edbe92d 100644
--- a/Source/core/svg/SVGMatrix.h
+++ b/Source/core/svg/SVGMatrix.h
@@ -20,8 +20,8 @@
 #ifndef SVGMatrix_h
 #define SVGMatrix_h
 
+#include "core/dom/ExceptionCode.h"
 #include "core/platform/graphics/transforms/AffineTransform.h"
-#include "core/svg/SVGException.h"
 
 namespace WebCore {
 
@@ -107,8 +107,12 @@
     SVGMatrix inverse(ExceptionCode& ec) const
     {
         AffineTransform transform = AffineTransform::inverse();
-        if (!isInvertible())
-            ec = SVGException::SVG_MATRIX_NOT_INVERTABLE;
+        if (!isInvertible()) {
+            // FIXME: This used to have a more specific error message:
+            // "An attempt was made to invert a matrix that is not invertible."
+            // When switching to SVG2 style exceptions we lost this information.
+            ec = INVALID_STATE_ERR;
+        }
 
         return transform;
     }
@@ -116,7 +120,7 @@
     SVGMatrix rotateFromVector(double x, double y, ExceptionCode& ec)
     {
         if (!x || !y)
-            ec = SVGException::SVG_INVALID_VALUE_ERR;
+            ec = INVALID_ACCESS_ERR;
 
         AffineTransform copy = *this;
         copy.rotateFromVector(x, y);
diff --git a/Source/core/svg/SVGNumberList.cpp b/Source/core/svg/SVGNumberList.cpp
index 9222de4..2b83b70 100644
--- a/Source/core/svg/SVGNumberList.cpp
+++ b/Source/core/svg/SVGNumberList.cpp
@@ -27,22 +27,34 @@
 
 namespace WebCore {
 
-void SVGNumberList::parse(const String& value)
+template<typename CharType>
+void SVGNumberList::parseInternal(const CharType*& ptr, const CharType* end)
 {
-    clear();
-
-    float number = 0;
-    const UChar* ptr = value.characters();
-    const UChar* end = ptr + value.length();
-
     // The spec strangely doesn't allow leading whitespace.  We might choose to violate that intentionally. (section 4.1)
     while (ptr < end) {
+        float number = 0;
         if (!parseNumber(ptr, end, number))
             return;
         append(number);
     }
 }
 
+void SVGNumberList::parse(const String& value)
+{
+    clear();
+    if (value.isEmpty())
+        return;
+    if (value.is8Bit()) {
+        const LChar* ptr = value.characters8();
+        const LChar* end = ptr + value.length();
+        parseInternal(ptr, end);
+    } else {
+        const UChar* ptr = value.characters16();
+        const UChar* end = ptr + value.length();
+        parseInternal(ptr, end);
+    }
+}
+
 String SVGNumberList::valueAsString() const
 {
     StringBuilder builder;
diff --git a/Source/core/svg/SVGNumberList.h b/Source/core/svg/SVGNumberList.h
index 1efea9e..828131f 100644
--- a/Source/core/svg/SVGNumberList.h
+++ b/Source/core/svg/SVGNumberList.h
@@ -32,6 +32,10 @@
 
     void parse(const String&);
     String valueAsString() const;
+
+private:
+    template<typename CharType>
+    void parseInternal(const CharType*& ptr, const CharType* end);
 };
 
 template<>
diff --git a/Source/core/svg/SVGParserUtilities.cpp b/Source/core/svg/SVGParserUtilities.cpp
index c728ca7..b0bd909 100644
--- a/Source/core/svg/SVGParserUtilities.cpp
+++ b/Source/core/svg/SVGParserUtilities.cpp
@@ -21,19 +21,18 @@
  */
 
 #include "config.h"
-
 #include "core/svg/SVGParserUtilities.h"
 
 #include "core/dom/Document.h"
 #include "core/platform/graphics/FloatRect.h"
 #include "core/svg/SVGPointList.h"
-
+#include "wtf/ASCIICType.h"
 #include <limits>
-#include <wtf/ASCIICType.h>
 
 namespace WebCore {
 
-template <typename FloatType> static inline bool isValidRange(const FloatType& x)
+template <typename FloatType>
+static inline bool isValidRange(const FloatType& x)
 {
     static const FloatType max = std::numeric_limits<FloatType>::max();
     return x >= -max && x <= max;
@@ -42,11 +41,12 @@
 // We use this generic parseNumber function to allow the Path parsing code to work 
 // at a higher precision internally, without any unnecessary runtime cost or code
 // complexity.
-template <typename CharacterType, typename FloatType> static bool genericParseNumber(const CharacterType*& ptr, const CharacterType* end, FloatType& number, bool skip)
+template <typename CharType, typename FloatType>
+static bool genericParseNumber(const CharType*& ptr, const CharType* end, FloatType& number, bool skip)
 {
     FloatType integer, decimal, frac, exponent;
     int sign, expsign;
-    const CharacterType* start = ptr;
+    const CharType* start = ptr;
 
     exponent = 0;
     integer = 0;
@@ -68,12 +68,12 @@
         return false;
 
     // read the integer part, build right-to-left
-    const CharacterType* ptrStartIntPart = ptr;
+    const CharType* ptrStartIntPart = ptr;
     while (ptr < end && *ptr >= '0' && *ptr <= '9')
         ++ptr; // Advance to first non-digit.
 
     if (ptr != ptrStartIntPart) {
-        const CharacterType* ptrScanIntPart = ptr - 1;
+        const CharType* ptrScanIntPart = ptr - 1;
         FloatType multiplier = 1;
         while (ptrScanIntPart >= ptrStartIntPart) {
             integer += multiplier * static_cast<FloatType>(*(ptrScanIntPart--) - '0');
@@ -141,11 +141,11 @@
     return true;
 }
 
-template <typename CharacterType>
-bool parseSVGNumber(CharacterType* begin, size_t length, double& number)
+template <typename CharType>
+bool parseSVGNumber(CharType* begin, size_t length, double& number)
 {
-    const CharacterType* ptr = begin;
-    const CharacterType* end = ptr + length;
+    const CharType* ptr = begin;
+    const CharType* end = ptr + length;
     return genericParseNumber(ptr, end, number, false);
 }
 
@@ -165,19 +165,26 @@
 
 bool parseNumberFromString(const String& string, float& number, bool skip)
 {
-    const UChar* ptr = string.characters();
+    if (string.isEmpty())
+        return false;
+    if (string.is8Bit()) {
+        const LChar* ptr = string.characters8();
+        const LChar* end = ptr + string.length();
+        return genericParseNumber(ptr, end, number, skip) && ptr == end;
+    }
+    const UChar* ptr = string.characters16();
     const UChar* end = ptr + string.length();
     return genericParseNumber(ptr, end, number, skip) && ptr == end;
 }
 
 // only used to parse largeArcFlag and sweepFlag which must be a "0" or "1"
 // and might not have any whitespace/comma after it
-template <typename CharacterType>
-bool genericParseArcFlag(const CharacterType*& ptr, const CharacterType* end, bool& flag)
+template <typename CharType>
+bool genericParseArcFlag(const CharType*& ptr, const CharType* end, bool& flag)
 {
     if (ptr >= end)
         return false;
-    const CharacterType flagChar = *ptr++;
+    const CharType flagChar = *ptr++;
     if (flagChar == '0')
         flag = false;
     else if (flagChar == '1')
@@ -200,30 +207,39 @@
     return genericParseArcFlag(ptr, end, flag);
 }
 
-bool parseNumberOptionalNumber(const String& s, float& x, float& y)
+template<typename CharType>
+static bool genericParseNumberOptionalNumber(const CharType*& ptr, const CharType* end, float& x, float& y)
 {
-    if (s.isEmpty())
-        return false;
-    const UChar* cur = s.characters();
-    const UChar* end = cur + s.length();
-
-    if (!parseNumber(cur, end, x))
+    if (!parseNumber(ptr, end, x))
         return false;
 
-    if (cur == end)
+    if (ptr == end)
         y = x;
-    else if (!parseNumber(cur, end, y, false))
+    else if (!parseNumber(ptr, end, y, false))
         return false;
 
-    return cur == end;
+    return ptr == end;
 }
 
-bool parseRect(const String& string, FloatRect& rect)
+bool parseNumberOptionalNumber(const String& string, float& x, float& y)
 {
-    const UChar* ptr = string.characters();
+    if (string.isEmpty())
+        return false;
+    if (string.is8Bit()) {
+        const LChar* ptr = string.characters8();
+        const LChar* end = ptr + string.length();
+        return genericParseNumberOptionalNumber(ptr, end, x, y);
+    }
+    const UChar* ptr = string.characters16();
     const UChar* end = ptr + string.length();
+    return genericParseNumberOptionalNumber(ptr, end, x, y);
+}
+
+template<typename CharType>
+static bool genericParseRect(const CharType*& ptr, const CharType* end, FloatRect& rect)
+{
     skipOptionalSVGSpaces(ptr, end);
-    
+
     float x = 0;
     float y = 0;
     float width = 0;
@@ -233,51 +249,72 @@
     return valid;
 }
 
+bool parseRect(const String& string, FloatRect& rect)
+{
+    if (string.isEmpty())
+        return false;
+    if (string.is8Bit()) {
+        const LChar* ptr = string.characters8();
+        const LChar* end = ptr + string.length();
+        return genericParseRect(ptr, end, rect);
+    }
+    const UChar* ptr = string.characters16();
+    const UChar* end = ptr + string.length();
+    return genericParseRect(ptr, end, rect);
+}
+
+template<typename CharType>
+static bool genericParsePointsList(SVGPointList& pointsList, const CharType*& ptr, const CharType* end)
+{
+    skipOptionalSVGSpaces(ptr, end);
+
+    bool delimParsed = false;
+    while (ptr < end) {
+        delimParsed = false;
+        float xPos = 0.0f;
+        if (!parseNumber(ptr, end, xPos))
+           return false;
+
+        float yPos = 0.0f;
+        if (!parseNumber(ptr, end, yPos, false))
+            return false;
+
+        skipOptionalSVGSpaces(ptr, end);
+
+        if (ptr < end && *ptr == ',') {
+            delimParsed = true;
+            ptr++;
+        }
+        skipOptionalSVGSpaces(ptr, end);
+
+        pointsList.append(FloatPoint(xPos, yPos));
+    }
+    return ptr == end && !delimParsed;
+}
+
+// FIXME: Why is the out parameter first?
 bool pointsListFromSVGData(SVGPointList& pointsList, const String& points)
 {
     if (points.isEmpty())
         return true;
-    const UChar* cur = points.characters();
-    const UChar* end = cur + points.length();
-
-    skipOptionalSVGSpaces(cur, end);
-
-    bool delimParsed = false;
-    while (cur < end) {
-        delimParsed = false;
-        float xPos = 0.0f;
-        if (!parseNumber(cur, end, xPos))
-           return false;
-
-        float yPos = 0.0f;
-        if (!parseNumber(cur, end, yPos, false))
-            return false;
-
-        skipOptionalSVGSpaces(cur, end);
-
-        if (cur < end && *cur == ',') {
-            delimParsed = true;
-            cur++;
-        }
-        skipOptionalSVGSpaces(cur, end);
-
-        pointsList.append(FloatPoint(xPos, yPos));
+    if (points.is8Bit()) {
+        const LChar* ptr = points.characters8();
+        const LChar* end = ptr + points.length();
+        return genericParsePointsList(pointsList, ptr, end);
     }
-    return cur == end && !delimParsed;
+    const UChar* ptr = points.characters16();
+    const UChar* end = ptr + points.length();
+    return genericParsePointsList(pointsList, ptr, end);
 }
 
-bool parseGlyphName(const String& input, HashSet<String>& values)
+template<typename CharType>
+static bool parseGlyphName(const CharType*& ptr, const CharType* end, HashSet<String>& values)
 {
-    // FIXME: Parsing error detection is missing.
-    values.clear();
-
-    const UChar* ptr = input.characters();
-    const UChar* end = ptr + input.length();
     skipOptionalSVGSpaces(ptr, end);
 
     while (ptr < end) {
         // Leading and trailing white space, and white space before and after separators, will be ignored.
-        const UChar* inputStart = ptr;
+        const CharType* inputStart = ptr;
         while (ptr < end && *ptr != ',')
             ++ptr;
 
@@ -285,7 +322,7 @@
             break;
 
         // walk backwards from the ; to ignore any whitespace
-        const UChar* inputEnd = ptr - 1;
+        const CharType* inputEnd = ptr - 1;
         while (inputStart < inputEnd && isSVGSpace(*inputEnd))
             --inputEnd;
 
@@ -296,7 +333,24 @@
     return true;
 }
 
-static bool parseUnicodeRange(const UChar* characters, unsigned length, UnicodeRange& range)
+bool parseGlyphName(const String& input, HashSet<String>& values)
+{
+    // FIXME: Parsing error detection is missing.
+    values.clear();
+    if (input.isEmpty())
+        return true;
+    if (input.is8Bit()) {
+        const LChar* ptr = input.characters8();
+        const LChar* end = ptr + input.length();
+        return parseGlyphName(ptr, end, values);
+    }
+    const UChar* ptr = input.characters16();
+    const UChar* end = ptr + input.length();
+    return parseGlyphName(ptr, end, values);
+}
+
+template<typename CharType>
+static bool parseUnicodeRange(const CharType* characters, unsigned length, UnicodeRange& range)
 {
     if (length < 2 || characters[0] != 'U' || characters[1] != '+')
         return false;
@@ -305,8 +359,8 @@
     unsigned startRange = 0;
     unsigned startLength = 0;
 
-    const UChar* ptr = characters + 2;
-    const UChar* end = characters + length;
+    const CharType* ptr = characters + 2;
+    const CharType* end = characters + length;
     while (ptr < end) {
         if (!isASCIIHexDigit(*ptr))
             break;
@@ -365,14 +419,11 @@
     return true;
 }
 
-bool parseKerningUnicodeString(const String& input, UnicodeRanges& rangeList, HashSet<String>& stringList)
+template<typename CharType>
+static bool genericParseKerningUnicodeString(const CharType*& ptr, const CharType* end, UnicodeRanges& rangeList, HashSet<String>& stringList)
 {
-    // FIXME: Parsing error detection is missing.
-    const UChar* ptr = input.characters();
-    const UChar* end = ptr + input.length();
-
     while (ptr < end) {
-        const UChar* inputStart = ptr;
+        const CharType* inputStart = ptr;
         while (ptr < end && *ptr != ',')
             ++ptr;
 
@@ -391,17 +442,31 @@
     return true;
 }
 
-Vector<String> parseDelimitedString(const String& input, const char seperator)
+bool parseKerningUnicodeString(const String& input, UnicodeRanges& rangeList, HashSet<String>& stringList)
+{
+    // FIXME: Parsing error detection is missing.
+    if (input.isEmpty())
+        return true;
+    if (input.is8Bit()) {
+        const LChar* ptr = input.characters8();
+        const LChar* end = ptr + input.length();
+        return genericParseKerningUnicodeString(ptr, end, rangeList, stringList);
+    }
+    const UChar* ptr = input.characters16();
+    const UChar* end = ptr + input.length();
+    return genericParseKerningUnicodeString(ptr, end, rangeList, stringList);
+}
+
+template<typename CharType>
+static Vector<String> genericParseDelimitedString(const CharType*& ptr, const CharType* end, const char seperator)
 {
     Vector<String> values;
 
-    const UChar* ptr = input.characters();
-    const UChar* end = ptr + input.length();
     skipOptionalSVGSpaces(ptr, end);
 
     while (ptr < end) {
         // Leading and trailing white space, and white space before and after semicolon separators, will be ignored.
-        const UChar* inputStart = ptr;
+        const CharType* inputStart = ptr;
         while (ptr < end && *ptr != seperator) // careful not to ignore whitespace inside inputs
             ptr++;
 
@@ -409,7 +474,7 @@
             break;
 
         // walk backwards from the ; to ignore any whitespace
-        const UChar* inputEnd = ptr - 1;
+        const CharType* inputEnd = ptr - 1;
         while (inputStart < inputEnd && isSVGSpace(*inputEnd))
             inputEnd--;
 
@@ -420,8 +485,22 @@
     return values;
 }
 
-template <typename CharacterType>
-bool parseFloatPoint(const CharacterType*& current, const CharacterType* end, FloatPoint& point)
+Vector<String> parseDelimitedString(const String& input, const char seperator)
+{
+    if (input.isEmpty())
+        return Vector<String>();
+    if (input.is8Bit()) {
+        const LChar* ptr = input.characters8();
+        const LChar* end = ptr + input.length();
+        return genericParseDelimitedString(ptr, end, seperator);
+    }
+    const UChar* ptr = input.characters16();
+    const UChar* end = ptr + input.length();
+    return genericParseDelimitedString(ptr, end, seperator);
+}
+
+template <typename CharType>
+bool parseFloatPoint(const CharType*& current, const CharType* end, FloatPoint& point)
 {
     float x;
     float y;
@@ -435,8 +514,8 @@
 template bool parseFloatPoint(const LChar*& current, const LChar* end, FloatPoint& point1);
 template bool parseFloatPoint(const UChar*& current, const UChar* end, FloatPoint& point1);
 
-template <typename CharacterType>
-inline bool parseFloatPoint2(const CharacterType*& current, const CharacterType* end, FloatPoint& point1, FloatPoint& point2)
+template <typename CharType>
+inline bool parseFloatPoint2(const CharType*& current, const CharType* end, FloatPoint& point1, FloatPoint& point2)
 {
     float x1;
     float y1;
@@ -455,8 +534,8 @@
 template bool parseFloatPoint2(const LChar*& current, const LChar* end, FloatPoint& point1, FloatPoint& point2);
 template bool parseFloatPoint2(const UChar*& current, const UChar* end, FloatPoint& point1, FloatPoint& point2);
 
-template <typename CharacterType>
-bool parseFloatPoint3(const CharacterType*& current, const CharacterType* end, FloatPoint& point1, FloatPoint& point2, FloatPoint& point3)
+template <typename CharType>
+bool parseFloatPoint3(const CharType*& current, const CharType* end, FloatPoint& point1, FloatPoint& point2, FloatPoint& point3)
 {
     float x1;
     float y1;
diff --git a/Source/core/svg/SVGParserUtilities.h b/Source/core/svg/SVGParserUtilities.h
index fcf0bd1..e67c9e1 100644
--- a/Source/core/svg/SVGParserUtilities.h
+++ b/Source/core/svg/SVGParserUtilities.h
@@ -34,8 +34,8 @@
 class FloatRect;
 class SVGPointList;
 
-template <typename CharacterType>
-bool parseSVGNumber(CharacterType* ptr, size_t length, double& number);
+template <typename CharType>
+bool parseSVGNumber(CharType* ptr, size_t length, double& number);
 bool parseNumber(const LChar*& ptr, const LChar* end, float& number, bool skip = true);
 bool parseNumber(const UChar*& ptr, const UChar* end, float& number, bool skip = true);
 bool parseNumberFromString(const String&, float& number, bool skip = true);
@@ -44,31 +44,31 @@
 bool parseArcFlag(const UChar*& ptr, const UChar* end, bool& flag);
 bool parseRect(const String&, FloatRect&);
 
-template <typename CharacterType>
-bool parseFloatPoint(const CharacterType*& current, const CharacterType* end, FloatPoint&);
-template <typename CharacterType>
-bool parseFloatPoint2(const CharacterType*& current, const CharacterType* end, FloatPoint&, FloatPoint&);
-template <typename CharacterType>
-bool parseFloatPoint3(const CharacterType*& current, const CharacterType* end, FloatPoint&, FloatPoint&, FloatPoint&);
+template <typename CharType>
+bool parseFloatPoint(const CharType*& current, const CharType* end, FloatPoint&);
+template <typename CharType>
+bool parseFloatPoint2(const CharType*& current, const CharType* end, FloatPoint&, FloatPoint&);
+template <typename CharType>
+bool parseFloatPoint3(const CharType*& current, const CharType* end, FloatPoint&, FloatPoint&, FloatPoint&);
 
 // SVG allows several different whitespace characters:
 // http://www.w3.org/TR/SVG/paths.html#PathDataBNF
-template <typename CharacterType>
-inline bool isSVGSpace(CharacterType c)
+template <typename CharType>
+inline bool isSVGSpace(CharType c)
 {
     return c == ' ' || c == '\t' || c == '\n' || c == '\r';
 }
 
-template <typename CharacterType>
-inline bool skipOptionalSVGSpaces(const CharacterType*& ptr, const CharacterType* end)
+template <typename CharType>
+inline bool skipOptionalSVGSpaces(const CharType*& ptr, const CharType* end)
 {
     while (ptr < end && isSVGSpace(*ptr))
         ptr++;
     return ptr < end;
 }
 
-template <typename CharacterType>
-inline bool skipOptionalSVGSpacesOrDelimiter(const CharacterType*& ptr, const CharacterType* end, char delimiter = ',')
+template <typename CharType>
+inline bool skipOptionalSVGSpacesOrDelimiter(const CharType*& ptr, const CharType* end, char delimiter = ',')
 {
     if (ptr < end && !isSVGSpace(*ptr) && *ptr != delimiter)
         return false;
diff --git a/Source/core/svg/SVGPathElement.cpp b/Source/core/svg/SVGPathElement.cpp
index 484044f..639b998 100644
--- a/Source/core/svg/SVGPathElement.cpp
+++ b/Source/core/svg/SVGPathElement.cpp
@@ -66,12 +66,11 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(d)
     REGISTER_LOCAL_ANIMATED_PROPERTY(pathLength)
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGPathElement::SVGPathElement(const QualifiedName& tagName, Document* document)
-    : SVGStyledTransformableElement(tagName, document)
+    : SVGGraphicsElement(tagName, document)
     , m_pathByteStream(SVGPathByteStream::create())
     , m_pathSegList(PathSegUnalteredRole)
     , m_isAnimValObserved(false)
@@ -206,19 +205,18 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGTests::addSupportedAttributes(supportedAttributes);
         SVGLangSpace::addSupportedAttributes(supportedAttributes);
         SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::dAttr);
         supportedAttributes.add(SVGNames::pathLengthAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGPathElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
     if (!isSupportedAttribute(name)) {
-        SVGStyledTransformableElement::parseAttribute(name, value);
+        SVGGraphicsElement::parseAttribute(name, value);
         return;
     }
 
@@ -235,8 +233,6 @@
         return;
     }
 
-    if (SVGTests::parseAttribute(name, value))
-        return;
     if (SVGLangSpace::parseAttribute(name, value))
         return;
     if (SVGExternalResourcesRequired::parseAttribute(name, value))
@@ -248,14 +244,11 @@
 void SVGPathElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGStyledTransformableElement::svgAttributeChanged(attrName);
+        SVGGraphicsElement::svgAttributeChanged(attrName);
         return;
     }
 
     SVGElementInstance::InvalidationGuard invalidationGuard(this);
-    
-    if (SVGTests::handleAttributeChange(this, attrName))
-        return;
 
     RenderSVGPath* renderer = toRenderSVGPath(this->renderer());
 
@@ -292,14 +285,14 @@
 
 Node::InsertionNotificationRequest SVGPathElement::insertedInto(ContainerNode* rootParent)
 {
-    SVGStyledTransformableElement::insertedInto(rootParent);
+    SVGGraphicsElement::insertedInto(rootParent);
     invalidateMPathDependencies();
     return InsertionDone;
 }
 
 void SVGPathElement::removedFrom(ContainerNode* rootParent)
 {
-    SVGStyledTransformableElement::removedFrom(rootParent);
+    SVGGraphicsElement::removedFrom(rootParent);
     invalidateMPathDependencies();
 }
 
@@ -401,10 +394,10 @@
     return renderer->path().boundingRect();
 }
 
-RenderObject* SVGPathElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGPathElement::createRenderer(RenderStyle*)
 {
     // By default, any subclass is expected to do path-based drawing
-    return new (arena) RenderSVGPath(this);
+    return new (document()->renderArena()) RenderSVGPath(this);
 }
 
 }
diff --git a/Source/core/svg/SVGPathElement.h b/Source/core/svg/SVGPathElement.h
index cc10120..14e31ae 100644
--- a/Source/core/svg/SVGPathElement.h
+++ b/Source/core/svg/SVGPathElement.h
@@ -25,11 +25,9 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedNumber.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGLangSpace.h"
+#include "core/svg/SVGGraphicsElement.h"
 #include "core/svg/SVGPathByteStream.h"
 #include "core/svg/SVGPathSegList.h"
-#include "core/svg/SVGStyledTransformableElement.h"
-#include "core/svg/SVGTests.h"
 
 namespace WebCore {
 
@@ -54,9 +52,7 @@
 class SVGPathSegCurvetoQuadraticSmoothRel;
 class SVGPathSegListPropertyTearOff;
 
-class SVGPathElement FINAL : public SVGStyledTransformableElement,
-                             public SVGTests,
-                             public SVGLangSpace,
+class SVGPathElement FINAL : public SVGGraphicsElement,
                              public SVGExternalResourcesRequired {
 public:
     static PassRefPtr<SVGPathElement> create(const QualifiedName&, Document*);
@@ -121,12 +117,7 @@
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
-
-    RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     virtual Node::InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
diff --git a/Source/core/svg/SVGPathElement.idl b/Source/core/svg/SVGPathElement.idl
index 8608fc3..1bfca0a 100644
--- a/Source/core/svg/SVGPathElement.idl
+++ b/Source/core/svg/SVGPathElement.idl
@@ -24,11 +24,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGPathElement : SVGStyledElement,
-                           SVGTests,
-                           SVGLangSpace,
-                           SVGExternalResourcesRequired,
-                           SVGTransformable {
+interface SVGPathElement : SVGGraphicsElement {
     readonly attribute SVGAnimatedNumber pathLength;
 
     float getTotalLength();
@@ -110,3 +106,4 @@
     readonly attribute SVGPathSegList animatedNormalizedPathSegList;
 };
 
+SVGPathElement implements SVGExternalResourcesRequired;
diff --git a/Source/core/svg/SVGPatternElement.cpp b/Source/core/svg/SVGPatternElement.cpp
index 4e552cb..bcc40f8 100644
--- a/Source/core/svg/SVGPatternElement.cpp
+++ b/Source/core/svg/SVGPatternElement.cpp
@@ -97,7 +97,7 @@
         supportedAttributes.add(SVGNames::widthAttr);
         supportedAttributes.add(SVGNames::heightAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGPatternElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -171,9 +171,9 @@
         object->setNeedsLayout(true);
 }
 
-RenderObject* SVGPatternElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGPatternElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGResourcePattern(this);
+    return new (document()->renderArena()) RenderSVGResourcePattern(this);
 }
 
 void SVGPatternElement::collectPatternAttributes(PatternAttributes& attributes) const
diff --git a/Source/core/svg/SVGPatternElement.h b/Source/core/svg/SVGPatternElement.h
index 981c88b..b813817 100644
--- a/Source/core/svg/SVGPatternElement.h
+++ b/Source/core/svg/SVGPatternElement.h
@@ -29,7 +29,6 @@
 #include "core/svg/SVGAnimatedTransformList.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGFitToViewBox.h"
-#include "core/svg/SVGLangSpace.h"
 #include "core/svg/SVGStyledElement.h"
 #include "core/svg/SVGTests.h"
 #include "core/svg/SVGURIReference.h"
@@ -42,7 +41,6 @@
 class SVGPatternElement FINAL : public SVGStyledElement,
                                 public SVGURIReference,
                                 public SVGTests,
-                                public SVGLangSpace,
                                 public SVGExternalResourcesRequired,
                                 public SVGFitToViewBox {
 public:
@@ -63,7 +61,7 @@
     virtual void svgAttributeChanged(const QualifiedName&);
     virtual void childrenChanged(bool changedByParser = false, Node* beforeChange = 0, Node* afterChange = 0, int childCountDelta = 0);
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     virtual bool selfHasRelativeLengths() const;
 
diff --git a/Source/core/svg/SVGPatternElement.idl b/Source/core/svg/SVGPatternElement.idl
index d8fe822..da1c7a3 100644
--- a/Source/core/svg/SVGPatternElement.idl
+++ b/Source/core/svg/SVGPatternElement.idl
@@ -23,13 +23,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGPatternElement : SVGStyledElement,
-                              SVGURIReference,
-                              SVGTests,
-                              SVGLangSpace,
-                              SVGExternalResourcesRequired,
-                              SVGFitToViewBox
-                              /* SVGUnitTypes */ {
+interface SVGPatternElement : SVGStyledElement {
     readonly attribute SVGAnimatedEnumeration   patternUnits;
     readonly attribute SVGAnimatedEnumeration   patternContentUnits;
     readonly attribute SVGAnimatedTransformList patternTransform;
@@ -39,3 +33,8 @@
     readonly attribute SVGAnimatedLength        height;
 };
 
+SVGPatternElement implements SVGExternalResourcesRequired;
+SVGPatternElement implements SVGFitToViewBox;
+SVGPatternElement implements SVGTests;
+SVGPatternElement implements SVGURIReference;
+
diff --git a/Source/core/svg/SVGPolyElement.cpp b/Source/core/svg/SVGPolyElement.cpp
index 76c9f17..df81eb9 100644
--- a/Source/core/svg/SVGPolyElement.cpp
+++ b/Source/core/svg/SVGPolyElement.cpp
@@ -52,12 +52,11 @@
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGPolyElement)
     REGISTER_LOCAL_ANIMATED_PROPERTY(points)
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 SVGPolyElement::SVGPolyElement(const QualifiedName& tagName, Document* document)
-    : SVGStyledTransformableElement(tagName, document)
+    : SVGGraphicsElement(tagName, document)
 {
     registerAnimatedPropertiesForSVGPolyElement();    
 }
@@ -66,18 +65,17 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGTests::addSupportedAttributes(supportedAttributes);
         SVGLangSpace::addSupportedAttributes(supportedAttributes);
         SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::pointsAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGPolyElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
 {
     if (!isSupportedAttribute(name)) {
-        SVGStyledTransformableElement::parseAttribute(name, value);
+        SVGGraphicsElement::parseAttribute(name, value);
         return;
     }
 
@@ -93,8 +91,6 @@
         return;
     }
 
-    if (SVGTests::parseAttribute(name, value))
-        return;
     if (SVGLangSpace::parseAttribute(name, value))
         return;
     if (SVGExternalResourcesRequired::parseAttribute(name, value))
@@ -106,14 +102,11 @@
 void SVGPolyElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGStyledTransformableElement::svgAttributeChanged(attrName);
+        SVGGraphicsElement::svgAttributeChanged(attrName);
         return;
     }
 
     SVGElementInstance::InvalidationGuard invalidationGuard(this);
-    
-    if (SVGTests::handleAttributeChange(this, attrName))
-        return;
 
     RenderSVGShape* renderer = toRenderSVGShape(this->renderer());
     if (!renderer)
diff --git a/Source/core/svg/SVGPolyElement.h b/Source/core/svg/SVGPolyElement.h
index 3f4be3c..7a031d3 100644
--- a/Source/core/svg/SVGPolyElement.h
+++ b/Source/core/svg/SVGPolyElement.h
@@ -24,16 +24,12 @@
 #include "SVGNames.h"
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGLangSpace.h"
+#include "core/svg/SVGGraphicsElement.h"
 #include "core/svg/SVGPointList.h"
-#include "core/svg/SVGStyledTransformableElement.h"
-#include "core/svg/SVGTests.h"
 
 namespace WebCore {
 
-class SVGPolyElement : public SVGStyledTransformableElement
-                     , public SVGTests
-                     , public SVGLangSpace
+class SVGPolyElement : public SVGGraphicsElement
                      , public SVGExternalResourcesRequired {
 public:
     SVGListPropertyTearOff<SVGPointList>* points();
@@ -64,11 +60,6 @@
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
 
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
-
 protected:
     mutable SVGSynchronizableAnimatedProperty<SVGPointList> m_points;
 };
diff --git a/Source/core/svg/SVGPolygonElement.idl b/Source/core/svg/SVGPolygonElement.idl
index e63f0050..8158365 100644
--- a/Source/core/svg/SVGPolygonElement.idl
+++ b/Source/core/svg/SVGPolygonElement.idl
@@ -23,12 +23,9 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGPolygonElement : SVGStyledElement,
-                              SVGTests,
-                              SVGLangSpace,
-                              SVGExternalResourcesRequired,
-                              SVGTransformable {
+interface SVGPolygonElement : SVGGraphicsElement {
     readonly attribute SVGPointList points;
     readonly attribute SVGPointList animatedPoints;
 };
 
+SVGPolygonElement implements SVGExternalResourcesRequired;
diff --git a/Source/core/svg/SVGPolylineElement.idl b/Source/core/svg/SVGPolylineElement.idl
index 62f559e..c3e284f 100644
--- a/Source/core/svg/SVGPolylineElement.idl
+++ b/Source/core/svg/SVGPolylineElement.idl
@@ -23,12 +23,10 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGPolylineElement : SVGStyledElement,
-                               SVGTests,
-                               SVGLangSpace,
-                               SVGExternalResourcesRequired,
-                               SVGTransformable {
+interface SVGPolylineElement : SVGGraphicsElement {
     readonly attribute SVGPointList points;
     readonly attribute SVGPointList animatedPoints;
 };
 
+SVGPolylineElement implements SVGExternalResourcesRequired;
+
diff --git a/Source/core/svg/SVGPreserveAspectRatio.cpp b/Source/core/svg/SVGPreserveAspectRatio.cpp
index d848ab2..d51dc04 100644
--- a/Source/core/svg/SVGPreserveAspectRatio.cpp
+++ b/Source/core/svg/SVGPreserveAspectRatio.cpp
@@ -57,101 +57,96 @@
     m_meetOrSlice = static_cast<SVGMeetOrSliceType>(meetOrSlice);
 }
 
-void SVGPreserveAspectRatio::parse(const String& value)
-{
-    const UChar* begin = value.characters();
-    parse(begin, begin + value.length(), true);
-}
-
-bool SVGPreserveAspectRatio::parse(const UChar*& currParam, const UChar* end, bool validate)
+template<typename CharType>
+bool SVGPreserveAspectRatio::parseInternal(const CharType*& ptr, const CharType* end, bool validate)
 {
     // FIXME: Rewrite this parser, without gotos!
-    if (!skipOptionalSVGSpaces(currParam, end))
+    if (!skipOptionalSVGSpaces(ptr, end))
         goto bailOut;
 
-    if (*currParam == 'd') {
-        if (!skipString(currParam, end, "defer"))
+    if (*ptr == 'd') {
+        if (!skipString(ptr, end, "defer"))
             goto bailOut;
 
         // FIXME: We just ignore the "defer" here.
-        if (currParam == end)
+        if (ptr == end)
             return true;
 
-        if (!skipOptionalSVGSpaces(currParam, end))
+        if (!skipOptionalSVGSpaces(ptr, end))
             goto bailOut;
     }
 
-    if (*currParam == 'n') {
-        if (!skipString(currParam, end, "none"))
+    if (*ptr == 'n') {
+        if (!skipString(ptr, end, "none"))
             goto bailOut;
         m_align = SVG_PRESERVEASPECTRATIO_NONE;
-        skipOptionalSVGSpaces(currParam, end);
-    } else if (*currParam == 'x') {
-        if ((end - currParam) < 8)
+        skipOptionalSVGSpaces(ptr, end);
+    } else if (*ptr == 'x') {
+        if ((end - ptr) < 8)
             goto bailOut;
-        if (currParam[1] != 'M' || currParam[4] != 'Y' || currParam[5] != 'M')
+        if (ptr[1] != 'M' || ptr[4] != 'Y' || ptr[5] != 'M')
             goto bailOut;
-        if (currParam[2] == 'i') {
-            if (currParam[3] == 'n') {
-                if (currParam[6] == 'i') {
-                    if (currParam[7] == 'n')
+        if (ptr[2] == 'i') {
+            if (ptr[3] == 'n') {
+                if (ptr[6] == 'i') {
+                    if (ptr[7] == 'n')
                         m_align = SVG_PRESERVEASPECTRATIO_XMINYMIN;
-                    else if (currParam[7] == 'd')
+                    else if (ptr[7] == 'd')
                         m_align = SVG_PRESERVEASPECTRATIO_XMINYMID;
                     else
                         goto bailOut;
-                } else if (currParam[6] == 'a' && currParam[7] == 'x')
+                } else if (ptr[6] == 'a' && ptr[7] == 'x')
                      m_align = SVG_PRESERVEASPECTRATIO_XMINYMAX;
                 else
                      goto bailOut;
-             } else if (currParam[3] == 'd') {
-                if (currParam[6] == 'i') {
-                    if (currParam[7] == 'n')
+            } else if (ptr[3] == 'd') {
+                if (ptr[6] == 'i') {
+                    if (ptr[7] == 'n')
                         m_align = SVG_PRESERVEASPECTRATIO_XMIDYMIN;
-                    else if (currParam[7] == 'd')
+                    else if (ptr[7] == 'd')
                         m_align = SVG_PRESERVEASPECTRATIO_XMIDYMID;
                     else
                         goto bailOut;
-                } else if (currParam[6] == 'a' && currParam[7] == 'x')
+                } else if (ptr[6] == 'a' && ptr[7] == 'x')
                     m_align = SVG_PRESERVEASPECTRATIO_XMIDYMAX;
                 else
                     goto bailOut;
             } else
                 goto bailOut;
-        } else if (currParam[2] == 'a' && currParam[3] == 'x') {
-            if (currParam[6] == 'i') {
-                if (currParam[7] == 'n')
+        } else if (ptr[2] == 'a' && ptr[3] == 'x') {
+            if (ptr[6] == 'i') {
+                if (ptr[7] == 'n')
                     m_align = SVG_PRESERVEASPECTRATIO_XMAXYMIN;
-                else if (currParam[7] == 'd')
+                else if (ptr[7] == 'd')
                     m_align = SVG_PRESERVEASPECTRATIO_XMAXYMID;
                 else
                     goto bailOut;
-            } else if (currParam[6] == 'a' && currParam[7] == 'x')
+            } else if (ptr[6] == 'a' && ptr[7] == 'x')
                 m_align = SVG_PRESERVEASPECTRATIO_XMAXYMAX;
             else
                 goto bailOut;
         } else
             goto bailOut;
-        currParam += 8;
-        skipOptionalSVGSpaces(currParam, end);
+        ptr += 8;
+        skipOptionalSVGSpaces(ptr, end);
     } else
         goto bailOut;
 
-    if (currParam < end) {
-        if (*currParam == 'm') {
-            if (!skipString(currParam, end, "meet"))
+    if (ptr < end) {
+        if (*ptr == 'm') {
+            if (!skipString(ptr, end, "meet"))
                 goto bailOut;
-            skipOptionalSVGSpaces(currParam, end);
-        } else if (*currParam == 's') {
-            if (!skipString(currParam, end, "slice"))
+            skipOptionalSVGSpaces(ptr, end);
+        } else if (*ptr == 's') {
+            if (!skipString(ptr, end, "slice"))
                 goto bailOut;
-            skipOptionalSVGSpaces(currParam, end);
+            skipOptionalSVGSpaces(ptr, end);
             if (m_align != SVG_PRESERVEASPECTRATIO_NONE)
                 m_meetOrSlice = SVG_MEETORSLICE_SLICE;
         }
     }
 
-    if (end != currParam && validate) {
+    if (end != ptr && validate) {
 bailOut:
         m_align = SVG_PRESERVEASPECTRATIO_XMIDYMID;
         m_meetOrSlice = SVG_MEETORSLICE_MEET;
@@ -160,6 +155,32 @@
     return true;
 }
 
+void SVGPreserveAspectRatio::parse(const String& string)
+{
+    if (string.isEmpty()) {
+        const LChar* ptr = 0;
+        parseInternal(ptr, ptr, true);
+    } else if (string.is8Bit()) {
+        const LChar* ptr = string.characters8();
+        const LChar* end = ptr + string.length();
+        parseInternal(ptr, end, true);
+    } else {
+        const UChar* ptr = string.characters16();
+        const UChar* end = ptr + string.length();
+        parseInternal(ptr, end, true);
+    }
+}
+
+bool SVGPreserveAspectRatio::parse(const LChar*& ptr, const LChar* end, bool validate)
+{
+    return parseInternal(ptr, end, validate);
+}
+
+bool SVGPreserveAspectRatio::parse(const UChar*& ptr, const UChar* end, bool validate)
+{
+    return parseInternal(ptr, end, validate);
+}
+
 void SVGPreserveAspectRatio::transformRect(FloatRect& destRect, FloatRect& srcRect)
 {
     if (m_align == SVG_PRESERVEASPECTRATIO_NONE)
diff --git a/Source/core/svg/SVGPreserveAspectRatio.h b/Source/core/svg/SVGPreserveAspectRatio.h
index 0f6cfa1..e8a6cd4 100644
--- a/Source/core/svg/SVGPreserveAspectRatio.h
+++ b/Source/core/svg/SVGPreserveAspectRatio.h
@@ -68,11 +68,15 @@
                            float physWidth, float physHeight) const;
 
     void parse(const String&);
-    bool parse(const UChar*& currParam, const UChar* end, bool validate);
+    bool parse(const LChar*& ptr, const LChar* end, bool validate);
+    bool parse(const UChar*& ptr, const UChar* end, bool validate);
 
     String valueAsString() const;
 
 private:
+    template<typename CharType>
+    bool parseInternal(const CharType*& ptr, const CharType* end, bool validate);
+
     SVGPreserveAspectRatioType m_align;
     SVGMeetOrSliceType m_meetOrSlice;
 };
diff --git a/Source/core/svg/SVGRadialGradientElement.cpp b/Source/core/svg/SVGRadialGradientElement.cpp
index 958f610..9f27105 100644
--- a/Source/core/svg/SVGRadialGradientElement.cpp
+++ b/Source/core/svg/SVGRadialGradientElement.cpp
@@ -82,7 +82,7 @@
         supportedAttributes.add(SVGNames::rAttr);
         supportedAttributes.add(SVGNames::frAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGRadialGradientElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -124,9 +124,9 @@
         object->setNeedsLayout(true);
 }
 
-RenderObject* SVGRadialGradientElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGRadialGradientElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGResourceRadialGradient(this);
+    return new (document()->renderArena()) RenderSVGResourceRadialGradient(this);
 }
 
 bool SVGRadialGradientElement::collectGradientAttributes(RadialGradientAttributes& attributes)
diff --git a/Source/core/svg/SVGRadialGradientElement.h b/Source/core/svg/SVGRadialGradientElement.h
index c545329..f70de31 100644
--- a/Source/core/svg/SVGRadialGradientElement.h
+++ b/Source/core/svg/SVGRadialGradientElement.h
@@ -41,7 +41,7 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void svgAttributeChanged(const QualifiedName&);
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     virtual bool selfHasRelativeLengths() const;
 
diff --git a/Source/core/svg/SVGRectElement.cpp b/Source/core/svg/SVGRectElement.cpp
index a276992..b00d3df 100644
--- a/Source/core/svg/SVGRectElement.cpp
+++ b/Source/core/svg/SVGRectElement.cpp
@@ -47,12 +47,11 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(rx)
     REGISTER_LOCAL_ANIMATED_PROPERTY(ry)
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGRectElement::SVGRectElement(const QualifiedName& tagName, Document* document)
-    : SVGStyledTransformableElement(tagName, document)
+    : SVGGraphicsElement(tagName, document)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
     , m_width(LengthModeWidth)
@@ -74,7 +73,6 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGTests::addSupportedAttributes(supportedAttributes);
         SVGLangSpace::addSupportedAttributes(supportedAttributes);
         SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::xAttr);
@@ -84,7 +82,7 @@
         supportedAttributes.add(SVGNames::rxAttr);
         supportedAttributes.add(SVGNames::ryAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGRectElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -92,7 +90,7 @@
     SVGParsingError parseError = NoError;
 
     if (!isSupportedAttribute(name))
-        SVGStyledTransformableElement::parseAttribute(name, value);
+        SVGGraphicsElement::parseAttribute(name, value);
     else if (name == SVGNames::xAttr)
         setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
     else if (name == SVGNames::yAttr)
@@ -105,8 +103,7 @@
         setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
     else if (name == SVGNames::heightAttr)
         setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
-    else if (SVGTests::parseAttribute(name, value)
-             || SVGLangSpace::parseAttribute(name, value)
+    else if (SVGLangSpace::parseAttribute(name, value)
              || SVGExternalResourcesRequired::parseAttribute(name, value)) {
     } else
         ASSERT_NOT_REACHED();
@@ -117,7 +114,7 @@
 void SVGRectElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGStyledTransformableElement::svgAttributeChanged(attrName);
+        SVGGraphicsElement::svgAttributeChanged(attrName);
         return;
     }
 
@@ -133,9 +130,6 @@
     if (isLengthAttribute)
         updateRelativeLengthsInformation();
 
-    if (SVGTests::handleAttributeChange(this, attrName))
-        return;
-
     RenderSVGShape* renderer = toRenderSVGShape(this->renderer());
     if (!renderer)
         return;
@@ -164,9 +158,9 @@
         || ry().isRelative();
 }
 
-RenderObject* SVGRectElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGRectElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGRect(this);
+    return new (document()->renderArena()) RenderSVGRect(this);
 }
 
 }
diff --git a/Source/core/svg/SVGRectElement.h b/Source/core/svg/SVGRectElement.h
index 3ce078e..cd5b85c 100644
--- a/Source/core/svg/SVGRectElement.h
+++ b/Source/core/svg/SVGRectElement.h
@@ -24,15 +24,11 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGLangSpace.h"
-#include "core/svg/SVGStyledTransformableElement.h"
-#include "core/svg/SVGTests.h"
+#include "core/svg/SVGGraphicsElement.h"
 
 namespace WebCore {
 
-class SVGRectElement FINAL : public SVGStyledTransformableElement,
-                             public SVGTests,
-                             public SVGLangSpace,
+class SVGRectElement FINAL : public SVGGraphicsElement,
                              public SVGExternalResourcesRequired {
 public:
     static PassRefPtr<SVGRectElement> create(const QualifiedName&, Document*);
@@ -49,7 +45,7 @@
 
     virtual bool selfHasRelativeLengths() const;
 
-    RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*) OVERRIDE;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGRectElement)
         DECLARE_ANIMATED_LENGTH(X, x)
@@ -60,11 +56,6 @@
         DECLARE_ANIMATED_LENGTH(Ry, ry)
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
-
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGRectElement.idl b/Source/core/svg/SVGRectElement.idl
index 55b6f3c..4de40f2 100644
--- a/Source/core/svg/SVGRectElement.idl
+++ b/Source/core/svg/SVGRectElement.idl
@@ -24,11 +24,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGRectElement : SVGStyledElement,
-                           SVGTests,
-                           SVGLangSpace,
-                           SVGExternalResourcesRequired,
-                           SVGTransformable {
+interface SVGRectElement : SVGGraphicsElement {
     readonly attribute SVGAnimatedLength x;
     readonly attribute SVGAnimatedLength y;
     readonly attribute SVGAnimatedLength width;
@@ -37,3 +33,5 @@
     readonly attribute SVGAnimatedLength ry;
 };
 
+SVGRectElement implements SVGExternalResourcesRequired;
+
diff --git a/Source/core/svg/SVGSVGElement.cpp b/Source/core/svg/SVGSVGElement.cpp
index 929d9f8..1fb7667 100644
--- a/Source/core/svg/SVGSVGElement.cpp
+++ b/Source/core/svg/SVGSVGElement.cpp
@@ -75,12 +75,11 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
     REGISTER_LOCAL_ANIMATED_PROPERTY(viewBox)
     REGISTER_LOCAL_ANIMATED_PROPERTY(preserveAspectRatio)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGSVGElement::SVGSVGElement(const QualifiedName& tagName, Document* doc)
-    : SVGStyledTransformableElement(tagName, doc)
+    : SVGGraphicsElement(tagName, doc)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
     , m_width(LengthModeWidth, "100%")
@@ -257,19 +256,18 @@
         setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
     else if (name == SVGNames::heightAttr)
         setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
-    else if (SVGTests::parseAttribute(name, value)
-               || SVGLangSpace::parseAttribute(name, value)
+    else if (SVGLangSpace::parseAttribute(name, value)
                || SVGExternalResourcesRequired::parseAttribute(name, value)
                || SVGFitToViewBox::parseAttribute(this, name, value)
                || SVGZoomAndPan::parseAttribute(this, name, value)) {
     } else
-        SVGStyledTransformableElement::parseAttribute(name, value);
+        SVGGraphicsElement::parseAttribute(name, value);
 
     reportAttributeParsingError(parseError, name, value);
 }
 
 void SVGSVGElement::svgAttributeChanged(const QualifiedName& attrName)
-{ 
+{
     bool updateRelativeLengthsOrViewBox = false;
     bool widthChanged = attrName == SVGNames::widthAttr;
     if (widthChanged
@@ -295,8 +293,6 @@
     }
 
     SVGElementInstance::InvalidationGuard invalidationGuard(this);
-    if (SVGTests::handleAttributeChange(this, attrName))
-        return;
 
     if (updateRelativeLengthsOrViewBox
         || SVGLangSpace::isKnownAttribute(attrName)
@@ -307,7 +303,7 @@
         return;
     }
 
-    SVGStyledElement::svgAttributeChanged(attrName);
+    SVGGraphicsElement::svgAttributeChanged(attrName);
 }
 
 unsigned SVGSVGElement::suspendRedraw(unsigned /* maxWaitMilliseconds */)
@@ -477,15 +473,15 @@
     // https://bugs.webkit.org/show_bug.cgi?id=103493
     if (document()->documentElement() == this)
         return true;
-    return StyledElement::rendererIsNeeded(context);
+    return Element::rendererIsNeeded(context);
 }
 
-RenderObject* SVGSVGElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGSVGElement::createRenderer(RenderStyle*)
 {
     if (isOutermostSVGSVGElement())
-        return new (arena) RenderSVGRoot(this);
+        return new (document()->renderArena()) RenderSVGRoot(this);
 
-    return new (arena) RenderSVGViewportContainer(this);
+    return new (document()->renderArena()) RenderSVGViewportContainer(this);
 }
 
 Node::InsertionNotificationRequest SVGSVGElement::insertedInto(ContainerNode* rootParent)
@@ -499,14 +495,14 @@
         if (!document()->parsing() && !document()->processingLoadEvent() && document()->loadEventFinished() && !timeContainer()->isStarted())
             timeContainer()->begin();
     }
-    return SVGStyledTransformableElement::insertedInto(rootParent);
+    return SVGGraphicsElement::insertedInto(rootParent);
 }
 
 void SVGSVGElement::removedFrom(ContainerNode* rootParent)
 {
     if (rootParent->inDocument())
         document()->accessSVGExtensions()->removeTimeContainer(this);
-    SVGStyledTransformableElement::removedFrom(rootParent);
+    SVGGraphicsElement::removedFrom(rootParent);
 }
 
 void SVGSVGElement::pauseAnimations()
diff --git a/Source/core/svg/SVGSVGElement.h b/Source/core/svg/SVGSVGElement.h
index d5e9aac..45cc287 100644
--- a/Source/core/svg/SVGSVGElement.h
+++ b/Source/core/svg/SVGSVGElement.h
@@ -27,9 +27,7 @@
 #include "core/svg/SVGAnimatedRect.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGFitToViewBox.h"
-#include "core/svg/SVGLangSpace.h"
-#include "core/svg/SVGStyledTransformableElement.h"
-#include "core/svg/SVGTests.h"
+#include "core/svg/SVGGraphicsElement.h"
 #include "core/svg/SVGZoomAndPan.h"
 
 namespace WebCore {
@@ -41,17 +39,15 @@
 class SVGViewElement;
 class SMILTimeContainer;
 
-class SVGSVGElement FINAL : public SVGStyledTransformableElement,
-                            public SVGTests,
-                            public SVGLangSpace,
+class SVGSVGElement FINAL : public SVGGraphicsElement,
                             public SVGExternalResourcesRequired,
                             public SVGFitToViewBox,
                             public SVGZoomAndPan {
 public:
     static PassRefPtr<SVGSVGElement> create(const QualifiedName&, Document*);
 
-    using SVGStyledTransformableElement::ref;
-    using SVGStyledTransformableElement::deref;
+    using SVGGraphicsElement::ref;
+    using SVGGraphicsElement::deref;
 
     virtual bool isValid() const { return SVGTests::isValid(); }
     virtual bool supportsFocus() const { return true; }
@@ -145,7 +141,7 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
 
     virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     virtual InsertionNotificationRequest insertedInto(ContainerNode*) OVERRIDE;
     virtual void removedFrom(ContainerNode*) OVERRIDE;
@@ -173,11 +169,6 @@
         DECLARE_ANIMATED_PRESERVEASPECTRATIO(PreserveAspectRatio, preserveAspectRatio)
     END_DECLARE_ANIMATED_PROPERTIES
 
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
-
     virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope) const;
 
     bool m_useCurrentView;
diff --git a/Source/core/svg/SVGSVGElement.idl b/Source/core/svg/SVGSVGElement.idl
index e32c0a3..c2d6852 100644
--- a/Source/core/svg/SVGSVGElement.idl
+++ b/Source/core/svg/SVGSVGElement.idl
@@ -21,15 +21,8 @@
  */
 
 // TODO: no css::ViewCSS available!
-// TODO: Fix SVGSVGElement inheritance (css::DocumentCSS)! 
 // TODO: no events::DocumentEvent available!
-interface SVGSVGElement : SVGStyledElement,
-                          SVGTests,
-                          SVGLangSpace,
-                          SVGExternalResourcesRequired,
-                          SVGTransformable,
-                          SVGFitToViewBox,
-                          SVGZoomAndPan {
+interface SVGSVGElement : SVGGraphicsElement {
     readonly attribute SVGAnimatedLength x;
     readonly attribute SVGAnimatedLength y;
     readonly attribute SVGAnimatedLength width;
@@ -76,3 +69,7 @@
     Element getElementById([Default=Undefined] optional DOMString elementId);
 };
 
+SVGSVGElement implements SVGExternalResourcesRequired;
+SVGSVGElement implements SVGFitToViewBox;
+SVGSVGElement implements SVGZoomAndPan;
+
diff --git a/Source/core/svg/SVGScriptElement.cpp b/Source/core/svg/SVGScriptElement.cpp
index c835b19..754f98d 100644
--- a/Source/core/svg/SVGScriptElement.cpp
+++ b/Source/core/svg/SVGScriptElement.cpp
@@ -65,7 +65,7 @@
         supportedAttributes.add(SVGNames::typeAttr);
         supportedAttributes.add(HTMLNames::onerrorAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGScriptElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGScriptElement.idl b/Source/core/svg/SVGScriptElement.idl
index 5a7ec3d..dea339f 100644
--- a/Source/core/svg/SVGScriptElement.idl
+++ b/Source/core/svg/SVGScriptElement.idl
@@ -23,9 +23,10 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGScriptElement : SVGElement,
-                             SVGURIReference,
-                             SVGExternalResourcesRequired {
+interface SVGScriptElement : SVGElement {
              [TreatNullAs=NullString] attribute DOMString type;
 };
 
+SVGScriptElement implements SVGExternalResourcesRequired;
+SVGScriptElement implements SVGURIReference;
+
diff --git a/Source/core/svg/SVGStopElement.cpp b/Source/core/svg/SVGStopElement.cpp
index 71fe014..96c7814 100644
--- a/Source/core/svg/SVGStopElement.cpp
+++ b/Source/core/svg/SVGStopElement.cpp
@@ -56,7 +56,7 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty())
         supportedAttributes.add(SVGNames::offsetAttr);
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGStopElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -97,9 +97,9 @@
     ASSERT_NOT_REACHED();
 }
 
-RenderObject* SVGStopElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGStopElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGGradientStop(this);
+    return new (document()->renderArena()) RenderSVGGradientStop(this);
 }
 
 bool SVGStopElement::rendererIsNeeded(const NodeRenderingContext&)
diff --git a/Source/core/svg/SVGStopElement.h b/Source/core/svg/SVGStopElement.h
index e5f47cf..7094a91 100644
--- a/Source/core/svg/SVGStopElement.h
+++ b/Source/core/svg/SVGStopElement.h
@@ -41,7 +41,7 @@
 
     virtual bool isGradientStop() const OVERRIDE { return true; }
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool rendererIsNeeded(const NodeRenderingContext&) OVERRIDE;
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGStopElement)
diff --git a/Source/core/svg/SVGStringList.cpp b/Source/core/svg/SVGStringList.cpp
index 682eba5..7b87a42 100644
--- a/Source/core/svg/SVGStringList.cpp
+++ b/Source/core/svg/SVGStringList.cpp
@@ -44,15 +44,11 @@
         append(emptyString());
 }
 
-void SVGStringList::parse(const String& data, UChar delimiter)
+template<typename CharType>
+void SVGStringList::parseInternal(const CharType*& ptr, const CharType* end, UChar delimiter)
 {
-    // TODO : more error checking/reporting
-    clear();
-
-    const UChar* ptr = data.characters();
-    const UChar* end = ptr + data.length();
     while (ptr < end) {
-        const UChar* start = ptr;
+        const CharType* start = ptr;
         while (ptr < end && *ptr != delimiter && !isSVGSpace(*ptr))
             ptr++;
         if (ptr == start)
@@ -62,6 +58,23 @@
     }
 }
 
+void SVGStringList::parse(const String& data, UChar delimiter)
+{
+    // FIXME: Add more error checking and reporting.
+    clear();
+    if (data.isEmpty())
+        return;
+    if (data.is8Bit()) {
+        const LChar* ptr = data.characters8();
+        const LChar* end = ptr + data.length();
+        parseInternal(ptr, end, delimiter);
+    } else {
+        const UChar* ptr = data.characters16();
+        const UChar* end = ptr + data.length();
+        parseInternal(ptr, end, delimiter);
+    }
+}
+
 String SVGStringList::valueAsString() const
 {
     StringBuilder builder;
diff --git a/Source/core/svg/SVGStringList.h b/Source/core/svg/SVGStringList.h
index 322acd3..3f75417 100644
--- a/Source/core/svg/SVGStringList.h
+++ b/Source/core/svg/SVGStringList.h
@@ -45,6 +45,9 @@
     String valueAsString() const;
 
 private:
+    template<typename CharType>
+    void parseInternal(const CharType*& ptr, const CharType* end, UChar delimiter);
+
     const QualifiedName& m_attributeName;
 };
 
diff --git a/Source/core/svg/SVGStyleElement.cpp b/Source/core/svg/SVGStyleElement.cpp
index ce9cdd4..4d87e87 100644
--- a/Source/core/svg/SVGStyleElement.cpp
+++ b/Source/core/svg/SVGStyleElement.cpp
@@ -104,7 +104,7 @@
         SVGLangSpace::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::titleAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGStyleElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGStyleElement.h b/Source/core/svg/SVGStyleElement.h
index 5c31b0d..84d7a0e 100644
--- a/Source/core/svg/SVGStyleElement.h
+++ b/Source/core/svg/SVGStyleElement.h
@@ -23,12 +23,10 @@
 
 #include "core/dom/StyleElement.h"
 #include "core/svg/SVGElement.h"
-#include "core/svg/SVGLangSpace.h"
 
 namespace WebCore {
 
 class SVGStyleElement FINAL : public SVGElement
-                            , public SVGLangSpace
                             , public StyleElement {
 public:
     static PassRefPtr<SVGStyleElement> create(const QualifiedName&, Document*, bool createdByParser);
diff --git a/Source/core/svg/SVGStyleElement.idl b/Source/core/svg/SVGStyleElement.idl
index 56beb82..431061d 100644
--- a/Source/core/svg/SVGStyleElement.idl
+++ b/Source/core/svg/SVGStyleElement.idl
@@ -24,7 +24,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGStyleElement : SVGElement, SVGLangSpace {
+interface SVGStyleElement : SVGElement {
     attribute boolean disabled;
     attribute DOMString type;
     attribute DOMString media;
diff --git a/Source/core/svg/SVGStyledElement.cpp b/Source/core/svg/SVGStyledElement.cpp
index a4f783b..9a683d4 100644
--- a/Source/core/svg/SVGStyledElement.cpp
+++ b/Source/core/svg/SVGStyledElement.cpp
@@ -123,7 +123,7 @@
     // with the SVG content. In general, the SVG user agent will include the unknown
     // elements in the DOM but will otherwise ignore unknown elements. 
     if (!parentOrShadowHostElement() || parentOrShadowHostElement()->isSVGElement())
-        return StyledElement::rendererIsNeeded(context);
+        return Element::rendererIsNeeded(context);
 
     return false;
 }
@@ -305,14 +305,14 @@
 {
     // SVG animation has currently requires special storage of values so we set
     // the className here.  svgAttributeChanged actually causes the resulting
-    // style updates (instead of StyledElement::parseAttribute). We don't
-    // tell StyledElement about the change to avoid parsing the class list twice
+    // style updates (instead of Element::parseAttribute). We don't
+    // tell Element about the change to avoid parsing the class list twice
     if (name == HTMLNames::classAttr) {
         setClassNameBaseValue(value);
         return;
     }
 
-    // id is handled by StyledElement which SVGElement inherits from
+    // id is handled by Element which SVGElement inherits from
     SVGElement::parseAttribute(name, value);
 }
 
@@ -426,7 +426,7 @@
 
 AffineTransform SVGStyledElement::localCoordinateSpaceTransform(SVGLocatable::CTMScope) const
 {
-    // To be overriden by SVGStyledLocatableElement/SVGStyledTransformableElement (or as special case SVGTextElement and SVGPatternElement)
+    // To be overriden by SVGStyledLocatableElement/SVGGraphicsElement (or as special case SVGTextElement and SVGPatternElement)
     return AffineTransform();
 }
 
diff --git a/Source/core/svg/SVGStyledElement.h b/Source/core/svg/SVGStyledElement.h
index e02af43..4b676d1 100644
--- a/Source/core/svg/SVGStyledElement.h
+++ b/Source/core/svg/SVGStyledElement.h
@@ -55,7 +55,6 @@
 
     virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope) const;
 
-    virtual CSSStyleDeclaration* style() { return StyledElement::style(); }
     virtual bool needsPendingResourceHandling() const { return true; }
 
 protected: 
diff --git a/Source/core/svg/SVGStyledLocatableElement.cpp b/Source/core/svg/SVGStyledLocatableElement.cpp
deleted file mode 100644
index ac4ba31..0000000
--- a/Source/core/svg/SVGStyledLocatableElement.cpp
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#include "config.h"
-
-#include "core/svg/SVGStyledLocatableElement.h"
-
-#include "core/platform/graphics/transforms/AffineTransform.h"
-
-namespace WebCore {
-
-SVGStyledLocatableElement::SVGStyledLocatableElement(const QualifiedName& tagName, Document* document, ConstructionType constructionType)
-    : SVGStyledElement(tagName, document, constructionType)
-{
-}
-
-SVGElement* SVGStyledLocatableElement::nearestViewportElement() const
-{
-    return SVGLocatable::nearestViewportElement(this);
-}
-
-SVGElement* SVGStyledLocatableElement::farthestViewportElement() const
-{
-    return SVGLocatable::farthestViewportElement(this);
-}
-
-FloatRect SVGStyledLocatableElement::getBBox(StyleUpdateStrategy styleUpdateStrategy)
-{
-    return SVGLocatable::getBBox(this, styleUpdateStrategy);
-}
-
-AffineTransform SVGStyledLocatableElement::getCTM(StyleUpdateStrategy styleUpdateStrategy)
-{
-    return SVGLocatable::computeCTM(this, SVGLocatable::NearestViewportScope, styleUpdateStrategy);
-}
-
-AffineTransform SVGStyledLocatableElement::getScreenCTM(StyleUpdateStrategy styleUpdateStrategy)
-{
-    return SVGLocatable::computeCTM(this, SVGLocatable::ScreenScope, styleUpdateStrategy);
-}
-
-}
diff --git a/Source/core/svg/SVGStyledLocatableElement.h b/Source/core/svg/SVGStyledLocatableElement.h
deleted file mode 100644
index 566ef20..0000000
--- a/Source/core/svg/SVGStyledLocatableElement.h
+++ /dev/null
@@ -1,58 +0,0 @@
-/*
- * Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org>
- * Copyright (C) 2004, 2005, 2006 Rob Buis <buis@kde.org>
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Library General Public
- * License as published by the Free Software Foundation; either
- * version 2 of the License, or (at your option) any later version.
- *
- * This library is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
- * Library General Public License for more details.
- *
- * You should have received a copy of the GNU Library General Public License
- * along with this library; see the file COPYING.LIB.  If not, write to
- * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
- * Boston, MA 02110-1301, USA.
- */
-
-#ifndef SVGStyledLocatableElement_h
-#define SVGStyledLocatableElement_h
-
-#include "core/svg/SVGLocatable.h"
-#include "core/svg/SVGStyledElement.h"
-
-namespace WebCore {
-
-class SVGElement;
-
-class SVGStyledLocatableElement : public SVGStyledElement,
-                                  virtual public SVGLocatable {
-public:
-    virtual SVGElement* nearestViewportElement() const;
-    virtual SVGElement* farthestViewportElement() const;
-
-    virtual FloatRect getBBox(StyleUpdateStrategy = AllowStyleUpdate);
-    virtual AffineTransform getCTM(StyleUpdateStrategy = AllowStyleUpdate);
-    virtual AffineTransform getScreenCTM(StyleUpdateStrategy = AllowStyleUpdate);
-
-    virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope mode) const { return SVGLocatable::localCoordinateSpaceTransform(mode); }
-
-protected:
-    SVGStyledLocatableElement(const QualifiedName&, Document*, ConstructionType = CreateSVGElement);
-
-private:
-    virtual bool isStyledLocatable() const OVERRIDE { return true; }
-};
-
-inline SVGStyledLocatableElement* toSVGStyledLocatableElement(SVGElement* element)
-{
-    ASSERT_WITH_SECURITY_IMPLICATION(!element || element->isStyledLocatable());
-    return static_cast<SVGStyledLocatableElement*>(element);
-}
-
-} // namespace WebCore
-
-#endif // SVGStyledLocatableElement_h
diff --git a/Source/core/svg/SVGSwitchElement.cpp b/Source/core/svg/SVGSwitchElement.cpp
index cdd76eb..99931e9 100644
--- a/Source/core/svg/SVGSwitchElement.cpp
+++ b/Source/core/svg/SVGSwitchElement.cpp
@@ -34,12 +34,11 @@
 
 BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGSwitchElement)
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGSwitchElement::SVGSwitchElement(const QualifiedName& tagName, Document* document)
-    : SVGStyledTransformableElement(tagName, document)
+    : SVGGraphicsElement(tagName, document)
 {
     ASSERT(hasTagName(SVGNames::switchTag));
     ScriptWrappable::init(this);
@@ -71,9 +70,9 @@
     return false;
 }
 
-RenderObject* SVGSwitchElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGSwitchElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGTransformableContainer(this);
+    return new (document()->renderArena()) RenderSVGTransformableContainer(this);
 }
 
 }
diff --git a/Source/core/svg/SVGSwitchElement.h b/Source/core/svg/SVGSwitchElement.h
index 5a37cf5..f629b29 100644
--- a/Source/core/svg/SVGSwitchElement.h
+++ b/Source/core/svg/SVGSwitchElement.h
@@ -23,15 +23,11 @@
 
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGLangSpace.h"
-#include "core/svg/SVGStyledTransformableElement.h"
-#include "core/svg/SVGTests.h"
+#include "core/svg/SVGGraphicsElement.h"
 
 namespace WebCore {
 
-class SVGSwitchElement FINAL : public SVGStyledTransformableElement,
-                               public SVGTests,
-                               public SVGLangSpace,
+class SVGSwitchElement FINAL : public SVGGraphicsElement,
                                public SVGExternalResourcesRequired {
 public:
     static PassRefPtr<SVGSwitchElement> create(const QualifiedName&, Document*);
@@ -44,16 +40,11 @@
 
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGSwitchElement)
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired)
     END_DECLARE_ANIMATED_PROPERTIES
-
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGSwitchElement.idl b/Source/core/svg/SVGSwitchElement.idl
index 512d8ce..cc801c9 100644
--- a/Source/core/svg/SVGSwitchElement.idl
+++ b/Source/core/svg/SVGSwitchElement.idl
@@ -23,10 +23,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGSwitchElement : SVGStyledElement,
-                             SVGTests,
-                             SVGLangSpace,
-                             SVGExternalResourcesRequired,
-                             SVGTransformable {
+interface SVGSwitchElement : SVGGraphicsElement {
 };
 
+SVGSwitchElement implements SVGExternalResourcesRequired;
+
diff --git a/Source/core/svg/SVGSymbolElement.cpp b/Source/core/svg/SVGSymbolElement.cpp
index e1db441..8693727 100644
--- a/Source/core/svg/SVGSymbolElement.cpp
+++ b/Source/core/svg/SVGSymbolElement.cpp
@@ -62,7 +62,7 @@
         SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         SVGFitToViewBox::addSupportedAttributes(supportedAttributes);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGSymbolElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -101,9 +101,9 @@
     return hasAttribute(SVGNames::viewBoxAttr);
 }
 
-RenderObject* SVGSymbolElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGSymbolElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGHiddenContainer(this);
+    return new (document()->renderArena()) RenderSVGHiddenContainer(this);
 }
 
 }
diff --git a/Source/core/svg/SVGSymbolElement.h b/Source/core/svg/SVGSymbolElement.h
index d06f1b3..3619708 100644
--- a/Source/core/svg/SVGSymbolElement.h
+++ b/Source/core/svg/SVGSymbolElement.h
@@ -26,13 +26,11 @@
 #include "core/svg/SVGAnimatedRect.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
 #include "core/svg/SVGFitToViewBox.h"
-#include "core/svg/SVGLangSpace.h"
 #include "core/svg/SVGStyledElement.h"
 
 namespace WebCore {
 
 class SVGSymbolElement FINAL : public SVGStyledElement,
-                               public SVGLangSpace,
                                public SVGExternalResourcesRequired,
                                public SVGFitToViewBox {
 public:
@@ -46,7 +44,7 @@
     bool isSupportedAttribute(const QualifiedName&);
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void svgAttributeChanged(const QualifiedName&);
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
 
     virtual bool selfHasRelativeLengths() const;
 
diff --git a/Source/core/svg/SVGSymbolElement.idl b/Source/core/svg/SVGSymbolElement.idl
index 94c9bd6..d866ab2 100644
--- a/Source/core/svg/SVGSymbolElement.idl
+++ b/Source/core/svg/SVGSymbolElement.idl
@@ -23,9 +23,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGSymbolElement : SVGStyledElement,
-                             SVGLangSpace,
-                             SVGExternalResourcesRequired,
-                             SVGFitToViewBox {
+interface SVGSymbolElement : SVGStyledElement {
 };
 
+SVGSymbolElement implements SVGExternalResourcesRequired;
+SVGSymbolElement implements SVGFitToViewBox;
diff --git a/Source/core/svg/SVGTRefElement.cpp b/Source/core/svg/SVGTRefElement.cpp
index 839f91f..553ba68 100644
--- a/Source/core/svg/SVGTRefElement.cpp
+++ b/Source/core/svg/SVGTRefElement.cpp
@@ -190,7 +190,7 @@
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty())
         SVGURIReference::addSupportedAttributes(supportedAttributes);
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGTRefElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -225,9 +225,9 @@
     ASSERT_NOT_REACHED();
 }
 
-RenderObject* SVGTRefElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGTRefElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGInline(this);
+    return new (document()->renderArena()) RenderSVGInline(this);
 }
 
 bool SVGTRefElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
@@ -245,7 +245,7 @@
             || parentNode()->hasTagName(SVGNames::textTag)
             || parentNode()->hasTagName(SVGNames::textPathTag)
             || parentNode()->hasTagName(SVGNames::tspanTag)))
-        return StyledElement::rendererIsNeeded(context);
+        return Element::rendererIsNeeded(context);
 
     return false;
 }
diff --git a/Source/core/svg/SVGTRefElement.h b/Source/core/svg/SVGTRefElement.h
index ee66c68..8a6378d 100644
--- a/Source/core/svg/SVGTRefElement.h
+++ b/Source/core/svg/SVGTRefElement.h
@@ -43,7 +43,7 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void svgAttributeChanged(const QualifiedName&);
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
     virtual bool rendererIsNeeded(const NodeRenderingContext&);
 
diff --git a/Source/core/svg/SVGTRefElement.idl b/Source/core/svg/SVGTRefElement.idl
index 5f58232..27eef02 100644
--- a/Source/core/svg/SVGTRefElement.idl
+++ b/Source/core/svg/SVGTRefElement.idl
@@ -23,7 +23,8 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGTRefElement : SVGTextPositioningElement,
-                           SVGURIReference {
+interface SVGTRefElement : SVGTextPositioningElement {
 };
 
+SVGTRefElement implements SVGURIReference;
+
diff --git a/Source/core/svg/SVGTSpanElement.cpp b/Source/core/svg/SVGTSpanElement.cpp
index 201f2f5..89bb9ec 100644
--- a/Source/core/svg/SVGTSpanElement.cpp
+++ b/Source/core/svg/SVGTSpanElement.cpp
@@ -40,9 +40,9 @@
     return adoptRef(new SVGTSpanElement(tagName, document));
 }
 
-RenderObject* SVGTSpanElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGTSpanElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGTSpan(this);
+    return new (document()->renderArena()) RenderSVGTSpan(this);
 }
 
 bool SVGTSpanElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
@@ -69,7 +69,7 @@
             || parentNode()->hasTagName(SVGNames::textTag)
             || parentNode()->hasTagName(SVGNames::textPathTag)
             || parentNode()->hasTagName(SVGNames::tspanTag)))
-        return StyledElement::rendererIsNeeded(context);
+        return Element::rendererIsNeeded(context);
 
     return false;
 }
diff --git a/Source/core/svg/SVGTSpanElement.h b/Source/core/svg/SVGTSpanElement.h
index 3e28dbb..8ba3c23 100644
--- a/Source/core/svg/SVGTSpanElement.h
+++ b/Source/core/svg/SVGTSpanElement.h
@@ -32,7 +32,7 @@
 private:
     SVGTSpanElement(const QualifiedName&, Document*);
             
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
     virtual bool rendererIsNeeded(const NodeRenderingContext&);
 };
diff --git a/Source/core/svg/SVGTests.idl b/Source/core/svg/SVGTests.idl
index 8f47e8e..e2eaa13 100644
--- a/Source/core/svg/SVGTests.idl
+++ b/Source/core/svg/SVGTests.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    DoNotGenerateToV8
+    NoInterfaceObject
 ] interface SVGTests {
     readonly attribute SVGStringList requiredFeatures;
     readonly attribute SVGStringList requiredExtensions;
diff --git a/Source/core/svg/SVGTextContentElement.cpp b/Source/core/svg/SVGTextContentElement.cpp
index d8ae19f..9a41300 100644
--- a/Source/core/svg/SVGTextContentElement.cpp
+++ b/Source/core/svg/SVGTextContentElement.cpp
@@ -58,12 +58,11 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(textLength)
     REGISTER_LOCAL_ANIMATED_PROPERTY(lengthAdjust)
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 SVGTextContentElement::SVGTextContentElement(const QualifiedName& tagName, Document* document)
-    : SVGStyledElement(tagName, document)
+    : SVGGraphicsElement(tagName, document)
     , m_textLength(LengthModeOther)
     , m_specifiedTextLength(LengthModeOther)
     , m_lengthAdjust(SVGLengthAdjustSpacing)
@@ -215,26 +214,25 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGTests::addSupportedAttributes(supportedAttributes);
         SVGLangSpace::addSupportedAttributes(supportedAttributes);
         SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::lengthAdjustAttr);
         supportedAttributes.add(SVGNames::textLengthAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 bool SVGTextContentElement::isPresentationAttribute(const QualifiedName& name) const
 {
     if (name.matches(XMLNames::spaceAttr))
         return true;
-    return SVGStyledElement::isPresentationAttribute(name);
+    return SVGGraphicsElement::isPresentationAttribute(name);
 }
 
 void SVGTextContentElement::collectStyleForPresentationAttribute(const QualifiedName& name, const AtomicString& value, MutableStylePropertySet* style)
 {
     if (!isSupportedAttribute(name))
-        SVGStyledElement::collectStyleForPresentationAttribute(name, value, style);
+        SVGGraphicsElement::collectStyleForPresentationAttribute(name, value, style);
     else if (name.matches(XMLNames::spaceAttr)) {
         DEFINE_STATIC_LOCAL(const AtomicString, preserveString, ("preserve", AtomicString::ConstructFromLiteral));
 
@@ -250,15 +248,14 @@
     SVGParsingError parseError = NoError;
 
     if (!isSupportedAttribute(name))
-        SVGStyledElement::parseAttribute(name, value);
+        SVGGraphicsElement::parseAttribute(name, value);
     else if (name == SVGNames::lengthAdjustAttr) {
         SVGLengthAdjustType propertyValue = SVGPropertyTraits<SVGLengthAdjustType>::fromString(value);
         if (propertyValue > 0)
             setLengthAdjustBaseValue(propertyValue);
     } else if (name == SVGNames::textLengthAttr) {
         m_textLength.value = SVGLength::construct(LengthModeOther, value, parseError, ForbidNegativeLengths);
-    } else if (SVGTests::parseAttribute(name, value)
-               || SVGExternalResourcesRequired::parseAttribute(name, value)) {
+    } else if (SVGExternalResourcesRequired::parseAttribute(name, value)) {
     } else if (SVGLangSpace::parseAttribute(name, value)) {
     } else
         ASSERT_NOT_REACHED();
@@ -269,15 +266,12 @@
 void SVGTextContentElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGStyledElement::svgAttributeChanged(attrName);
+        SVGGraphicsElement::svgAttributeChanged(attrName);
         return;
     }
 
     SVGElementInstance::InvalidationGuard invalidationGuard(this);
 
-    if (SVGTests::handleAttributeChange(this, attrName))
-        return;
-
     if (attrName == SVGNames::textLengthAttr)
         m_specifiedTextLength = m_textLength.value;
 
@@ -301,20 +295,13 @@
     if (!renderer->isSVGText() && !renderer->isSVGInline())
         return 0;
 
-    Node* node = renderer->node();
-    ASSERT(node);
-    ASSERT(node->isSVGElement());
+    SVGElement* element = toSVGElement(renderer->node());
+    ASSERT(element);
 
-    if (!node->hasTagName(SVGNames::textTag)
-        && !node->hasTagName(SVGNames::tspanTag)
-#if ENABLE(SVG_FONTS)
-        && !node->hasTagName(SVGNames::altGlyphTag)
-#endif
-        && !node->hasTagName(SVGNames::trefTag)
-        && !node->hasTagName(SVGNames::textPathTag))
+    if (!element->isTextContent())
         return 0;
 
-    return static_cast<SVGTextContentElement*>(node);
+    return toSVGTextContentElement(element);
 }
 
 }
diff --git a/Source/core/svg/SVGTextContentElement.h b/Source/core/svg/SVGTextContentElement.h
index 1bd62b2..6b1d0fa 100644
--- a/Source/core/svg/SVGTextContentElement.h
+++ b/Source/core/svg/SVGTextContentElement.h
@@ -25,9 +25,7 @@
 #include "core/svg/SVGAnimatedEnumeration.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGLangSpace.h"
-#include "core/svg/SVGStyledElement.h"
-#include "core/svg/SVGTests.h"
+#include "core/svg/SVGGraphicsElement.h"
 
 namespace WebCore {
 
@@ -66,9 +64,7 @@
     }
 };
 
-class SVGTextContentElement : public SVGStyledElement,
-                              public SVGTests,
-                              public SVGLangSpace,
+class SVGTextContentElement : public SVGGraphicsElement,
                               public SVGExternalResourcesRequired {
 public:
     // Forward declare enumerations in the W3C naming scheme, for IDL generation.
@@ -122,11 +118,6 @@
         DECLARE_ANIMATED_ENUMERATION(LengthAdjust, lengthAdjust, SVGLengthAdjustType)
         DECLARE_ANIMATED_BOOLEAN(ExternalResourcesRequired, externalResourcesRequired) 
     END_DECLARE_ANIMATED_PROPERTIES
-
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
 };
 
 inline SVGTextContentElement* toSVGTextContentElement(SVGElement* element)
diff --git a/Source/core/svg/SVGTextContentElement.idl b/Source/core/svg/SVGTextContentElement.idl
index 4a2acb9..689c7bd 100644
--- a/Source/core/svg/SVGTextContentElement.idl
+++ b/Source/core/svg/SVGTextContentElement.idl
@@ -23,10 +23,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGTextContentElement : SVGStyledElement,
-                                  SVGTests,
-                                  SVGLangSpace,
-                                  SVGExternalResourcesRequired {
+interface SVGTextContentElement : SVGGraphicsElement {
     // lengthAdjust Types
     const unsigned short LENGTHADJUST_UNKNOWN          = 0;
     const unsigned short LENGTHADJUST_SPACING          = 1;
@@ -48,3 +45,6 @@
                          [Default=Undefined,IsIndex] optional unsigned long length);
 };
 
+// FIXME: SVGTextContentElement is not supposed to implement SVGExternalResourcesRequired.
+SVGTextContentElement implements SVGExternalResourcesRequired;
+
diff --git a/Source/core/svg/SVGTextElement.cpp b/Source/core/svg/SVGTextElement.cpp
index 2319c22..ff72883 100644
--- a/Source/core/svg/SVGTextElement.cpp
+++ b/Source/core/svg/SVGTextElement.cpp
@@ -24,28 +24,17 @@
 
 #include "SVGNames.h"
 #include "core/dom/NodeRenderingContext.h"
-#include "core/platform/graphics/FloatRect.h"
-#include "core/platform/graphics/transforms/AffineTransform.h"
 #include "core/rendering/svg/RenderSVGResource.h"
 #include "core/rendering/svg/RenderSVGText.h"
 #include "core/svg/SVGElementInstance.h"
 
 namespace WebCore {
 
-// Animated property definitions
-DEFINE_ANIMATED_TRANSFORM_LIST(SVGTextElement, SVGNames::transformAttr, Transform, transform)
-
-BEGIN_REGISTER_ANIMATED_PROPERTIES(SVGTextElement)
-    REGISTER_LOCAL_ANIMATED_PROPERTY(transform)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTextPositioningElement)
-END_REGISTER_ANIMATED_PROPERTIES
-
 inline SVGTextElement::SVGTextElement(const QualifiedName& tagName, Document* doc)
     : SVGTextPositioningElement(tagName, doc)
 {
     ASSERT(hasTagName(SVGNames::textTag));
     ScriptWrappable::init(this);
-    registerAnimatedPropertiesForSVGTextElement();
 }
 
 PassRefPtr<SVGTextElement> SVGTextElement::create(const QualifiedName& tagName, Document* document)
@@ -53,57 +42,8 @@
     return adoptRef(new SVGTextElement(tagName, document));
 }
 
-bool SVGTextElement::isSupportedAttribute(const QualifiedName& attrName)
-{
-    DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
-    if (supportedAttributes.isEmpty())
-        supportedAttributes.add(SVGNames::transformAttr);
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
-}
-
-void SVGTextElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
-{
-    if (!isSupportedAttribute(name)) {
-        SVGTextPositioningElement::parseAttribute(name, value);
-        return;
-    }
-
-    if (name == SVGNames::transformAttr) {
-        SVGTransformList newList;
-        newList.parse(value);
-        detachAnimatedTransformListWrappers(newList.size());
-        setTransformBaseValue(newList);
-        return;
-    }
-
-    ASSERT_NOT_REACHED();
-}
-
-SVGElement* SVGTextElement::nearestViewportElement() const
-{
-    return SVGTransformable::nearestViewportElement(this);
-}
-
-SVGElement* SVGTextElement::farthestViewportElement() const
-{
-    return SVGTransformable::farthestViewportElement(this);
-}
-
-FloatRect SVGTextElement::getBBox(StyleUpdateStrategy styleUpdateStrategy)
-{
-    return SVGTransformable::getBBox(this, styleUpdateStrategy);
-}
-
-AffineTransform SVGTextElement::getCTM(StyleUpdateStrategy styleUpdateStrategy)
-{
-    return SVGLocatable::computeCTM(this, SVGLocatable::NearestViewportScope, styleUpdateStrategy);
-}
-
-AffineTransform SVGTextElement::getScreenCTM(StyleUpdateStrategy styleUpdateStrategy)
-{
-    return SVGLocatable::computeCTM(this, SVGLocatable::ScreenScope, styleUpdateStrategy);
-}
-
+// We override SVGGraphics::animatedLocalTransform() so that the transform-origin
+// is not taken into account.
 AffineTransform SVGTextElement::animatedLocalTransform() const
 {
     AffineTransform matrix;
@@ -120,21 +60,15 @@
     } else
         transform().concatenate(matrix);
 
-    if (m_supplementalTransform)
-        return *m_supplementalTransform * matrix;
+    const AffineTransform* transform = const_cast<SVGTextElement*>(this)->supplementalTransform();
+    if (transform)
+        return *transform * matrix;
     return matrix;
 }
 
-AffineTransform* SVGTextElement::supplementalTransform()
+RenderObject* SVGTextElement::createRenderer(RenderStyle*)
 {
-    if (!m_supplementalTransform)
-        m_supplementalTransform = adoptPtr(new AffineTransform);
-    return m_supplementalTransform.get();
-}
-
-RenderObject* SVGTextElement::createRenderer(RenderArena* arena, RenderStyle*)
-{
-    return new (arena) RenderSVGText(this);
+    return new (document()->renderArena()) RenderSVGText(this);
 }
 
 bool SVGTextElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
@@ -152,26 +86,4 @@
     return false;
 }
 
-void SVGTextElement::svgAttributeChanged(const QualifiedName& attrName)
-{
-    if (!isSupportedAttribute(attrName)) {
-        SVGTextPositioningElement::svgAttributeChanged(attrName);
-        return;
-    }
-
-    SVGElementInstance::InvalidationGuard invalidationGuard(this);
-
-    RenderObject* renderer = this->renderer();
-    if (!renderer)
-        return;
-
-    if (attrName == SVGNames::transformAttr) {
-        renderer->setNeedsTransformUpdate();
-        RenderSVGResource::markForLayoutAndParentResourceInvalidation(renderer);
-        return;
-    }
-
-    ASSERT_NOT_REACHED();
-}
-
 }
diff --git a/Source/core/svg/SVGTextElement.h b/Source/core/svg/SVGTextElement.h
index dba5212..998a069 100644
--- a/Source/core/svg/SVGTextElement.h
+++ b/Source/core/svg/SVGTextElement.h
@@ -23,21 +23,13 @@
 
 #include "core/svg/SVGAnimatedTransformList.h"
 #include "core/svg/SVGTextPositioningElement.h"
-#include "core/svg/SVGTransformable.h"
 
 namespace WebCore {
 
-class SVGTextElement FINAL : public SVGTextPositioningElement,
-                             public SVGTransformable {
+class SVGTextElement FINAL : public SVGTextPositioningElement {
 public:
     static PassRefPtr<SVGTextElement> create(const QualifiedName&, Document*);
 
-    virtual SVGElement* nearestViewportElement() const;
-    virtual SVGElement* farthestViewportElement() const;
-
-    virtual FloatRect getBBox(StyleUpdateStrategy = AllowStyleUpdate);
-    virtual AffineTransform getCTM(StyleUpdateStrategy = AllowStyleUpdate);
-    virtual AffineTransform getScreenCTM(StyleUpdateStrategy = AllowStyleUpdate);
     virtual AffineTransform animatedLocalTransform() const;
 
 private:
@@ -45,23 +37,8 @@
 
     virtual bool supportsFocus() const { return true; }
 
-    bool isSupportedAttribute(const QualifiedName&);
-    virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
-
-    virtual AffineTransform* supplementalTransform();
-    virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope mode) const { return SVGTransformable::localCoordinateSpaceTransform(mode); }
-
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
-            
-    virtual void svgAttributeChanged(const QualifiedName&);
-
-    BEGIN_DECLARE_ANIMATED_PROPERTIES(SVGTextElement)
-        DECLARE_ANIMATED_TRANSFORM_LIST(Transform, transform)
-    END_DECLARE_ANIMATED_PROPERTIES
-
-    // Used by <animateMotion>
-    OwnPtr<AffineTransform> m_supplementalTransform;
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGTextElement.idl b/Source/core/svg/SVGTextElement.idl
index fec5719..ce82c08 100644
--- a/Source/core/svg/SVGTextElement.idl
+++ b/Source/core/svg/SVGTextElement.idl
@@ -23,7 +23,6 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGTextElement : SVGTextPositioningElement,
-                           SVGTransformable {
+interface SVGTextElement : SVGTextPositioningElement {
 };
 
diff --git a/Source/core/svg/SVGTextPathElement.cpp b/Source/core/svg/SVGTextPathElement.cpp
index 5359ec6..5541cb3 100644
--- a/Source/core/svg/SVGTextPathElement.cpp
+++ b/Source/core/svg/SVGTextPathElement.cpp
@@ -80,7 +80,7 @@
         supportedAttributes.add(SVGNames::methodAttr);
         supportedAttributes.add(SVGNames::spacingAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGTextPathElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -127,9 +127,9 @@
         RenderSVGResource::markForLayoutAndParentResourceInvalidation(object);
 }
 
-RenderObject* SVGTextPathElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGTextPathElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGTextPath(this);
+    return new (document()->renderArena()) RenderSVGTextPath(this);
 }
 
 bool SVGTextPathElement::childShouldCreateRenderer(const NodeRenderingContext& childContext) const
@@ -148,7 +148,7 @@
     if (parentNode()
         && (parentNode()->hasTagName(SVGNames::aTag)
             || parentNode()->hasTagName(SVGNames::textTag)))
-        return StyledElement::rendererIsNeeded(context);
+        return Element::rendererIsNeeded(context);
 
     return false;
 }
diff --git a/Source/core/svg/SVGTextPathElement.h b/Source/core/svg/SVGTextPathElement.h
index 8a4466e..f1d939f 100644
--- a/Source/core/svg/SVGTextPathElement.h
+++ b/Source/core/svg/SVGTextPathElement.h
@@ -126,7 +126,7 @@
     virtual void parseAttribute(const QualifiedName&, const AtomicString&) OVERRIDE;
     virtual void svgAttributeChanged(const QualifiedName&);
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual bool childShouldCreateRenderer(const NodeRenderingContext&) const;
     virtual bool rendererIsNeeded(const NodeRenderingContext&);
 
diff --git a/Source/core/svg/SVGTextPathElement.idl b/Source/core/svg/SVGTextPathElement.idl
index 629ff18..d21292a 100644
--- a/Source/core/svg/SVGTextPathElement.idl
+++ b/Source/core/svg/SVGTextPathElement.idl
@@ -23,8 +23,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGTextPathElement : SVGTextContentElement,
-                               SVGURIReference {
+interface SVGTextPathElement : SVGTextContentElement {
     // textPath Method Types
     const unsigned short TEXTPATH_METHODTYPE_UNKNOWN   = 0;
     const unsigned short TEXTPATH_METHODTYPE_ALIGN     = 1;
@@ -40,3 +39,5 @@
     readonly attribute SVGAnimatedEnumeration spacing;
 };
 
+SVGTextPathElement implements SVGURIReference;
+
diff --git a/Source/core/svg/SVGTextPositioningElement.cpp b/Source/core/svg/SVGTextPositioningElement.cpp
index 3940145..b8c8f8a 100644
--- a/Source/core/svg/SVGTextPositioningElement.cpp
+++ b/Source/core/svg/SVGTextPositioningElement.cpp
@@ -64,7 +64,7 @@
         supportedAttributes.add(SVGNames::dyAttr);
         supportedAttributes.add(SVGNames::rotateAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGTextPositioningElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGTitleElement.h b/Source/core/svg/SVGTitleElement.h
index 5e84bf7..0edbc54 100644
--- a/Source/core/svg/SVGTitleElement.h
+++ b/Source/core/svg/SVGTitleElement.h
@@ -21,13 +21,11 @@
 #ifndef SVGTitleElement_h
 #define SVGTitleElement_h
 
-#include "core/svg/SVGLangSpace.h"
 #include "core/svg/SVGStyledElement.h"
 
 namespace WebCore {
 
-class SVGTitleElement FINAL : public SVGStyledElement,
-                              public SVGLangSpace {
+class SVGTitleElement FINAL : public SVGStyledElement {
 public:
     static PassRefPtr<SVGTitleElement> create(const QualifiedName&, Document*);
 
diff --git a/Source/core/svg/SVGTitleElement.idl b/Source/core/svg/SVGTitleElement.idl
index 48096eb..c3bb47c 100644
--- a/Source/core/svg/SVGTitleElement.idl
+++ b/Source/core/svg/SVGTitleElement.idl
@@ -23,7 +23,6 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGTitleElement : SVGStyledElement,
-                            SVGLangSpace {
+interface SVGTitleElement : SVGStyledElement {
 };
 
diff --git a/Source/core/svg/SVGTransform.h b/Source/core/svg/SVGTransform.h
index f236962..deb2ef8 100644
--- a/Source/core/svg/SVGTransform.h
+++ b/Source/core/svg/SVGTransform.h
@@ -23,6 +23,7 @@
 
 #include "core/platform/graphics/FloatPoint.h"
 #include "core/svg/SVGMatrix.h"
+#include "wtf/text/WTFString.h"
 
 namespace WebCore {
 
diff --git a/Source/core/svg/SVGTransformList.cpp b/Source/core/svg/SVGTransformList.cpp
index ff96c9d..1567a2c 100644
--- a/Source/core/svg/SVGTransformList.cpp
+++ b/Source/core/svg/SVGTransformList.cpp
@@ -75,9 +75,23 @@
 
 void SVGTransformList::parse(const String& transform)
 {
-    const UChar* start = transform.characters();
-    if (!SVGTransformable::parseTransformAttribute(*this, start, start + transform.length()))
+    if (transform.isEmpty()) {
+        // FIXME: The parseTransformAttribute function secretly calls clear()
+        // based on a |mode| parameter. We should study whether we should
+        // remove the |mode| parameter and force callers to call clear()
+        // themselves.
         clear();
+    } else if (transform.is8Bit()) {
+        const LChar* ptr = transform.characters8();
+        const LChar* end = ptr + transform.length();
+        if (!SVGTransformable::parseTransformAttribute(*this, ptr, end))
+            clear();
+    } else {
+        const UChar* ptr = transform.characters16();
+        const UChar* end = ptr + transform.length();
+        if (!SVGTransformable::parseTransformAttribute(*this, ptr, end))
+            clear();
+    }
 }
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGTransformable.cpp b/Source/core/svg/SVGTransformable.cpp
index a1b18a9..ca1f9dc 100644
--- a/Source/core/svg/SVGTransformable.cpp
+++ b/Source/core/svg/SVGTransformable.cpp
@@ -29,7 +29,8 @@
 
 namespace WebCore {
 
-static int parseTransformParamList(const UChar*& ptr, const UChar* end, float* values, int required, int optional)
+template<typename CharType>
+static int parseTransformParamList(const CharType*& ptr, const CharType* end, float* values, int required, int optional)
 {
     int optionalParams = 0, requiredParams = 0;
     
@@ -90,7 +91,8 @@
 {
 }
 
-bool SVGTransformable::parseTransformValue(unsigned type, const UChar*& ptr, const UChar* end, SVGTransform& transform)
+template<typename CharType>
+static bool parseTransformValueInternal(unsigned type, const CharType*& ptr, const CharType* end, SVGTransform& transform)
 {
     if (type == SVGTransform::SVG_TRANSFORM_UNKNOWN)
         return false;
@@ -133,32 +135,43 @@
     return true;
 }
 
-static const UChar skewXDesc[] =  {'s', 'k', 'e', 'w', 'X'};
-static const UChar skewYDesc[] =  {'s', 'k', 'e', 'w', 'Y'};
-static const UChar scaleDesc[] =  {'s', 'c', 'a', 'l', 'e'};
-static const UChar translateDesc[] =  {'t', 'r', 'a', 'n', 's', 'l', 'a', 't', 'e'};
-static const UChar rotateDesc[] =  {'r', 'o', 't', 'a', 't', 'e'};
-static const UChar matrixDesc[] =  {'m', 'a', 't', 'r', 'i', 'x'};
-
-static inline bool parseAndSkipType(const UChar*& currTransform, const UChar* end, unsigned short& type)
+bool SVGTransformable::parseTransformValue(unsigned type, const LChar*& ptr, const LChar* end, SVGTransform& transform)
 {
-    if (currTransform >= end)
+    return parseTransformValueInternal(type, ptr, end, transform);
+}
+
+bool SVGTransformable::parseTransformValue(unsigned type, const UChar*& ptr, const UChar* end, SVGTransform& transform)
+{
+    return parseTransformValueInternal(type, ptr, end, transform);
+}
+
+static const LChar skewXDesc[] =  {'s', 'k', 'e', 'w', 'X'};
+static const LChar skewYDesc[] =  {'s', 'k', 'e', 'w', 'Y'};
+static const LChar scaleDesc[] =  {'s', 'c', 'a', 'l', 'e'};
+static const LChar translateDesc[] =  {'t', 'r', 'a', 'n', 's', 'l', 'a', 't', 'e'};
+static const LChar rotateDesc[] =  {'r', 'o', 't', 'a', 't', 'e'};
+static const LChar matrixDesc[] =  {'m', 'a', 't', 'r', 'i', 'x'};
+
+template<typename CharType>
+static inline bool parseAndSkipType(const CharType*& ptr, const CharType* end, unsigned short& type)
+{
+    if (ptr >= end)
         return false;
 
-    if (*currTransform == 's') {
-        if (skipString(currTransform, end, skewXDesc, WTF_ARRAY_LENGTH(skewXDesc)))
+    if (*ptr == 's') {
+        if (skipString(ptr, end, skewXDesc, WTF_ARRAY_LENGTH(skewXDesc)))
             type = SVGTransform::SVG_TRANSFORM_SKEWX;
-        else if (skipString(currTransform, end, skewYDesc, WTF_ARRAY_LENGTH(skewYDesc)))
+        else if (skipString(ptr, end, skewYDesc, WTF_ARRAY_LENGTH(skewYDesc)))
             type = SVGTransform::SVG_TRANSFORM_SKEWY;
-        else if (skipString(currTransform, end, scaleDesc, WTF_ARRAY_LENGTH(scaleDesc)))
+        else if (skipString(ptr, end, scaleDesc, WTF_ARRAY_LENGTH(scaleDesc)))
             type = SVGTransform::SVG_TRANSFORM_SCALE;
         else
             return false;
-    } else if (skipString(currTransform, end, translateDesc, WTF_ARRAY_LENGTH(translateDesc)))
+    } else if (skipString(ptr, end, translateDesc, WTF_ARRAY_LENGTH(translateDesc)))
         type = SVGTransform::SVG_TRANSFORM_TRANSLATE;
-    else if (skipString(currTransform, end, rotateDesc, WTF_ARRAY_LENGTH(rotateDesc)))
+    else if (skipString(ptr, end, rotateDesc, WTF_ARRAY_LENGTH(rotateDesc)))
         type = SVGTransform::SVG_TRANSFORM_ROTATE;
-    else if (skipString(currTransform, end, matrixDesc, WTF_ARRAY_LENGTH(matrixDesc)))
+    else if (skipString(ptr, end, matrixDesc, WTF_ARRAY_LENGTH(matrixDesc)))
         type = SVGTransform::SVG_TRANSFORM_MATRIX;
     else
         return false;
@@ -166,42 +179,62 @@
     return true;
 }
 
-SVGTransform::SVGTransformType SVGTransformable::parseTransformType(const String& typeString)
+SVGTransform::SVGTransformType SVGTransformable::parseTransformType(const String& string)
 {
+    if (string.isEmpty())
+        return SVGTransform::SVG_TRANSFORM_UNKNOWN;
     unsigned short type = SVGTransform::SVG_TRANSFORM_UNKNOWN;
-    const UChar* characters = typeString.characters();
-    parseAndSkipType(characters, characters + typeString.length(), type);
+    if (string.is8Bit()) {
+        const LChar* ptr = string.characters8();
+        const LChar* end = ptr + string.length();
+        parseAndSkipType(ptr, end, type);
+    } else {
+        const UChar* ptr = string.characters16();
+        const UChar* end = ptr + string.length();
+        parseAndSkipType(ptr, end, type);
+    }
     return static_cast<SVGTransform::SVGTransformType>(type);
 }
 
-bool SVGTransformable::parseTransformAttribute(SVGTransformList& list, const UChar*& currTransform, const UChar* end, TransformParsingMode mode)
+template<typename CharType>
+bool SVGTransformable::parseTransformAttributeInternal(SVGTransformList& list, const CharType*& ptr, const CharType* end, TransformParsingMode mode)
 {
     if (mode == ClearList)
         list.clear();
 
     bool delimParsed = false;
-    while (currTransform < end) {
+    while (ptr < end) {
         delimParsed = false;
         unsigned short type = SVGTransform::SVG_TRANSFORM_UNKNOWN;
-        skipOptionalSVGSpaces(currTransform, end);
+        skipOptionalSVGSpaces(ptr, end);
 
-        if (!parseAndSkipType(currTransform, end, type))
+        if (!parseAndSkipType(ptr, end, type))
             return false;
 
         SVGTransform transform;
-        if (!parseTransformValue(type, currTransform, end, transform))
+        if (!parseTransformValue(type, ptr, end, transform))
             return false;
 
         list.append(transform);
-        skipOptionalSVGSpaces(currTransform, end);
-        if (currTransform < end && *currTransform == ',') {
+        skipOptionalSVGSpaces(ptr, end);
+        if (ptr < end && *ptr == ',') {
             delimParsed = true;
-            ++currTransform;
+            ++ptr;
         }
-        skipOptionalSVGSpaces(currTransform, end);
+        skipOptionalSVGSpaces(ptr, end);
     }
 
     return !delimParsed;
 }
 
+bool SVGTransformable::parseTransformAttribute(SVGTransformList& list, const LChar*& ptr, const LChar* end, TransformParsingMode mode)
+{
+    return parseTransformAttributeInternal(list, ptr, end, mode);
+}
+
+bool SVGTransformable::parseTransformAttribute(SVGTransformList& list, const UChar*& ptr, const UChar* end, TransformParsingMode mode)
+{
+    return parseTransformAttributeInternal(list, ptr, end, mode);
+}
+
 }
diff --git a/Source/core/svg/SVGTransformable.h b/Source/core/svg/SVGTransformable.h
index 1e74b30..b7c6f3d 100644
--- a/Source/core/svg/SVGTransformable.h
+++ b/Source/core/svg/SVGTransformable.h
@@ -39,12 +39,20 @@
 
     virtual ~SVGTransformable();
 
-    static bool parseTransformAttribute(SVGTransformList&, const UChar*& ptr, const UChar* end, TransformParsingMode mode = ClearList);
+    static bool parseTransformAttribute(SVGTransformList&, const LChar*& ptr, const LChar* end, TransformParsingMode = ClearList);
+    static bool parseTransformAttribute(SVGTransformList&, const UChar*& ptr, const UChar* end, TransformParsingMode = ClearList);
+
+    static bool parseTransformValue(unsigned type, const LChar*& ptr, const LChar* end, SVGTransform&);
     static bool parseTransformValue(unsigned type, const UChar*& ptr, const UChar* end, SVGTransform&);
+
     static SVGTransform::SVGTransformType parseTransformType(const String&);
 
     virtual AffineTransform localCoordinateSpaceTransform(SVGLocatable::CTMScope) const { return animatedLocalTransform(); }
     virtual AffineTransform animatedLocalTransform() const = 0;
+
+private:
+    template<typename CharType>
+    static bool parseTransformAttributeInternal(SVGTransformList&, const CharType*& ptr, const CharType* end, TransformParsingMode);
 };
 
 } // namespace WebCore
diff --git a/Source/core/svg/SVGTransformable.idl b/Source/core/svg/SVGTransformable.idl
deleted file mode 100644
index f7e4525..0000000
--- a/Source/core/svg/SVGTransformable.idl
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * Copyright (C) 2006 Samuel Weinig <sam.weinig@gmail.com>
- * Copyright (C) 2006 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- *    notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- *    notice, this list of conditions and the following disclaimer in the
- *    documentation and/or other materials provided with the distribution.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
- * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
- */
-
-interface SVGTransformable : SVGLocatable {
-    readonly attribute SVGAnimatedTransformList transform;
-};
-
diff --git a/Source/core/svg/SVGURIReference.idl b/Source/core/svg/SVGURIReference.idl
index 850048f..06dcca9 100644
--- a/Source/core/svg/SVGURIReference.idl
+++ b/Source/core/svg/SVGURIReference.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    DoNotGenerateToV8
+    NoInterfaceObject
 ] interface SVGURIReference {
     readonly attribute SVGAnimatedString href;
 };
diff --git a/Source/core/svg/SVGUseElement.cpp b/Source/core/svg/SVGUseElement.cpp
index caf330c..418d1b7 100644
--- a/Source/core/svg/SVGUseElement.cpp
+++ b/Source/core/svg/SVGUseElement.cpp
@@ -67,12 +67,11 @@
     REGISTER_LOCAL_ANIMATED_PROPERTY(height)
     REGISTER_LOCAL_ANIMATED_PROPERTY(href)
     REGISTER_LOCAL_ANIMATED_PROPERTY(externalResourcesRequired)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGStyledTransformableElement)
-    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGTests)
+    REGISTER_PARENT_ANIMATED_PROPERTIES(SVGGraphicsElement)
 END_REGISTER_ANIMATED_PROPERTIES
 
 inline SVGUseElement::SVGUseElement(const QualifiedName& tagName, Document* document, bool wasInsertedByParser)
-    : SVGStyledTransformableElement(tagName, document)
+    : SVGGraphicsElement(tagName, document)
     , m_x(LengthModeWidth)
     , m_y(LengthModeHeight)
     , m_width(LengthModeWidth)
@@ -125,7 +124,6 @@
 {
     DEFINE_STATIC_LOCAL(HashSet<QualifiedName>, supportedAttributes, ());
     if (supportedAttributes.isEmpty()) {
-        SVGTests::addSupportedAttributes(supportedAttributes);
         SVGLangSpace::addSupportedAttributes(supportedAttributes);
         SVGExternalResourcesRequired::addSupportedAttributes(supportedAttributes);
         SVGURIReference::addSupportedAttributes(supportedAttributes);
@@ -134,7 +132,7 @@
         supportedAttributes.add(SVGNames::widthAttr);
         supportedAttributes.add(SVGNames::heightAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGUseElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
@@ -142,7 +140,7 @@
     SVGParsingError parseError = NoError;
 
     if (!isSupportedAttribute(name))
-        SVGStyledTransformableElement::parseAttribute(name, value);
+        SVGGraphicsElement::parseAttribute(name, value);
     else if (name == SVGNames::xAttr)
         setXBaseValue(SVGLength::construct(LengthModeWidth, value, parseError));
     else if (name == SVGNames::yAttr)
@@ -151,8 +149,7 @@
         setWidthBaseValue(SVGLength::construct(LengthModeWidth, value, parseError, ForbidNegativeLengths));
     else if (name == SVGNames::heightAttr)
         setHeightBaseValue(SVGLength::construct(LengthModeHeight, value, parseError, ForbidNegativeLengths));
-    else if (SVGTests::parseAttribute(name, value)
-             || SVGLangSpace::parseAttribute(name, value)
+    else if (SVGLangSpace::parseAttribute(name, value)
              || SVGExternalResourcesRequired::parseAttribute(name, value)
              || SVGURIReference::parseAttribute(name, value)) {
     } else
@@ -171,7 +168,7 @@
 Node::InsertionNotificationRequest SVGUseElement::insertedInto(ContainerNode* rootParent)
 {
     // This functions exists to assure assumptions made in the code regarding SVGElementInstance creation/destruction are satisfied.
-    SVGStyledTransformableElement::insertedInto(rootParent);
+    SVGGraphicsElement::insertedInto(rootParent);
     if (!rootParent->inDocument())
         return InsertionDone;
     ASSERT(!m_targetElementInstance || !isWellFormedDocument(document()));
@@ -184,7 +181,7 @@
 
 void SVGUseElement::removedFrom(ContainerNode* rootParent)
 {
-    SVGStyledTransformableElement::removedFrom(rootParent);
+    SVGGraphicsElement::removedFrom(rootParent);
     if (rootParent->inDocument())
         clearResourceReferences();
 }
@@ -211,7 +208,7 @@
 void SVGUseElement::svgAttributeChanged(const QualifiedName& attrName)
 {
     if (!isSupportedAttribute(attrName)) {
-        SVGStyledTransformableElement::svgAttributeChanged(attrName);
+        SVGGraphicsElement::svgAttributeChanged(attrName);
         return;
     }
 
@@ -228,9 +225,6 @@
         return;
     }
 
-    if (SVGTests::handleAttributeChange(this, attrName))
-        return;
-
     if (SVGExternalResourcesRequired::handleAttributeChange(this, attrName))
         return;
 
@@ -362,7 +356,7 @@
         allowedElementTags.add(SVGNames::tspanTag);
         allowedElementTags.add(SVGNames::useTag);
     }
-    return !allowedElementTags.contains<QualifiedName, SVGAttributeHashTranslator>(element->tagQName());
+    return !allowedElementTags.contains<SVGAttributeHashTranslator>(element->tagQName());
 }
 
 static bool subtreeContainsDisallowedElement(Node* start)
@@ -525,9 +519,9 @@
 #endif
 }
 
-RenderObject* SVGUseElement::createRenderer(RenderArena* arena, RenderStyle*)
+RenderObject* SVGUseElement::createRenderer(RenderStyle*)
 {
-    return new (arena) RenderSVGTransformableContainer(this);
+    return new (document()->renderArena()) RenderSVGTransformableContainer(this);
 }
 
 static bool isDirectReference(const Node* node)
@@ -549,12 +543,12 @@
     if (!n)
         return;
 
-    if (n->isSVGElement() && toSVGElement(n)->isStyledTransformable()) {
+    if (n->isSVGElement() && toSVGElement(n)->isSVGGraphicsElement()) {
         if (!isDirectReference(n))
             // Spec: Indirect references are an error (14.3.5)
             document()->accessSVGExtensions()->reportError("Not allowed to use indirect reference in <clip-path>");
         else {
-            toSVGStyledTransformableElement(n)->toClipPath(path);
+            toSVGGraphicsElement(n)->toClipPath(path);
             // FIXME: Avoid manual resolution of x/y here. Its potentially harmful.
             SVGLengthContext lengthContext(this);
             path.translate(FloatSize(x().value(lengthContext), y().value(lengthContext)));
@@ -974,7 +968,7 @@
 
 void SVGUseElement::finishParsingChildren()
 {
-    SVGStyledTransformableElement::finishParsingChildren();
+    SVGGraphicsElement::finishParsingChildren();
     SVGExternalResourcesRequired::finishParsingChildren();
     if (m_wasInsertedByParser) {
         buildPendingResource();
diff --git a/Source/core/svg/SVGUseElement.h b/Source/core/svg/SVGUseElement.h
index ba2bf08..b659fac 100644
--- a/Source/core/svg/SVGUseElement.h
+++ b/Source/core/svg/SVGUseElement.h
@@ -25,9 +25,7 @@
 #include "core/svg/SVGAnimatedBoolean.h"
 #include "core/svg/SVGAnimatedLength.h"
 #include "core/svg/SVGExternalResourcesRequired.h"
-#include "core/svg/SVGLangSpace.h"
-#include "core/svg/SVGStyledTransformableElement.h"
-#include "core/svg/SVGTests.h"
+#include "core/svg/SVGGraphicsElement.h"
 #include "core/svg/SVGURIReference.h"
 
 namespace WebCore {
@@ -35,9 +33,7 @@
 class CachedDocument;
 class SVGElementInstance;
 
-class SVGUseElement FINAL : public SVGStyledTransformableElement,
-                            public SVGTests,
-                            public SVGLangSpace,
+class SVGUseElement FINAL : public SVGGraphicsElement,
                             public SVGExternalResourcesRequired,
                             public SVGURIReference,
                             public CachedDocumentClient {
@@ -69,7 +65,7 @@
 
     virtual void willRecalcStyle(StyleChange) OVERRIDE;
 
-    virtual RenderObject* createRenderer(RenderArena*, RenderStyle*);
+    virtual RenderObject* createRenderer(RenderStyle*);
     virtual void toClipPath(Path&);
 
     void clearResourceReferences();
@@ -114,11 +110,6 @@
     Document* referencedDocument() const;
     void setCachedDocument(CachedResourceHandle<CachedDocument>);
 
-    // SVGTests
-    virtual void synchronizeRequiredFeatures() { SVGTests::synchronizeRequiredFeatures(this); }
-    virtual void synchronizeRequiredExtensions() { SVGTests::synchronizeRequiredExtensions(this); }
-    virtual void synchronizeSystemLanguage() { SVGTests::synchronizeSystemLanguage(this); }
-
     // SVGExternalResourcesRequired
     virtual void setHaveFiredLoadEvent(bool haveFiredLoadEvent) { m_haveFiredLoadEvent = haveFiredLoadEvent; }
     virtual bool isParserInserted() const { return m_wasInsertedByParser; }
diff --git a/Source/core/svg/SVGUseElement.idl b/Source/core/svg/SVGUseElement.idl
index 8ee8b4a..e348103 100644
--- a/Source/core/svg/SVGUseElement.idl
+++ b/Source/core/svg/SVGUseElement.idl
@@ -23,12 +23,7 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGUseElement : SVGStyledElement,
-                          SVGURIReference,
-                          SVGTests,
-                          SVGLangSpace,
-                          SVGExternalResourcesRequired,
-                          SVGTransformable {
+interface SVGUseElement : SVGGraphicsElement {
     readonly attribute SVGAnimatedLength   x;
     readonly attribute SVGAnimatedLength   y;
     readonly attribute SVGAnimatedLength   width;
@@ -38,3 +33,7 @@
     readonly attribute SVGElementInstance animatedInstanceRoot;
 };
 
+SVGUseElement implements SVGExternalResourcesRequired;
+SVGUseElement implements SVGTests;
+SVGUseElement implements SVGURIReference;
+
diff --git a/Source/core/svg/SVGViewElement.cpp b/Source/core/svg/SVGViewElement.cpp
index 1adb609..cc4750f 100644
--- a/Source/core/svg/SVGViewElement.cpp
+++ b/Source/core/svg/SVGViewElement.cpp
@@ -65,7 +65,7 @@
         SVGZoomAndPan::addSupportedAttributes(supportedAttributes);
         supportedAttributes.add(SVGNames::viewTargetAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGViewElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/SVGViewElement.idl b/Source/core/svg/SVGViewElement.idl
index 4d43028..296c410 100644
--- a/Source/core/svg/SVGViewElement.idl
+++ b/Source/core/svg/SVGViewElement.idl
@@ -23,10 +23,11 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-interface SVGViewElement : SVGElement,
-                           SVGExternalResourcesRequired,
-                           SVGFitToViewBox,
-                           SVGZoomAndPan {
+interface SVGViewElement : SVGElement {
     readonly attribute SVGStringList viewTarget;
 };
 
+SVGViewElement implements SVGExternalResourcesRequired;
+SVGViewElement implements SVGFitToViewBox;
+SVGViewElement implements SVGZoomAndPan;
+
diff --git a/Source/core/svg/SVGViewSpec.cpp b/Source/core/svg/SVGViewSpec.cpp
index 023e693..cbc3cf1 100644
--- a/Source/core/svg/SVGViewSpec.cpp
+++ b/Source/core/svg/SVGViewSpec.cpp
@@ -200,98 +200,107 @@
     m_viewTargetString = emptyString();
 }
 
-static const UChar svgViewSpec[] = {'s', 'v', 'g', 'V', 'i', 'e', 'w'};
-static const UChar viewBoxSpec[] = {'v', 'i', 'e', 'w', 'B', 'o', 'x'};
-static const UChar preserveAspectRatioSpec[] = {'p', 'r', 'e', 's', 'e', 'r', 'v', 'e', 'A', 's', 'p', 'e', 'c', 't', 'R', 'a', 't', 'i', 'o'};
-static const UChar transformSpec[] = {'t', 'r', 'a', 'n', 's', 'f', 'o', 'r', 'm'};
-static const UChar zoomAndPanSpec[] = {'z', 'o', 'o', 'm', 'A', 'n', 'd', 'P', 'a', 'n'};
-static const UChar viewTargetSpec[] =  {'v', 'i', 'e', 'w', 'T', 'a', 'r', 'g', 'e', 't'};
+static const LChar svgViewSpec[] = {'s', 'v', 'g', 'V', 'i', 'e', 'w'};
+static const LChar viewBoxSpec[] = {'v', 'i', 'e', 'w', 'B', 'o', 'x'};
+static const LChar preserveAspectRatioSpec[] = {'p', 'r', 'e', 's', 'e', 'r', 'v', 'e', 'A', 's', 'p', 'e', 'c', 't', 'R', 'a', 't', 'i', 'o'};
+static const LChar transformSpec[] = {'t', 'r', 'a', 'n', 's', 'f', 'o', 'r', 'm'};
+static const LChar zoomAndPanSpec[] = {'z', 'o', 'o', 'm', 'A', 'n', 'd', 'P', 'a', 'n'};
+static const LChar viewTargetSpec[] =  {'v', 'i', 'e', 'w', 'T', 'a', 'r', 'g', 'e', 't'};
 
-bool SVGViewSpec::parseViewSpec(const String& viewSpec)
+template<typename CharType>
+bool SVGViewSpec::parseViewSpecInternal(const CharType* ptr, const CharType* end)
 {
-    const UChar* currViewSpec = viewSpec.characters();
-    const UChar* end = currViewSpec + viewSpec.length();
-
-    if (currViewSpec >= end || !m_contextElement)
+    if (!skipString(ptr, end, svgViewSpec, WTF_ARRAY_LENGTH(svgViewSpec)))
         return false;
 
-    if (!skipString(currViewSpec, end, svgViewSpec, WTF_ARRAY_LENGTH(svgViewSpec)))
+    if (ptr >= end || *ptr != '(')
         return false;
+    ptr++;
 
-    if (currViewSpec >= end || *currViewSpec != '(')
-        return false;
-    currViewSpec++;
-
-    while (currViewSpec < end && *currViewSpec != ')') {
-        if (*currViewSpec == 'v') {
-            if (skipString(currViewSpec, end, viewBoxSpec, WTF_ARRAY_LENGTH(viewBoxSpec))) {
-                if (currViewSpec >= end || *currViewSpec != '(')
+    while (ptr < end && *ptr != ')') {
+        if (*ptr == 'v') {
+            if (skipString(ptr, end, viewBoxSpec, WTF_ARRAY_LENGTH(viewBoxSpec))) {
+                if (ptr >= end || *ptr != '(')
                     return false;
-                currViewSpec++;
+                ptr++;
                 FloatRect viewBox;
-                if (!SVGFitToViewBox::parseViewBox(m_contextElement->document(), currViewSpec, end, viewBox, false))
+                if (!SVGFitToViewBox::parseViewBox(m_contextElement->document(), ptr, end, viewBox, false))
                     return false;
                 setViewBoxBaseValue(viewBox);
-                if (currViewSpec >= end || *currViewSpec != ')')
+                if (ptr >= end || *ptr != ')')
                     return false;
-                currViewSpec++;
-            } else if (skipString(currViewSpec, end, viewTargetSpec, WTF_ARRAY_LENGTH(viewTargetSpec))) {
-                if (currViewSpec >= end || *currViewSpec != '(')
+                ptr++;
+            } else if (skipString(ptr, end, viewTargetSpec, WTF_ARRAY_LENGTH(viewTargetSpec))) {
+                if (ptr >= end || *ptr != '(')
                     return false;
-                const UChar* viewTargetStart = ++currViewSpec;
-                while (currViewSpec < end && *currViewSpec != ')')
-                    currViewSpec++;
-                if (currViewSpec >= end)
+                const CharType* viewTargetStart = ++ptr;
+                while (ptr < end && *ptr != ')')
+                    ptr++;
+                if (ptr >= end)
                     return false;
-                setViewTargetString(String(viewTargetStart, currViewSpec - viewTargetStart));
-                currViewSpec++;
+                setViewTargetString(String(viewTargetStart, ptr - viewTargetStart));
+                ptr++;
             } else
                 return false;
-        } else if (*currViewSpec == 'z') {
-            if (!skipString(currViewSpec, end, zoomAndPanSpec, WTF_ARRAY_LENGTH(zoomAndPanSpec)))
+        } else if (*ptr == 'z') {
+            if (!skipString(ptr, end, zoomAndPanSpec, WTF_ARRAY_LENGTH(zoomAndPanSpec)))
                 return false;
-            if (currViewSpec >= end || *currViewSpec != '(')
+            if (ptr >= end || *ptr != '(')
                 return false;
-            currViewSpec++;
-            if (!parseZoomAndPan(currViewSpec, end, m_zoomAndPan))
+            ptr++;
+            if (!parseZoomAndPan(ptr, end, m_zoomAndPan))
                 return false;
-            if (currViewSpec >= end || *currViewSpec != ')')
+            if (ptr >= end || *ptr != ')')
                 return false;
-            currViewSpec++;
-        } else if (*currViewSpec == 'p') {
-            if (!skipString(currViewSpec, end, preserveAspectRatioSpec, WTF_ARRAY_LENGTH(preserveAspectRatioSpec)))
+            ptr++;
+        } else if (*ptr == 'p') {
+            if (!skipString(ptr, end, preserveAspectRatioSpec, WTF_ARRAY_LENGTH(preserveAspectRatioSpec)))
                 return false;
-            if (currViewSpec >= end || *currViewSpec != '(')
+            if (ptr >= end || *ptr != '(')
                 return false;
-            currViewSpec++;
+            ptr++;
             SVGPreserveAspectRatio preserveAspectRatio;
-            if (!preserveAspectRatio.parse(currViewSpec, end, false))
+            if (!preserveAspectRatio.parse(ptr, end, false))
                 return false;
             setPreserveAspectRatioBaseValue(preserveAspectRatio);
-            if (currViewSpec >= end || *currViewSpec != ')')
+            if (ptr >= end || *ptr != ')')
                 return false;
-            currViewSpec++;
-        } else if (*currViewSpec == 't') {
-            if (!skipString(currViewSpec, end, transformSpec, WTF_ARRAY_LENGTH(transformSpec)))
+            ptr++;
+        } else if (*ptr == 't') {
+            if (!skipString(ptr, end, transformSpec, WTF_ARRAY_LENGTH(transformSpec)))
                 return false;
-            if (currViewSpec >= end || *currViewSpec != '(')
+            if (ptr >= end || *ptr != '(')
                 return false;
-            currViewSpec++;
-            SVGTransformable::parseTransformAttribute(m_transform, currViewSpec, end, SVGTransformable::DoNotClearList);
-            if (currViewSpec >= end || *currViewSpec != ')')
+            ptr++;
+            SVGTransformable::parseTransformAttribute(m_transform, ptr, end, SVGTransformable::DoNotClearList);
+            if (ptr >= end || *ptr != ')')
                 return false;
-            currViewSpec++;
+            ptr++;
         } else
             return false;
 
-        if (currViewSpec < end && *currViewSpec == ';')
-            currViewSpec++;
+        if (ptr < end && *ptr == ';')
+            ptr++;
     }
     
-    if (currViewSpec >= end || *currViewSpec != ')')
+    if (ptr >= end || *ptr != ')')
         return false;
 
     return true;
 }
 
+bool SVGViewSpec::parseViewSpec(const String& spec)
+{
+    if (spec.isEmpty() || !m_contextElement)
+        return false;
+    if (spec.is8Bit()) {
+        const LChar* ptr = spec.characters8();
+        const LChar* end = ptr + spec.length();
+        return parseViewSpecInternal(ptr, end);
+    }
+    const UChar* ptr = spec.characters16();
+    const UChar* end = ptr + spec.length();
+    return parseViewSpecInternal(ptr, end);
+}
+
 }
diff --git a/Source/core/svg/SVGViewSpec.h b/Source/core/svg/SVGViewSpec.h
index 89d2502..06f6d31 100644
--- a/Source/core/svg/SVGViewSpec.h
+++ b/Source/core/svg/SVGViewSpec.h
@@ -83,7 +83,7 @@
     void setPreserveAspectRatioBaseValue(const SVGPreserveAspectRatio& preserveAspectRatio) { m_preserveAspectRatio = preserveAspectRatio; }
 
 private:
-    SVGViewSpec(SVGElement*);
+    explicit SVGViewSpec(SVGElement*);
 
     static const SVGPropertyInfo* transformPropertyInfo();
     static const SVGPropertyInfo* viewBoxPropertyInfo();
@@ -97,6 +97,9 @@
     static PassRefPtr<SVGAnimatedProperty> lookupOrCreateViewBoxWrapper(SVGViewSpec* contextElement);
     static PassRefPtr<SVGAnimatedProperty> lookupOrCreatePreserveAspectRatioWrapper(SVGViewSpec* contextElement);
 
+    template<typename CharType>
+    bool parseViewSpecInternal(const CharType* ptr, const CharType* end);
+
     SVGElement* m_contextElement;
     SVGZoomAndPanType m_zoomAndPan;
 
diff --git a/Source/core/svg/SVGViewSpec.idl b/Source/core/svg/SVGViewSpec.idl
index 55b1489..40ac152 100644
--- a/Source/core/svg/SVGViewSpec.idl
+++ b/Source/core/svg/SVGViewSpec.idl
@@ -23,8 +23,6 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
  */
 
-// SVGViewSpec intentionally doesn't inherit from SVGZoomAndPan & SVGFitToViewBox on the IDLs.
-// It would require that any of those classes would be RefCounted, and we want to avoid that.
 interface SVGViewSpec {
       readonly attribute SVGTransformList transform;
       readonly attribute SVGElement viewTarget;
@@ -35,9 +33,7 @@
 
       // SVGZoomAndPan
       [SetterRaisesException] attribute unsigned short zoomAndPan;
-
-      // SVGFitToViewBox
-      readonly attribute SVGAnimatedRect viewBox;
-      readonly attribute SVGAnimatedPreserveAspectRatio preserveAspectRatio;
 };
 
+SVGViewSpec implements SVGFitToViewBox;
+
diff --git a/Source/core/svg/SVGZoomAndPan.cpp b/Source/core/svg/SVGZoomAndPan.cpp
index 6003ec9..450152c 100644
--- a/Source/core/svg/SVGZoomAndPan.cpp
+++ b/Source/core/svg/SVGZoomAndPan.cpp
@@ -36,10 +36,11 @@
     supportedAttributes.add(SVGNames::zoomAndPanAttr);
 }
 
-static const UChar disable[] =  {'d', 'i', 's', 'a', 'b', 'l', 'e'};
-static const UChar magnify[] =  {'m', 'a', 'g', 'n', 'i', 'f', 'y'};
+static const LChar disable[] =  {'d', 'i', 's', 'a', 'b', 'l', 'e'};
+static const LChar magnify[] =  {'m', 'a', 'g', 'n', 'i', 'f', 'y'};
 
-bool SVGZoomAndPan::parseZoomAndPan(const UChar*& start, const UChar* end, SVGZoomAndPanType& zoomAndPan)
+template<typename CharType>
+static bool parseZoomAndPanInternal(const CharType*& start, const CharType* end, SVGZoomAndPanType& zoomAndPan)
 {
     if (skipString(start, end, disable, WTF_ARRAY_LENGTH(disable))) {
         zoomAndPan = SVGZoomAndPanDisable;
@@ -52,6 +53,16 @@
     return false;
 }
 
+bool SVGZoomAndPan::parseZoomAndPan(const LChar*& start, const LChar* end, SVGZoomAndPanType& zoomAndPan)
+{
+    return parseZoomAndPanInternal(start, end, zoomAndPan);
+}
+
+bool SVGZoomAndPan::parseZoomAndPan(const UChar*& start, const UChar* end, SVGZoomAndPanType& zoomAndPan)
+{
+    return parseZoomAndPanInternal(start, end, zoomAndPan);
+}
+
 NO_RETURN_DUE_TO_ASSERT void SVGZoomAndPan::ref()
 {
     ASSERT_NOT_REACHED();
diff --git a/Source/core/svg/SVGZoomAndPan.h b/Source/core/svg/SVGZoomAndPan.h
index 56f7e63..061b9fc 100644
--- a/Source/core/svg/SVGZoomAndPan.h
+++ b/Source/core/svg/SVGZoomAndPan.h
@@ -55,6 +55,7 @@
         return static_cast<SVGZoomAndPanType>(number);
     }
 
+    static bool parseZoomAndPan(const LChar*& start, const LChar* end, SVGZoomAndPanType&);
     static bool parseZoomAndPan(const UChar*& start, const UChar* end, SVGZoomAndPanType&);
 
     template<class SVGElementTarget>
diff --git a/Source/core/svg/SVGZoomAndPan.idl b/Source/core/svg/SVGZoomAndPan.idl
index de112e2..edc9f8e 100644
--- a/Source/core/svg/SVGZoomAndPan.idl
+++ b/Source/core/svg/SVGZoomAndPan.idl
@@ -25,7 +25,7 @@
  */
 
 [
-    DoNotGenerateToV8
+    NoInterfaceObject
 ] interface SVGZoomAndPan {
     const unsigned short SVG_ZOOMANDPAN_UNKNOWN = 0;
     const unsigned short SVG_ZOOMANDPAN_DISABLE = 1;
diff --git a/Source/core/svg/animation/SVGSMILElement.cpp b/Source/core/svg/animation/SVGSMILElement.cpp
index 80826ce..b5fdb07 100644
--- a/Source/core/svg/animation/SVGSMILElement.cpp
+++ b/Source/core/svg/animation/SVGSMILElement.cpp
@@ -450,7 +450,7 @@
         supportedAttributes.add(SVGNames::attributeNameAttr);
         supportedAttributes.add(XLinkNames::hrefAttr);
     }
-    return supportedAttributes.contains<QualifiedName, SVGAttributeHashTranslator>(attrName);
+    return supportedAttributes.contains<SVGAttributeHashTranslator>(attrName);
 }
 
 void SVGSMILElement::parseAttribute(const QualifiedName& name, const AtomicString& value)
diff --git a/Source/core/svg/graphics/SVGImage.cpp b/Source/core/svg/graphics/SVGImage.cpp
index 333ae76..c8231a1 100644
--- a/Source/core/svg/graphics/SVGImage.cpp
+++ b/Source/core/svg/graphics/SVGImage.cpp
@@ -41,6 +41,7 @@
 #include "core/svg/SVGDocument.h"
 #include "core/svg/SVGSVGElement.h"
 #include "core/svg/graphics/SVGImageChromeClient.h"
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
@@ -142,9 +143,7 @@
     setImageObserver(observer);
 }
 
-// Passes ownership of the native image to the caller so PassNativeImagePtr needs
-// to be a smart pointer type.
-PassNativeImagePtr SVGImage::nativeImageForCurrentFrame()
+PassRefPtr<NativeImageSkia> SVGImage::nativeImageForCurrentFrame()
 {
     if (!m_page)
         return 0;
@@ -190,7 +189,7 @@
     image->drawPattern(context, scaledSrcRect, scaleWithoutCTM, phase, compositeOp, dstRect);
 }
 
-void SVGImage::draw(GraphicsContext* context, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp, BlendMode)
+void SVGImage::draw(GraphicsContext* context, const FloatRect& dstRect, const FloatRect& srcRect, CompositeOperator compositeOp, BlendMode blendMode)
 {
     if (!m_page)
         return;
@@ -198,7 +197,7 @@
     FrameView* view = frameView();
 
     GraphicsContextStateSaver stateSaver(*context);
-    context->setCompositeOperation(compositeOp);
+    context->setCompositeOperation(compositeOp, blendMode);
     context->clip(enclosingIntRect(dstRect));
     if (compositeOp != CompositeSourceOver)
         context->beginTransparencyLayer(1);
@@ -218,7 +217,7 @@
     if (view->needsLayout())
         view->layout();
 
-    view->paint(context, IntRect(0, 0, view->width(), view->height()));
+    view->paint(context, enclosingIntRect(srcRect));
 
     if (compositeOp != CompositeSourceOver)
         context->endTransparencyLayer();
@@ -354,11 +353,9 @@
         frame->view()->setTransparent(true); // SVG Images are transparent.
 
         ASSERT(loader->activeDocumentLoader()); // DocumentLoader should have been created by frame->init().
-        loader->activeDocumentLoader()->writer()->setMIMEType("image/svg+xml");
-        loader->activeDocumentLoader()->writer()->begin(KURL()); // create the empty document
-        loader->activeDocumentLoader()->writer()->addData(data()->data(), data()->size());
-        loader->activeDocumentLoader()->writer()->end();
-
+        DocumentWriter* writer = loader->activeDocumentLoader()->beginWriting("image/svg+xml", "UTF-8");
+        writer->addData(data()->data(), data()->size());
+        loader->activeDocumentLoader()->endWriting(writer);
         // Set the intrinsic size before a container size is available.
         m_intrinsicSize = containerSize();
     }
diff --git a/Source/core/svg/graphics/SVGImage.h b/Source/core/svg/graphics/SVGImage.h
index b195976..e8c4918 100644
--- a/Source/core/svg/graphics/SVGImage.h
+++ b/Source/core/svg/graphics/SVGImage.h
@@ -60,7 +60,7 @@
 
     virtual void reportMemoryUsage(MemoryObjectInfo*) const OVERRIDE;
 
-    virtual PassNativeImagePtr nativeImageForCurrentFrame() OVERRIDE;
+    virtual PassRefPtr<NativeImageSkia> nativeImageForCurrentFrame() OVERRIDE;
 
 private:
     friend class SVGImageChromeClient;
diff --git a/Source/core/svg/graphics/SVGImageForContainer.cpp b/Source/core/svg/graphics/SVGImageForContainer.cpp
index 56531a5..0b21d90 100644
--- a/Source/core/svg/graphics/SVGImageForContainer.cpp
+++ b/Source/core/svg/graphics/SVGImageForContainer.cpp
@@ -24,6 +24,7 @@
 #include "core/platform/graphics/FloatSize.h"
 #include "core/platform/graphics/Image.h"
 #include "core/svg/graphics/SVGImage.h"
+#include "wtf/PassRefPtr.h"
 
 namespace WebCore {
 
@@ -46,7 +47,7 @@
     m_image->drawPatternForContainer(context, m_containerSize, m_zoom, srcRect, scale, phase, compositeOp, dstRect);
 }
 
-PassNativeImagePtr SVGImageForContainer::nativeImageForCurrentFrame()
+PassRefPtr<NativeImageSkia> SVGImageForContainer::nativeImageForCurrentFrame()
 {
     return m_image->nativeImageForCurrentFrame();
 }
diff --git a/Source/core/svg/graphics/SVGImageForContainer.h b/Source/core/svg/graphics/SVGImageForContainer.h
index 164422c..f56e39f 100644
--- a/Source/core/svg/graphics/SVGImageForContainer.h
+++ b/Source/core/svg/graphics/SVGImageForContainer.h
@@ -59,7 +59,7 @@
     // FIXME: Implement this to be less conservative.
     virtual bool currentFrameKnownToBeOpaque() OVERRIDE { return false; }
 
-    virtual PassNativeImagePtr nativeImageForCurrentFrame() OVERRIDE;
+    virtual PassRefPtr<NativeImageSkia> nativeImageForCurrentFrame() OVERRIDE;
 
 private:
     SVGImageForContainer(SVGImage* image, const FloatSize& containerSize, float zoom)
diff --git a/Source/core/svg/graphics/filters/SVGFilter.cpp b/Source/core/svg/graphics/filters/SVGFilter.cpp
index d66019d..d7b9107 100644
--- a/Source/core/svg/graphics/filters/SVGFilter.cpp
+++ b/Source/core/svg/graphics/filters/SVGFilter.cpp
@@ -39,14 +39,14 @@
 {
     if (m_effectBBoxMode)
         value *= m_targetBoundingBox.width();
-    return Filter::applyHorizontalScale(value) * absoluteFilterRegion().width() / filterRegion().width();
+    return Filter::applyHorizontalScale(value);
 }
 
 float SVGFilter::applyVerticalScale(float value) const
 {
     if (m_effectBBoxMode)
         value *= m_targetBoundingBox.height();
-    return Filter::applyVerticalScale(value) * absoluteFilterRegion().height() / filterRegion().height();
+    return Filter::applyVerticalScale(value);
 }
 
 PassRefPtr<SVGFilter> SVGFilter::create(const AffineTransform& absoluteTransform, const FloatRect& absoluteSourceDrawingRegion, const FloatRect& targetBoundingBox, const FloatRect& filterRegion, bool effectBBoxMode)
diff --git a/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h b/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h
index c896eaf..271b88b 100644
--- a/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGAnimatedEnumerationPropertyTearOff.h
@@ -20,7 +20,7 @@
 #ifndef SVGAnimatedEnumerationPropertyTearOff_h
 #define SVGAnimatedEnumerationPropertyTearOff_h
 
-#include "core/svg/SVGException.h"
+#include "core/dom/ExceptionCode.h"
 #include "core/svg/properties/SVGAnimatedStaticPropertyTearOff.h"
 #include "core/svg/properties/SVGPropertyTraits.h"
 
@@ -33,7 +33,7 @@
     {
         // All SVG enumeration values, that are allowed to be set via SVG DOM start with 1, 0 corresponds to unknown and is not settable through SVG DOM.
         if (!property || property > SVGPropertyTraits<EnumType>::highestEnumValue()) {
-            ec = SVGException::SVG_INVALID_VALUE_ERR;
+            ec = TypeError;
             return;
         }
         SVGAnimatedStaticPropertyTearOff<unsigned>::setBaseVal(property, ec);
diff --git a/Source/core/svg/properties/SVGListProperty.h b/Source/core/svg/properties/SVGListProperty.h
index 1a62158..b44b3c5 100644
--- a/Source/core/svg/properties/SVGListProperty.h
+++ b/Source/core/svg/properties/SVGListProperty.h
@@ -20,7 +20,7 @@
 #ifndef SVGListProperty_h
 #define SVGListProperty_h
 
-#include "core/svg/SVGException.h"
+#include "core/dom/ExceptionCode.h"
 #include "core/svg/properties/SVGAnimatedProperty.h"
 #include "core/svg/properties/SVGPropertyTearOff.h"
 #include "core/svg/properties/SVGPropertyTraits.h"
@@ -147,7 +147,7 @@
 
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            ec = SVGException::SVG_WRONG_TYPE_ERR;
+            ec = TypeError;
             return 0;
         }
 
@@ -241,7 +241,7 @@
 
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            ec = SVGException::SVG_WRONG_TYPE_ERR;
+            ec = TypeError;
             return 0;
         }
 
@@ -314,7 +314,7 @@
 
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            ec = SVGException::SVG_WRONG_TYPE_ERR;
+            ec = TypeError;
             return 0;
         }
 
@@ -417,7 +417,7 @@
 
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            ec = SVGException::SVG_WRONG_TYPE_ERR;
+            ec = TypeError;
             return 0;
         }
 
diff --git a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
index e4bee7a..b090664 100644
--- a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
+++ b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.cpp
@@ -22,6 +22,7 @@
 #include "core/svg/properties/SVGPathSegListPropertyTearOff.h"
 
 #include "SVGNames.h"
+#include "core/dom/ExceptionCode.h"
 #include "core/svg/SVGPathElement.h"
 #include "core/svg/SVGPathSegWithContext.h"
 #include "core/svg/properties/SVGAnimatedPathSegListPropertyTearOff.h"
@@ -62,7 +63,7 @@
 {
     // Not specified, but FF/Opera do it this way, and it's just sane.
     if (!passNewItem) {
-        ec = SVGException::SVG_WRONG_TYPE_ERR;
+        ec = TypeError;
         return 0;
     }
 
diff --git a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
index c5e64de..5761f7c 100644
--- a/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
+++ b/Source/core/svg/properties/SVGPathSegListPropertyTearOff.h
@@ -20,6 +20,7 @@
 #ifndef SVGPathSegListPropertyTearOff_h
 #define SVGPathSegListPropertyTearOff_h
 
+#include "core/dom/ExceptionCode.h"
 #include "core/svg/SVGPathSegList.h"
 #include "core/svg/properties/SVGAnimatedListPropertyTearOff.h"
 
@@ -71,7 +72,7 @@
     {
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            ec = SVGException::SVG_WRONG_TYPE_ERR;
+            ec = TypeError;
             return 0;
         }
 
@@ -86,7 +87,7 @@
     {
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            ec = SVGException::SVG_WRONG_TYPE_ERR;
+            ec = TypeError;
             return 0;
         }
 
@@ -102,7 +103,7 @@
     {
         // Not specified, but FF/Opera do it this way, and it's just sane.
         if (!passNewItem) {
-            ec = SVGException::SVG_WRONG_TYPE_ERR;
+            ec = TypeError;
             return 0;
         }
 
diff --git a/Source/core/testing/InternalSettings.cpp b/Source/core/testing/InternalSettings.cpp
index 54d7358..4704e08 100644
--- a/Source/core/testing/InternalSettings.cpp
+++ b/Source/core/testing/InternalSettings.cpp
@@ -190,6 +190,14 @@
     settings()->setTouchEventEmulationEnabled(enabled);
 }
 
+// FIXME: This is a temporary flag and should be removed once accelerated
+// overflow scroll is ready (crbug.com/254111).
+void InternalSettings::setCompositorDrivenAcceleratedScrollingEnabled(bool enabled, ExceptionCode& ec)
+{
+    InternalSettingsGuardForSettings();
+    settings()->setCompositorDrivenAcceleratedScrollingEnabled(enabled);
+}
+
 typedef void (Settings::*SetFontFamilyFunction)(const AtomicString&, UScriptCode);
 static void setFontFamily(Settings* settings, const String& family, const String& script, SetFontFamilyFunction setter)
 {
diff --git a/Source/core/testing/InternalSettings.h b/Source/core/testing/InternalSettings.h
index 0a980de..8ac6c02 100644
--- a/Source/core/testing/InternalSettings.h
+++ b/Source/core/testing/InternalSettings.h
@@ -101,6 +101,10 @@
     void setTouchEventEmulationEnabled(bool, ExceptionCode&);
     void setUsesOverlayScrollbars(bool, ExceptionCode&);
 
+    // FIXME: This is a temporary flag and should be removed once accelerated
+    // overflow scroll is ready (crbug.com/254111).
+    void setCompositorDrivenAcceleratedScrollingEnabled(bool, ExceptionCode&);
+
     // FIXME: The following are RuntimeEnabledFeatures and likely
     // cannot be changed after process start. These setters should
     // be removed or moved onto internals.runtimeFlags:
diff --git a/Source/core/testing/InternalSettings.idl b/Source/core/testing/InternalSettings.idl
index b9ec8e1..85aa626 100644
--- a/Source/core/testing/InternalSettings.idl
+++ b/Source/core/testing/InternalSettings.idl
@@ -45,6 +45,10 @@
     [RaisesException] void setImagesEnabled(boolean enabled);
     [RaisesException] void setDefaultVideoPosterURL(DOMString poster);
 
+    // FIXME: This is a temporary flag and should be removed once accelerated
+    // overflow scroll is ready (crbug.com/254111).
+    [RaisesException] void setCompositorDrivenAcceleratedScrollingEnabled(boolean enabled);
+
     // FIXME: The following are RuntimeEnabledFeatures and likely
     // cannot be changed after process start.  These setters should
     // be removed or moved onto internals.runtimeFlags:
diff --git a/Source/core/testing/Internals.cpp b/Source/core/testing/Internals.cpp
index 7d9f195..f766d92 100644
--- a/Source/core/testing/Internals.cpp
+++ b/Source/core/testing/Internals.cpp
@@ -195,7 +195,7 @@
 }
 
 Internals::Internals(Document* document)
-    : ContextDestructionObserver(document)
+    : ContextLifecycleObserver(document)
     , m_runtimeFlags(InternalRuntimeFlags::create())
 {
 }
@@ -742,6 +742,17 @@
     return s_pagePopupDriver ? s_pagePopupDriver->pagePopupController() : 0;
 }
 
+PassRefPtr<ClientRect> Internals::unscaledViewportRect(ExceptionCode& ec)
+{
+    Document* document = contextDocument();
+    if (!document || !document->view()) {
+        ec = INVALID_ACCESS_ERR;
+        return ClientRect::create();
+    }
+
+    return ClientRect::create(document->view()->visibleContentRect());
+}
+
 PassRefPtr<ClientRect> Internals::absoluteCaretBounds(ExceptionCode& ec)
 {
     Document* document = contextDocument();
@@ -1889,7 +1900,9 @@
 PassRefPtr<ArrayBuffer> Internals::serializeObject(PassRefPtr<SerializedScriptValue> value) const
 {
     String stringValue = value->toWireString();
-    return ArrayBuffer::create(static_cast<const void*>(stringValue.impl()->characters()), stringValue.sizeInBytes());
+    RefPtr<ArrayBuffer> buffer = ArrayBuffer::createUninitialized(stringValue.length(), sizeof(UChar));
+    stringValue.copyTo(static_cast<UChar*>(buffer->data()), stringValue.length());
+    return buffer.release();
 }
 
 PassRefPtr<SerializedScriptValue> Internals::deserializeBuffer(PassRefPtr<ArrayBuffer> buffer) const
@@ -1908,6 +1921,17 @@
     frame()->loader()->reload(endToEnd);
 }
 
+PassRefPtr<ClientRect> Internals::selectionBounds(ExceptionCode& ec)
+{
+    Document* document = contextDocument();
+    if (!document || !document->frame() || !document->frame()->selection()) {
+        ec = INVALID_ACCESS_ERR;
+        return 0;
+    }
+
+    return ClientRect::create(document->frame()->selection()->bounds());
+}
+
 String Internals::markerTextForListItem(Element* element, ExceptionCode& ec)
 {
     if (!element) {
@@ -1926,6 +1950,16 @@
     return element->imageSourceURL();
 }
 
+String Internals::baseURL(Document* document, ExceptionCode& ec)
+{
+    if (!document) {
+        ec = INVALID_ACCESS_ERR;
+        return String();
+    }
+
+    return document->baseURL().string();
+}
+
 bool Internals::isSelectPopupVisible(Node* node)
 {
     if (!isHTMLSelectElement(node))
diff --git a/Source/core/testing/Internals.h b/Source/core/testing/Internals.h
index 586fb50..9e2f433 100644
--- a/Source/core/testing/Internals.h
+++ b/Source/core/testing/Internals.h
@@ -28,7 +28,7 @@
 #define Internals_h
 
 #include "core/css/CSSComputedStyleDeclaration.h"
-#include "core/dom/ContextDestructionObserver.h"
+#include "core/dom/ContextLifecycleObserver.h"
 #include "core/dom/ExceptionCodePlaceholder.h"
 #include "core/dom/NodeList.h"
 #include <wtf/ArrayBuffer.h>
@@ -62,8 +62,7 @@
 
 typedef int ExceptionCode;
 
-class Internals : public RefCounted<Internals>
-                , public ContextDestructionObserver {
+class Internals : public RefCounted<Internals>, public ContextLifecycleObserver {
 public:
     static PassRefPtr<Internals> create(Document*);
     virtual ~Internals();
@@ -128,6 +127,8 @@
     void setEnableMockPagePopup(bool, ExceptionCode&);
     PassRefPtr<PagePopupController> pagePopupController();
 
+    PassRefPtr<ClientRect> unscaledViewportRect(ExceptionCode&);
+
     PassRefPtr<ClientRect> absoluteCaretBounds(ExceptionCode&);
 
     PassRefPtr<ClientRect> boundingBox(Element*, ExceptionCode&);
@@ -278,6 +279,9 @@
 
     bool isSelectPopupVisible(Node*);
 
+    PassRefPtr<ClientRect> selectionBounds(ExceptionCode&);
+    String baseURL(Document*, ExceptionCode&);
+
 private:
     explicit Internals(Document*);
     Document* contextDocument() const;
diff --git a/Source/core/testing/Internals.idl b/Source/core/testing/Internals.idl
index c2ebf7e..d9e537e 100644
--- a/Source/core/testing/Internals.idl
+++ b/Source/core/testing/Internals.idl
@@ -85,6 +85,8 @@
     [RaisesException] void setEnableMockPagePopup(boolean enabled);
     readonly attribute PagePopupController pagePopupController;
 
+    [RaisesException] ClientRect unscaledViewportRect();
+
     [RaisesException] ClientRect absoluteCaretBounds();
 
     [RaisesException] ClientRect boundingBox(Element element);
@@ -233,6 +235,8 @@
 
     [RaisesException] DOMString markerTextForListItem(Element element);
 
+    [RaisesException] DOMString baseURL(Document document);
+
     SerializedScriptValue deserializeBuffer(ArrayBuffer buffer);
     ArrayBuffer serializeObject(SerializedScriptValue obj);
 
@@ -245,4 +249,6 @@
     [RaisesException] DOMString getImageSourceURL(Element element);
 
     boolean isSelectPopupVisible(Node node);
+
+    [RaisesException] ClientRect selectionBounds();
 };
diff --git a/Source/core/testing/MockPagePopupDriver.cpp b/Source/core/testing/MockPagePopupDriver.cpp
index da877a9..4c2fc5b 100644
--- a/Source/core/testing/MockPagePopupDriver.cpp
+++ b/Source/core/testing/MockPagePopupDriver.cpp
@@ -69,14 +69,11 @@
     if (document->body())
         document->body()->appendChild(m_iframe.get());
     Frame* contentFrame = m_iframe->contentFrame();
-    DocumentWriter* writer = contentFrame->loader()->activeDocumentLoader()->writer();
-    writer->setMIMEType("text/html");
-    writer->setEncoding("UTF-8", false);
-    writer->begin();
+    DocumentWriter* writer = contentFrame->loader()->activeDocumentLoader()->beginWriting("text/html", "UTF-8");
     const char scriptToSetUpPagePopupController[] = "<script>window.pagePopupController = parent.internals.pagePopupController;</script>";
     writer->addData(scriptToSetUpPagePopupController, sizeof(scriptToSetUpPagePopupController));
     m_popupClient->writeDocument(*writer);
-    writer->end();
+    contentFrame->loader()->activeDocumentLoader()->endWriting(writer);
 }
 
 PassRefPtr<MockPagePopup> MockPagePopup::create(PagePopupClient* client, const IntRect& originBoundsInRootView, Frame* mainFrame)
diff --git a/Source/core/tests/HeapGraphSerializerTest.cpp b/Source/core/tests/HeapGraphSerializerTest.cpp
index b9a6347..94a22b8 100644
--- a/Source/core/tests/HeapGraphSerializerTest.cpp
+++ b/Source/core/tests/HeapGraphSerializerTest.cpp
@@ -70,8 +70,8 @@
         m_nodes = chunkPart("nodes");
 
         // Reset platform depended size field values.
-        for (InspectorArray::iterator i = m_nodes->begin(); i != m_nodes->end(); i += s_nodeFieldCount)
-            *(i + s_sizeOffset) = InspectorBasicValue::create(0);
+        for (JSONArray::iterator i = m_nodes->begin(); i != m_nodes->end(); i += s_nodeFieldCount)
+            *(i + s_sizeOffset) = JSONBasicValue::create(0);
 
         m_id2index.clear();
 
@@ -95,12 +95,12 @@
     HeapGraphSerializer* serializer() { return &m_serializer; }
 
 private:
-    PassRefPtr<InspectorArray> chunkPart(String partName)
+    PassRefPtr<JSONArray> chunkPart(String partName)
     {
         EXPECT_TRUE(m_heapSnapshotChunk);
-        RefPtr<InspectorObject> chunk = *reinterpret_cast<RefPtr<InspectorObject>*>(&m_heapSnapshotChunk);
-        RefPtr<InspectorValue> partValue = chunk->get(partName);
-        RefPtr<InspectorArray> partArray;
+        RefPtr<JSONObject> chunk = *reinterpret_cast<RefPtr<JSONObject>*>(&m_heapSnapshotChunk);
+        RefPtr<JSONValue> partValue = chunk->get(partName);
+        RefPtr<JSONArray> partArray;
         EXPECT_TRUE(partValue->asArray(&partArray));
         return partArray.release();
     }
@@ -110,17 +110,17 @@
         return chunkPart(partName)->toJSONString().replace("\"", "'");
     }
 
-    String stringValue(InspectorArray* array, int index)
+    String stringValue(JSONArray* array, int index)
     {
-        RefPtr<InspectorValue> inspectorValue = array->get(index);
+        RefPtr<JSONValue> inspectorValue = array->get(index);
         String value;
         EXPECT_TRUE(inspectorValue->asString(&value));
         return value;
     }
 
-    int intValue(InspectorArray* array, int index)
+    int intValue(JSONArray* array, int index)
     {
-        RefPtr<InspectorValue> inspectorValue = array->get(index);
+        RefPtr<JSONValue> inspectorValue = array->get(index);
         int value;
         EXPECT_TRUE(inspectorValue->asNumber(&value));
         return value;
@@ -169,9 +169,9 @@
     HeapGraphSerializer m_serializer;
     RefPtr<TypeBuilder::Memory::HeapSnapshotChunk> m_heapSnapshotChunk;
 
-    RefPtr<InspectorArray> m_strings;
-    RefPtr<InspectorArray> m_nodes;
-    RefPtr<InspectorArray> m_edges;
+    RefPtr<JSONArray> m_strings;
+    RefPtr<JSONArray> m_nodes;
+    RefPtr<JSONArray> m_edges;
     HashMap<int, int> m_id2index;
 
     static const int s_nodeFieldCount = 5;
diff --git a/Source/core/webcore_arm_neon.target.darwin-arm.mk b/Source/core/webcore_arm_neon.target.darwin-arm.mk
index c38f7a9..cc25897 100644
--- a/Source/core/webcore_arm_neon.target.darwin-arm.mk
+++ b/Source/core/webcore_arm_neon.target.darwin-arm.mk
@@ -21,7 +21,7 @@
 
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -38,6 +38,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_arm_neon.target.linux-arm.mk b/Source/core/webcore_arm_neon.target.linux-arm.mk
index c38f7a9..cc25897 100644
--- a/Source/core/webcore_arm_neon.target.linux-arm.mk
+++ b/Source/core/webcore_arm_neon.target.linux-arm.mk
@@ -21,7 +21,7 @@
 
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -38,6 +38,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_derived.target.darwin-arm.mk b/Source/core/webcore_derived.target.darwin-arm.mk
index a8122e2..d52cef9 100644
--- a/Source/core/webcore_derived.target.darwin-arm.mk
+++ b/Source/core/webcore_derived.target.darwin-arm.mk
@@ -12,6 +12,7 @@
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
@@ -84,8 +85,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/Event.cpp: $(gyp_shared_intermediate_dir)/webkit/Event.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/DOMException.cpp: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp
-	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/PickerCommon.cpp: $(gyp_shared_intermediate_dir)/webkit/PickerCommon.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp
@@ -100,8 +99,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/SVGNames.cpp: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/MathMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp
-	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/MathMLNames.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/FontFamilyNames.cpp: $(gyp_shared_intermediate_dir)/webkit/FontFamilyNames.cpp
@@ -158,7 +155,6 @@
 	$(gyp_intermediate_dir)/CalendarPicker.cpp \
 	$(gyp_intermediate_dir)/ColorSuggestionPicker.cpp \
 	$(gyp_intermediate_dir)/Event.cpp \
-	$(gyp_intermediate_dir)/DOMException.cpp \
 	$(gyp_intermediate_dir)/PickerCommon.cpp \
 	$(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp \
 	$(gyp_intermediate_dir)/V8HTMLElementWrapperFactory.cpp \
@@ -166,7 +162,6 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/SVGNames.cpp \
-	$(gyp_intermediate_dir)/MathMLElementFactory.cpp \
 	$(gyp_intermediate_dir)/MathMLNames.cpp \
 	$(gyp_intermediate_dir)/FontFamilyNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
@@ -191,13 +186,13 @@
 	third_party/WebKit/Source/bindings/v8/ActiveDOMCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/ArrayValue.cpp \
 	third_party/WebKit/Source/bindings/v8/BindingSecurity.cpp \
+	third_party/WebKit/Source/bindings/v8/CustomElementConstructorBuilder.cpp \
 	third_party/WebKit/Source/bindings/v8/CustomElementHelpers.cpp \
 	third_party/WebKit/Source/bindings/v8/DOMDataStore.cpp \
 	third_party/WebKit/Source/bindings/v8/DOMWrapperWorld.cpp \
 	third_party/WebKit/Source/bindings/v8/DateExtension.cpp \
 	third_party/WebKit/Source/bindings/v8/Dictionary.cpp \
 	third_party/WebKit/Source/bindings/v8/IDBBindingUtilities.cpp \
-	third_party/WebKit/Source/bindings/v8/NPObjectWrapper.cpp \
 	third_party/WebKit/Source/bindings/v8/NPV8Object.cpp \
 	third_party/WebKit/Source/bindings/v8/PageScriptDebugServer.cpp \
 	third_party/WebKit/Source/bindings/v8/RetainedDOMInfo.cpp \
@@ -220,7 +215,7 @@
 	third_party/WebKit/Source/bindings/v8/V8AbstractEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Binding.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Callback.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Collection.cpp \
+	third_party/WebKit/Source/bindings/v8/V8CustomElementCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/V8DOMConfiguration.cpp \
 	third_party/WebKit/Source/bindings/v8/V8ErrorHandler.cpp \
 	third_party/WebKit/Source/bindings/v8/V8DOMWrapper.cpp \
@@ -245,9 +240,10 @@
 	third_party/WebKit/Source/bindings/v8/V8Utilities.cpp \
 	third_party/WebKit/Source/bindings/v8/V8ValueCache.cpp \
 	third_party/WebKit/Source/bindings/v8/V8WindowShell.cpp \
-	third_party/WebKit/Source/bindings/v8/V8WorkerContextEventListener.cpp \
+	third_party/WebKit/Source/bindings/v8/V8WorkerGlobalScopeEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptController.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptDebugServer.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8AlgorithmCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioBufferSourceNodeCustom.cpp \
@@ -266,7 +262,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8CustomSQLStatementErrorCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CustomXPathNSResolver.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DataViewCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DedicatedWorkerContextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8DedicatedWorkerGlobalScopeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceMotionEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DocumentCustom.cpp \
@@ -310,6 +306,8 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8PannerNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PerformanceEntryCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PopStateEventCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8PromiseCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8PromiseResolverCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLResultSetRowListCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp \
@@ -323,7 +321,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebKitPointCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WindowCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WorkerContextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8WorkerGlobalScopeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCryptoCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8XMLHttpRequestCustom.cpp \
@@ -332,7 +330,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -367,9 +365,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -391,11 +387,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -410,7 +406,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -433,10 +428,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/webcore \
 	$(gyp_shared_intermediate_dir)/webkit \
 	$(gyp_shared_intermediate_dir)/webkit/bindings \
@@ -470,6 +464,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -492,10 +487,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -507,9 +501,186 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/webcore \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom \
+	$(LOCAL_PATH)/third_party/WebKit/Source/modules/mediastream \
+	$(LOCAL_PATH)/third_party/WebKit/Source/modules/speech \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/dom \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/html \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/page \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -526,6 +697,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_derived.target.darwin-mips.mk b/Source/core/webcore_derived.target.darwin-mips.mk
index ceed8d8..00ba22d 100644
--- a/Source/core/webcore_derived.target.darwin-mips.mk
+++ b/Source/core/webcore_derived.target.darwin-mips.mk
@@ -12,6 +12,7 @@
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
@@ -84,8 +85,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/Event.cpp: $(gyp_shared_intermediate_dir)/webkit/Event.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/DOMException.cpp: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp
-	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/PickerCommon.cpp: $(gyp_shared_intermediate_dir)/webkit/PickerCommon.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp
@@ -100,8 +99,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/SVGNames.cpp: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/MathMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp
-	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/MathMLNames.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/FontFamilyNames.cpp: $(gyp_shared_intermediate_dir)/webkit/FontFamilyNames.cpp
@@ -158,7 +155,6 @@
 	$(gyp_intermediate_dir)/CalendarPicker.cpp \
 	$(gyp_intermediate_dir)/ColorSuggestionPicker.cpp \
 	$(gyp_intermediate_dir)/Event.cpp \
-	$(gyp_intermediate_dir)/DOMException.cpp \
 	$(gyp_intermediate_dir)/PickerCommon.cpp \
 	$(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp \
 	$(gyp_intermediate_dir)/V8HTMLElementWrapperFactory.cpp \
@@ -166,7 +162,6 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/SVGNames.cpp \
-	$(gyp_intermediate_dir)/MathMLElementFactory.cpp \
 	$(gyp_intermediate_dir)/MathMLNames.cpp \
 	$(gyp_intermediate_dir)/FontFamilyNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
@@ -191,13 +186,13 @@
 	third_party/WebKit/Source/bindings/v8/ActiveDOMCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/ArrayValue.cpp \
 	third_party/WebKit/Source/bindings/v8/BindingSecurity.cpp \
+	third_party/WebKit/Source/bindings/v8/CustomElementConstructorBuilder.cpp \
 	third_party/WebKit/Source/bindings/v8/CustomElementHelpers.cpp \
 	third_party/WebKit/Source/bindings/v8/DOMDataStore.cpp \
 	third_party/WebKit/Source/bindings/v8/DOMWrapperWorld.cpp \
 	third_party/WebKit/Source/bindings/v8/DateExtension.cpp \
 	third_party/WebKit/Source/bindings/v8/Dictionary.cpp \
 	third_party/WebKit/Source/bindings/v8/IDBBindingUtilities.cpp \
-	third_party/WebKit/Source/bindings/v8/NPObjectWrapper.cpp \
 	third_party/WebKit/Source/bindings/v8/NPV8Object.cpp \
 	third_party/WebKit/Source/bindings/v8/PageScriptDebugServer.cpp \
 	third_party/WebKit/Source/bindings/v8/RetainedDOMInfo.cpp \
@@ -220,7 +215,7 @@
 	third_party/WebKit/Source/bindings/v8/V8AbstractEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Binding.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Callback.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Collection.cpp \
+	third_party/WebKit/Source/bindings/v8/V8CustomElementCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/V8DOMConfiguration.cpp \
 	third_party/WebKit/Source/bindings/v8/V8ErrorHandler.cpp \
 	third_party/WebKit/Source/bindings/v8/V8DOMWrapper.cpp \
@@ -245,9 +240,10 @@
 	third_party/WebKit/Source/bindings/v8/V8Utilities.cpp \
 	third_party/WebKit/Source/bindings/v8/V8ValueCache.cpp \
 	third_party/WebKit/Source/bindings/v8/V8WindowShell.cpp \
-	third_party/WebKit/Source/bindings/v8/V8WorkerContextEventListener.cpp \
+	third_party/WebKit/Source/bindings/v8/V8WorkerGlobalScopeEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptController.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptDebugServer.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8AlgorithmCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioBufferSourceNodeCustom.cpp \
@@ -266,7 +262,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8CustomSQLStatementErrorCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CustomXPathNSResolver.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DataViewCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DedicatedWorkerContextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8DedicatedWorkerGlobalScopeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceMotionEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DocumentCustom.cpp \
@@ -310,6 +306,8 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8PannerNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PerformanceEntryCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PopStateEventCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8PromiseCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8PromiseResolverCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLResultSetRowListCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp \
@@ -323,7 +321,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebKitPointCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WindowCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WorkerContextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8WorkerGlobalScopeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCryptoCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8XMLHttpRequestCustom.cpp \
@@ -332,7 +330,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -367,9 +365,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -390,11 +386,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -409,7 +405,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -432,10 +427,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/webcore \
 	$(gyp_shared_intermediate_dir)/webkit \
 	$(gyp_shared_intermediate_dir)/webkit/bindings \
@@ -469,6 +463,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -491,10 +486,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -506,9 +500,185 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/webcore \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom \
+	$(LOCAL_PATH)/third_party/WebKit/Source/modules/mediastream \
+	$(LOCAL_PATH)/third_party/WebKit/Source/modules/speech \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/dom \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/html \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/page \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -523,6 +693,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-EL \
+	-Wl,--no-keep-memory \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_derived.target.darwin-x86.mk b/Source/core/webcore_derived.target.darwin-x86.mk
index 6e721fa..b8e77da 100644
--- a/Source/core/webcore_derived.target.darwin-x86.mk
+++ b/Source/core/webcore_derived.target.darwin-x86.mk
@@ -12,6 +12,7 @@
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
@@ -84,8 +85,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/Event.cpp: $(gyp_shared_intermediate_dir)/webkit/Event.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/DOMException.cpp: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp
-	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/PickerCommon.cpp: $(gyp_shared_intermediate_dir)/webkit/PickerCommon.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp
@@ -100,8 +99,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/SVGNames.cpp: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/MathMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp
-	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/MathMLNames.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/FontFamilyNames.cpp: $(gyp_shared_intermediate_dir)/webkit/FontFamilyNames.cpp
@@ -158,7 +155,6 @@
 	$(gyp_intermediate_dir)/CalendarPicker.cpp \
 	$(gyp_intermediate_dir)/ColorSuggestionPicker.cpp \
 	$(gyp_intermediate_dir)/Event.cpp \
-	$(gyp_intermediate_dir)/DOMException.cpp \
 	$(gyp_intermediate_dir)/PickerCommon.cpp \
 	$(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp \
 	$(gyp_intermediate_dir)/V8HTMLElementWrapperFactory.cpp \
@@ -166,7 +162,6 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/SVGNames.cpp \
-	$(gyp_intermediate_dir)/MathMLElementFactory.cpp \
 	$(gyp_intermediate_dir)/MathMLNames.cpp \
 	$(gyp_intermediate_dir)/FontFamilyNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
@@ -191,13 +186,13 @@
 	third_party/WebKit/Source/bindings/v8/ActiveDOMCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/ArrayValue.cpp \
 	third_party/WebKit/Source/bindings/v8/BindingSecurity.cpp \
+	third_party/WebKit/Source/bindings/v8/CustomElementConstructorBuilder.cpp \
 	third_party/WebKit/Source/bindings/v8/CustomElementHelpers.cpp \
 	third_party/WebKit/Source/bindings/v8/DOMDataStore.cpp \
 	third_party/WebKit/Source/bindings/v8/DOMWrapperWorld.cpp \
 	third_party/WebKit/Source/bindings/v8/DateExtension.cpp \
 	third_party/WebKit/Source/bindings/v8/Dictionary.cpp \
 	third_party/WebKit/Source/bindings/v8/IDBBindingUtilities.cpp \
-	third_party/WebKit/Source/bindings/v8/NPObjectWrapper.cpp \
 	third_party/WebKit/Source/bindings/v8/NPV8Object.cpp \
 	third_party/WebKit/Source/bindings/v8/PageScriptDebugServer.cpp \
 	third_party/WebKit/Source/bindings/v8/RetainedDOMInfo.cpp \
@@ -220,7 +215,7 @@
 	third_party/WebKit/Source/bindings/v8/V8AbstractEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Binding.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Callback.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Collection.cpp \
+	third_party/WebKit/Source/bindings/v8/V8CustomElementCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/V8DOMConfiguration.cpp \
 	third_party/WebKit/Source/bindings/v8/V8ErrorHandler.cpp \
 	third_party/WebKit/Source/bindings/v8/V8DOMWrapper.cpp \
@@ -245,9 +240,10 @@
 	third_party/WebKit/Source/bindings/v8/V8Utilities.cpp \
 	third_party/WebKit/Source/bindings/v8/V8ValueCache.cpp \
 	third_party/WebKit/Source/bindings/v8/V8WindowShell.cpp \
-	third_party/WebKit/Source/bindings/v8/V8WorkerContextEventListener.cpp \
+	third_party/WebKit/Source/bindings/v8/V8WorkerGlobalScopeEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptController.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptDebugServer.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8AlgorithmCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioBufferSourceNodeCustom.cpp \
@@ -266,7 +262,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8CustomSQLStatementErrorCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CustomXPathNSResolver.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DataViewCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DedicatedWorkerContextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8DedicatedWorkerGlobalScopeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceMotionEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DocumentCustom.cpp \
@@ -310,6 +306,8 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8PannerNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PerformanceEntryCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PopStateEventCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8PromiseCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8PromiseResolverCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLResultSetRowListCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp \
@@ -323,7 +321,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebKitPointCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WindowCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WorkerContextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8WorkerGlobalScopeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCryptoCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8XMLHttpRequestCustom.cpp \
@@ -332,7 +330,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -369,9 +367,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -393,11 +389,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -412,7 +408,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -435,10 +430,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/webcore \
 	$(gyp_shared_intermediate_dir)/webkit \
 	$(gyp_shared_intermediate_dir)/webkit/bindings \
@@ -472,6 +466,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -494,10 +489,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -508,9 +502,189 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/webcore \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom \
+	$(LOCAL_PATH)/third_party/WebKit/Source/modules/mediastream \
+	$(LOCAL_PATH)/third_party/WebKit/Source/modules/speech \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/dom \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/html \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/page \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -525,6 +699,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-m32 \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_derived.target.linux-arm.mk b/Source/core/webcore_derived.target.linux-arm.mk
index a8122e2..d52cef9 100644
--- a/Source/core/webcore_derived.target.linux-arm.mk
+++ b/Source/core/webcore_derived.target.linux-arm.mk
@@ -12,6 +12,7 @@
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
@@ -84,8 +85,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/Event.cpp: $(gyp_shared_intermediate_dir)/webkit/Event.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/DOMException.cpp: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp
-	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/PickerCommon.cpp: $(gyp_shared_intermediate_dir)/webkit/PickerCommon.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp
@@ -100,8 +99,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/SVGNames.cpp: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/MathMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp
-	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/MathMLNames.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/FontFamilyNames.cpp: $(gyp_shared_intermediate_dir)/webkit/FontFamilyNames.cpp
@@ -158,7 +155,6 @@
 	$(gyp_intermediate_dir)/CalendarPicker.cpp \
 	$(gyp_intermediate_dir)/ColorSuggestionPicker.cpp \
 	$(gyp_intermediate_dir)/Event.cpp \
-	$(gyp_intermediate_dir)/DOMException.cpp \
 	$(gyp_intermediate_dir)/PickerCommon.cpp \
 	$(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp \
 	$(gyp_intermediate_dir)/V8HTMLElementWrapperFactory.cpp \
@@ -166,7 +162,6 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/SVGNames.cpp \
-	$(gyp_intermediate_dir)/MathMLElementFactory.cpp \
 	$(gyp_intermediate_dir)/MathMLNames.cpp \
 	$(gyp_intermediate_dir)/FontFamilyNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
@@ -191,13 +186,13 @@
 	third_party/WebKit/Source/bindings/v8/ActiveDOMCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/ArrayValue.cpp \
 	third_party/WebKit/Source/bindings/v8/BindingSecurity.cpp \
+	third_party/WebKit/Source/bindings/v8/CustomElementConstructorBuilder.cpp \
 	third_party/WebKit/Source/bindings/v8/CustomElementHelpers.cpp \
 	third_party/WebKit/Source/bindings/v8/DOMDataStore.cpp \
 	third_party/WebKit/Source/bindings/v8/DOMWrapperWorld.cpp \
 	third_party/WebKit/Source/bindings/v8/DateExtension.cpp \
 	third_party/WebKit/Source/bindings/v8/Dictionary.cpp \
 	third_party/WebKit/Source/bindings/v8/IDBBindingUtilities.cpp \
-	third_party/WebKit/Source/bindings/v8/NPObjectWrapper.cpp \
 	third_party/WebKit/Source/bindings/v8/NPV8Object.cpp \
 	third_party/WebKit/Source/bindings/v8/PageScriptDebugServer.cpp \
 	third_party/WebKit/Source/bindings/v8/RetainedDOMInfo.cpp \
@@ -220,7 +215,7 @@
 	third_party/WebKit/Source/bindings/v8/V8AbstractEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Binding.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Callback.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Collection.cpp \
+	third_party/WebKit/Source/bindings/v8/V8CustomElementCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/V8DOMConfiguration.cpp \
 	third_party/WebKit/Source/bindings/v8/V8ErrorHandler.cpp \
 	third_party/WebKit/Source/bindings/v8/V8DOMWrapper.cpp \
@@ -245,9 +240,10 @@
 	third_party/WebKit/Source/bindings/v8/V8Utilities.cpp \
 	third_party/WebKit/Source/bindings/v8/V8ValueCache.cpp \
 	third_party/WebKit/Source/bindings/v8/V8WindowShell.cpp \
-	third_party/WebKit/Source/bindings/v8/V8WorkerContextEventListener.cpp \
+	third_party/WebKit/Source/bindings/v8/V8WorkerGlobalScopeEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptController.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptDebugServer.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8AlgorithmCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioBufferSourceNodeCustom.cpp \
@@ -266,7 +262,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8CustomSQLStatementErrorCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CustomXPathNSResolver.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DataViewCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DedicatedWorkerContextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8DedicatedWorkerGlobalScopeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceMotionEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DocumentCustom.cpp \
@@ -310,6 +306,8 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8PannerNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PerformanceEntryCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PopStateEventCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8PromiseCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8PromiseResolverCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLResultSetRowListCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp \
@@ -323,7 +321,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebKitPointCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WindowCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WorkerContextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8WorkerGlobalScopeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCryptoCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8XMLHttpRequestCustom.cpp \
@@ -332,7 +330,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -367,9 +365,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -391,11 +387,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -410,7 +406,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -433,10 +428,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/webcore \
 	$(gyp_shared_intermediate_dir)/webkit \
 	$(gyp_shared_intermediate_dir)/webkit/bindings \
@@ -470,6 +464,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -492,10 +487,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -507,9 +501,186 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/webcore \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom \
+	$(LOCAL_PATH)/third_party/WebKit/Source/modules/mediastream \
+	$(LOCAL_PATH)/third_party/WebKit/Source/modules/speech \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/dom \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/html \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/page \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -526,6 +697,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_derived.target.linux-mips.mk b/Source/core/webcore_derived.target.linux-mips.mk
index ceed8d8..00ba22d 100644
--- a/Source/core/webcore_derived.target.linux-mips.mk
+++ b/Source/core/webcore_derived.target.linux-mips.mk
@@ -12,6 +12,7 @@
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
@@ -84,8 +85,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/Event.cpp: $(gyp_shared_intermediate_dir)/webkit/Event.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/DOMException.cpp: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp
-	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/PickerCommon.cpp: $(gyp_shared_intermediate_dir)/webkit/PickerCommon.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp
@@ -100,8 +99,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/SVGNames.cpp: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/MathMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp
-	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/MathMLNames.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/FontFamilyNames.cpp: $(gyp_shared_intermediate_dir)/webkit/FontFamilyNames.cpp
@@ -158,7 +155,6 @@
 	$(gyp_intermediate_dir)/CalendarPicker.cpp \
 	$(gyp_intermediate_dir)/ColorSuggestionPicker.cpp \
 	$(gyp_intermediate_dir)/Event.cpp \
-	$(gyp_intermediate_dir)/DOMException.cpp \
 	$(gyp_intermediate_dir)/PickerCommon.cpp \
 	$(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp \
 	$(gyp_intermediate_dir)/V8HTMLElementWrapperFactory.cpp \
@@ -166,7 +162,6 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/SVGNames.cpp \
-	$(gyp_intermediate_dir)/MathMLElementFactory.cpp \
 	$(gyp_intermediate_dir)/MathMLNames.cpp \
 	$(gyp_intermediate_dir)/FontFamilyNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
@@ -191,13 +186,13 @@
 	third_party/WebKit/Source/bindings/v8/ActiveDOMCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/ArrayValue.cpp \
 	third_party/WebKit/Source/bindings/v8/BindingSecurity.cpp \
+	third_party/WebKit/Source/bindings/v8/CustomElementConstructorBuilder.cpp \
 	third_party/WebKit/Source/bindings/v8/CustomElementHelpers.cpp \
 	third_party/WebKit/Source/bindings/v8/DOMDataStore.cpp \
 	third_party/WebKit/Source/bindings/v8/DOMWrapperWorld.cpp \
 	third_party/WebKit/Source/bindings/v8/DateExtension.cpp \
 	third_party/WebKit/Source/bindings/v8/Dictionary.cpp \
 	third_party/WebKit/Source/bindings/v8/IDBBindingUtilities.cpp \
-	third_party/WebKit/Source/bindings/v8/NPObjectWrapper.cpp \
 	third_party/WebKit/Source/bindings/v8/NPV8Object.cpp \
 	third_party/WebKit/Source/bindings/v8/PageScriptDebugServer.cpp \
 	third_party/WebKit/Source/bindings/v8/RetainedDOMInfo.cpp \
@@ -220,7 +215,7 @@
 	third_party/WebKit/Source/bindings/v8/V8AbstractEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Binding.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Callback.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Collection.cpp \
+	third_party/WebKit/Source/bindings/v8/V8CustomElementCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/V8DOMConfiguration.cpp \
 	third_party/WebKit/Source/bindings/v8/V8ErrorHandler.cpp \
 	third_party/WebKit/Source/bindings/v8/V8DOMWrapper.cpp \
@@ -245,9 +240,10 @@
 	third_party/WebKit/Source/bindings/v8/V8Utilities.cpp \
 	third_party/WebKit/Source/bindings/v8/V8ValueCache.cpp \
 	third_party/WebKit/Source/bindings/v8/V8WindowShell.cpp \
-	third_party/WebKit/Source/bindings/v8/V8WorkerContextEventListener.cpp \
+	third_party/WebKit/Source/bindings/v8/V8WorkerGlobalScopeEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptController.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptDebugServer.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8AlgorithmCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioBufferSourceNodeCustom.cpp \
@@ -266,7 +262,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8CustomSQLStatementErrorCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CustomXPathNSResolver.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DataViewCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DedicatedWorkerContextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8DedicatedWorkerGlobalScopeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceMotionEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DocumentCustom.cpp \
@@ -310,6 +306,8 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8PannerNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PerformanceEntryCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PopStateEventCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8PromiseCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8PromiseResolverCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLResultSetRowListCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp \
@@ -323,7 +321,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebKitPointCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WindowCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WorkerContextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8WorkerGlobalScopeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCryptoCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8XMLHttpRequestCustom.cpp \
@@ -332,7 +330,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -367,9 +365,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -390,11 +386,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -409,7 +405,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -432,10 +427,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/webcore \
 	$(gyp_shared_intermediate_dir)/webkit \
 	$(gyp_shared_intermediate_dir)/webkit/bindings \
@@ -469,6 +463,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -491,10 +486,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -506,9 +500,185 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/webcore \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom \
+	$(LOCAL_PATH)/third_party/WebKit/Source/modules/mediastream \
+	$(LOCAL_PATH)/third_party/WebKit/Source/modules/speech \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/dom \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/html \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/page \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -523,6 +693,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-EL \
+	-Wl,--no-keep-memory \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_derived.target.linux-x86.mk b/Source/core/webcore_derived.target.linux-x86.mk
index 6e721fa..b8e77da 100644
--- a/Source/core/webcore_derived.target.linux-x86.mk
+++ b/Source/core/webcore_derived.target.linux-x86.mk
@@ -12,6 +12,7 @@
 # Make sure our deps are built first.
 GYP_TARGET_DEPENDENCIES := \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_webcore_prerequisites_gyp)/webcore_prerequisites.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
@@ -84,8 +85,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/Event.cpp: $(gyp_shared_intermediate_dir)/webkit/Event.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/DOMException.cpp: $(gyp_shared_intermediate_dir)/webkit/DOMException.cpp
-	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/PickerCommon.cpp: $(gyp_shared_intermediate_dir)/webkit/PickerCommon.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp: $(gyp_shared_intermediate_dir)/webkit/UserAgentStyleSheetsData.cpp
@@ -100,8 +99,6 @@
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/SVGNames.cpp: $(gyp_shared_intermediate_dir)/webkit/SVGNames.cpp
 	mkdir -p $(@D); cp $< $@
-$(gyp_intermediate_dir)/MathMLElementFactory.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLElementFactory.cpp
-	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/MathMLNames.cpp: $(gyp_shared_intermediate_dir)/webkit/MathMLNames.cpp
 	mkdir -p $(@D); cp $< $@
 $(gyp_intermediate_dir)/FontFamilyNames.cpp: $(gyp_shared_intermediate_dir)/webkit/FontFamilyNames.cpp
@@ -158,7 +155,6 @@
 	$(gyp_intermediate_dir)/CalendarPicker.cpp \
 	$(gyp_intermediate_dir)/ColorSuggestionPicker.cpp \
 	$(gyp_intermediate_dir)/Event.cpp \
-	$(gyp_intermediate_dir)/DOMException.cpp \
 	$(gyp_intermediate_dir)/PickerCommon.cpp \
 	$(gyp_intermediate_dir)/UserAgentStyleSheetsData.cpp \
 	$(gyp_intermediate_dir)/V8HTMLElementWrapperFactory.cpp \
@@ -166,7 +162,6 @@
 	$(gyp_intermediate_dir)/XMLNSNames.cpp \
 	$(gyp_intermediate_dir)/XMLNames.cpp \
 	$(gyp_intermediate_dir)/SVGNames.cpp \
-	$(gyp_intermediate_dir)/MathMLElementFactory.cpp \
 	$(gyp_intermediate_dir)/MathMLNames.cpp \
 	$(gyp_intermediate_dir)/FontFamilyNames.cpp \
 	$(gyp_intermediate_dir)/HTMLEntityTable.cpp \
@@ -191,13 +186,13 @@
 	third_party/WebKit/Source/bindings/v8/ActiveDOMCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/ArrayValue.cpp \
 	third_party/WebKit/Source/bindings/v8/BindingSecurity.cpp \
+	third_party/WebKit/Source/bindings/v8/CustomElementConstructorBuilder.cpp \
 	third_party/WebKit/Source/bindings/v8/CustomElementHelpers.cpp \
 	third_party/WebKit/Source/bindings/v8/DOMDataStore.cpp \
 	third_party/WebKit/Source/bindings/v8/DOMWrapperWorld.cpp \
 	third_party/WebKit/Source/bindings/v8/DateExtension.cpp \
 	third_party/WebKit/Source/bindings/v8/Dictionary.cpp \
 	third_party/WebKit/Source/bindings/v8/IDBBindingUtilities.cpp \
-	third_party/WebKit/Source/bindings/v8/NPObjectWrapper.cpp \
 	third_party/WebKit/Source/bindings/v8/NPV8Object.cpp \
 	third_party/WebKit/Source/bindings/v8/PageScriptDebugServer.cpp \
 	third_party/WebKit/Source/bindings/v8/RetainedDOMInfo.cpp \
@@ -220,7 +215,7 @@
 	third_party/WebKit/Source/bindings/v8/V8AbstractEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Binding.cpp \
 	third_party/WebKit/Source/bindings/v8/V8Callback.cpp \
-	third_party/WebKit/Source/bindings/v8/V8Collection.cpp \
+	third_party/WebKit/Source/bindings/v8/V8CustomElementCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/V8DOMConfiguration.cpp \
 	third_party/WebKit/Source/bindings/v8/V8ErrorHandler.cpp \
 	third_party/WebKit/Source/bindings/v8/V8DOMWrapper.cpp \
@@ -245,9 +240,10 @@
 	third_party/WebKit/Source/bindings/v8/V8Utilities.cpp \
 	third_party/WebKit/Source/bindings/v8/V8ValueCache.cpp \
 	third_party/WebKit/Source/bindings/v8/V8WindowShell.cpp \
-	third_party/WebKit/Source/bindings/v8/V8WorkerContextEventListener.cpp \
+	third_party/WebKit/Source/bindings/v8/V8WorkerGlobalScopeEventListener.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptController.cpp \
 	third_party/WebKit/Source/bindings/v8/WorkerScriptDebugServer.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8AlgorithmCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8ArrayBufferViewCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8AudioBufferSourceNodeCustom.cpp \
@@ -266,7 +262,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8CustomSQLStatementErrorCallback.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8CustomXPathNSResolver.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DataViewCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8DedicatedWorkerContextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8DedicatedWorkerGlobalScopeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceMotionEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DeviceOrientationEventCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8DocumentCustom.cpp \
@@ -310,6 +306,8 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8PannerNodeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PerformanceEntryCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8PopStateEventCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8PromiseCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8PromiseResolverCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLResultSetRowListCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8SQLTransactionSyncCustom.cpp \
@@ -323,7 +321,7 @@
 	third_party/WebKit/Source/bindings/v8/custom/V8WebGLRenderingContextCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WebKitPointCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WindowCustom.cpp \
-	third_party/WebKit/Source/bindings/v8/custom/V8WorkerContextCustom.cpp \
+	third_party/WebKit/Source/bindings/v8/custom/V8WorkerGlobalScopeCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCryptoCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8WorkerCustom.cpp \
 	third_party/WebKit/Source/bindings/v8/custom/V8XMLHttpRequestCustom.cpp \
@@ -332,7 +330,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -369,9 +367,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -393,11 +389,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -412,7 +408,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -435,10 +430,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/webcore \
 	$(gyp_shared_intermediate_dir)/webkit \
 	$(gyp_shared_intermediate_dir)/webkit/bindings \
@@ -472,6 +466,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -494,10 +489,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -508,9 +502,189 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/webcore \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(LOCAL_PATH)/third_party/WebKit/Source/bindings/v8/custom \
+	$(LOCAL_PATH)/third_party/WebKit/Source/modules/mediastream \
+	$(LOCAL_PATH)/third_party/WebKit/Source/modules/speech \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/dom \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/html \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/html/shadow \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/inspector \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/page \
+	$(LOCAL_PATH)/third_party/WebKit/Source/core/svg \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -525,6 +699,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-m32 \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_dom.target.darwin-arm.mk b/Source/core/webcore_dom.target.darwin-arm.mk
index b3345b1..2127fbe 100644
--- a/Source/core/webcore_dom.target.darwin-arm.mk
+++ b/Source/core/webcore_dom.target.darwin-arm.mk
@@ -43,14 +43,16 @@
 	third_party/WebKit/Source/core/dom/CompositionEvent.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNode.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp \
-	third_party/WebKit/Source/core/dom/ContextDestructionObserver.cpp \
+	third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/ContextFeatures.cpp \
+	third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementDefinition.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementCallbackDispatcher.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistry.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.cpp \
 	third_party/WebKit/Source/core/dom/CustomEvent.cpp \
-	third_party/WebKit/Source/core/dom/DOMCoreException.cpp \
 	third_party/WebKit/Source/core/dom/DOMError.cpp \
+	third_party/WebKit/Source/core/dom/DOMException.cpp \
 	third_party/WebKit/Source/core/dom/DOMImplementation.cpp \
 	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
@@ -68,6 +70,7 @@
 	third_party/WebKit/Source/core/dom/DocumentLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/DocumentMarkerController.cpp \
 	third_party/WebKit/Source/core/dom/DocumentMarker.cpp \
+	third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp \
 	third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp \
 	third_party/WebKit/Source/core/dom/DocumentParser.cpp \
 	third_party/WebKit/Source/core/dom/DocumentSharedObjectPool.cpp \
@@ -85,7 +88,6 @@
 	third_party/WebKit/Source/core/dom/EventNames.cpp \
 	third_party/WebKit/Source/core/dom/EventPathWalker.cpp \
 	third_party/WebKit/Source/core/dom/EventTarget.cpp \
-	third_party/WebKit/Source/core/dom/ExceptionBase.cpp \
 	third_party/WebKit/Source/core/dom/ExceptionCodePlaceholder.cpp \
 	third_party/WebKit/Source/core/dom/FocusEvent.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenController.cpp \
@@ -100,6 +102,7 @@
 	third_party/WebKit/Source/core/dom/MessageEvent.cpp \
 	third_party/WebKit/Source/core/dom/MessagePort.cpp \
 	third_party/WebKit/Source/core/dom/MessagePortChannel.cpp \
+	third_party/WebKit/Source/core/dom/Microtask.cpp \
 	third_party/WebKit/Source/core/dom/MouseEvent.cpp \
 	third_party/WebKit/Source/core/dom/MouseRelatedEvent.cpp \
 	third_party/WebKit/Source/core/dom/MutationEvent.cpp \
@@ -133,7 +136,6 @@
 	third_party/WebKit/Source/core/dom/PseudoElement.cpp \
 	third_party/WebKit/Source/core/dom/QualifiedName.cpp \
 	third_party/WebKit/Source/core/dom/Range.cpp \
-	third_party/WebKit/Source/core/dom/RegisteredEventListener.cpp \
 	third_party/WebKit/Source/core/dom/ResourceProgressEvent.cpp \
 	third_party/WebKit/Source/core/dom/ScopedEventQueue.cpp \
 	third_party/WebKit/Source/core/dom/ScriptElement.cpp \
@@ -147,7 +149,6 @@
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
-	third_party/WebKit/Source/core/dom/StyledElement.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextEvent.cpp \
@@ -181,7 +182,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -216,9 +217,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -240,11 +239,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -259,7 +258,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -282,10 +280,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -307,6 +304,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -330,10 +328,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -345,9 +342,175 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -364,6 +527,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_dom.target.darwin-mips.mk b/Source/core/webcore_dom.target.darwin-mips.mk
index 5540509..4e8a700 100644
--- a/Source/core/webcore_dom.target.darwin-mips.mk
+++ b/Source/core/webcore_dom.target.darwin-mips.mk
@@ -43,14 +43,16 @@
 	third_party/WebKit/Source/core/dom/CompositionEvent.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNode.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp \
-	third_party/WebKit/Source/core/dom/ContextDestructionObserver.cpp \
+	third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/ContextFeatures.cpp \
+	third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementDefinition.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementCallbackDispatcher.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistry.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.cpp \
 	third_party/WebKit/Source/core/dom/CustomEvent.cpp \
-	third_party/WebKit/Source/core/dom/DOMCoreException.cpp \
 	third_party/WebKit/Source/core/dom/DOMError.cpp \
+	third_party/WebKit/Source/core/dom/DOMException.cpp \
 	third_party/WebKit/Source/core/dom/DOMImplementation.cpp \
 	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
@@ -68,6 +70,7 @@
 	third_party/WebKit/Source/core/dom/DocumentLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/DocumentMarkerController.cpp \
 	third_party/WebKit/Source/core/dom/DocumentMarker.cpp \
+	third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp \
 	third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp \
 	third_party/WebKit/Source/core/dom/DocumentParser.cpp \
 	third_party/WebKit/Source/core/dom/DocumentSharedObjectPool.cpp \
@@ -85,7 +88,6 @@
 	third_party/WebKit/Source/core/dom/EventNames.cpp \
 	third_party/WebKit/Source/core/dom/EventPathWalker.cpp \
 	third_party/WebKit/Source/core/dom/EventTarget.cpp \
-	third_party/WebKit/Source/core/dom/ExceptionBase.cpp \
 	third_party/WebKit/Source/core/dom/ExceptionCodePlaceholder.cpp \
 	third_party/WebKit/Source/core/dom/FocusEvent.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenController.cpp \
@@ -100,6 +102,7 @@
 	third_party/WebKit/Source/core/dom/MessageEvent.cpp \
 	third_party/WebKit/Source/core/dom/MessagePort.cpp \
 	third_party/WebKit/Source/core/dom/MessagePortChannel.cpp \
+	third_party/WebKit/Source/core/dom/Microtask.cpp \
 	third_party/WebKit/Source/core/dom/MouseEvent.cpp \
 	third_party/WebKit/Source/core/dom/MouseRelatedEvent.cpp \
 	third_party/WebKit/Source/core/dom/MutationEvent.cpp \
@@ -133,7 +136,6 @@
 	third_party/WebKit/Source/core/dom/PseudoElement.cpp \
 	third_party/WebKit/Source/core/dom/QualifiedName.cpp \
 	third_party/WebKit/Source/core/dom/Range.cpp \
-	third_party/WebKit/Source/core/dom/RegisteredEventListener.cpp \
 	third_party/WebKit/Source/core/dom/ResourceProgressEvent.cpp \
 	third_party/WebKit/Source/core/dom/ScopedEventQueue.cpp \
 	third_party/WebKit/Source/core/dom/ScriptElement.cpp \
@@ -147,7 +149,6 @@
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
-	third_party/WebKit/Source/core/dom/StyledElement.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextEvent.cpp \
@@ -181,7 +182,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -216,9 +217,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -239,11 +238,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -258,7 +257,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -281,10 +279,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -306,6 +303,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -329,10 +327,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -344,9 +341,174 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -361,6 +523,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-EL \
+	-Wl,--no-keep-memory \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_dom.target.darwin-x86.mk b/Source/core/webcore_dom.target.darwin-x86.mk
index 84fdf1b..b5936eb 100644
--- a/Source/core/webcore_dom.target.darwin-x86.mk
+++ b/Source/core/webcore_dom.target.darwin-x86.mk
@@ -43,14 +43,16 @@
 	third_party/WebKit/Source/core/dom/CompositionEvent.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNode.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp \
-	third_party/WebKit/Source/core/dom/ContextDestructionObserver.cpp \
+	third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/ContextFeatures.cpp \
+	third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementDefinition.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementCallbackDispatcher.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistry.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.cpp \
 	third_party/WebKit/Source/core/dom/CustomEvent.cpp \
-	third_party/WebKit/Source/core/dom/DOMCoreException.cpp \
 	third_party/WebKit/Source/core/dom/DOMError.cpp \
+	third_party/WebKit/Source/core/dom/DOMException.cpp \
 	third_party/WebKit/Source/core/dom/DOMImplementation.cpp \
 	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
@@ -68,6 +70,7 @@
 	third_party/WebKit/Source/core/dom/DocumentLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/DocumentMarkerController.cpp \
 	third_party/WebKit/Source/core/dom/DocumentMarker.cpp \
+	third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp \
 	third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp \
 	third_party/WebKit/Source/core/dom/DocumentParser.cpp \
 	third_party/WebKit/Source/core/dom/DocumentSharedObjectPool.cpp \
@@ -85,7 +88,6 @@
 	third_party/WebKit/Source/core/dom/EventNames.cpp \
 	third_party/WebKit/Source/core/dom/EventPathWalker.cpp \
 	third_party/WebKit/Source/core/dom/EventTarget.cpp \
-	third_party/WebKit/Source/core/dom/ExceptionBase.cpp \
 	third_party/WebKit/Source/core/dom/ExceptionCodePlaceholder.cpp \
 	third_party/WebKit/Source/core/dom/FocusEvent.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenController.cpp \
@@ -100,6 +102,7 @@
 	third_party/WebKit/Source/core/dom/MessageEvent.cpp \
 	third_party/WebKit/Source/core/dom/MessagePort.cpp \
 	third_party/WebKit/Source/core/dom/MessagePortChannel.cpp \
+	third_party/WebKit/Source/core/dom/Microtask.cpp \
 	third_party/WebKit/Source/core/dom/MouseEvent.cpp \
 	third_party/WebKit/Source/core/dom/MouseRelatedEvent.cpp \
 	third_party/WebKit/Source/core/dom/MutationEvent.cpp \
@@ -133,7 +136,6 @@
 	third_party/WebKit/Source/core/dom/PseudoElement.cpp \
 	third_party/WebKit/Source/core/dom/QualifiedName.cpp \
 	third_party/WebKit/Source/core/dom/Range.cpp \
-	third_party/WebKit/Source/core/dom/RegisteredEventListener.cpp \
 	third_party/WebKit/Source/core/dom/ResourceProgressEvent.cpp \
 	third_party/WebKit/Source/core/dom/ScopedEventQueue.cpp \
 	third_party/WebKit/Source/core/dom/ScriptElement.cpp \
@@ -147,7 +149,6 @@
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
-	third_party/WebKit/Source/core/dom/StyledElement.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextEvent.cpp \
@@ -181,7 +182,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -218,9 +219,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -242,11 +241,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -261,7 +260,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -284,10 +282,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -309,6 +306,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -332,10 +330,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -346,9 +343,178 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -363,6 +529,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-m32 \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_dom.target.linux-arm.mk b/Source/core/webcore_dom.target.linux-arm.mk
index b3345b1..2127fbe 100644
--- a/Source/core/webcore_dom.target.linux-arm.mk
+++ b/Source/core/webcore_dom.target.linux-arm.mk
@@ -43,14 +43,16 @@
 	third_party/WebKit/Source/core/dom/CompositionEvent.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNode.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp \
-	third_party/WebKit/Source/core/dom/ContextDestructionObserver.cpp \
+	third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/ContextFeatures.cpp \
+	third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementDefinition.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementCallbackDispatcher.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistry.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.cpp \
 	third_party/WebKit/Source/core/dom/CustomEvent.cpp \
-	third_party/WebKit/Source/core/dom/DOMCoreException.cpp \
 	third_party/WebKit/Source/core/dom/DOMError.cpp \
+	third_party/WebKit/Source/core/dom/DOMException.cpp \
 	third_party/WebKit/Source/core/dom/DOMImplementation.cpp \
 	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
@@ -68,6 +70,7 @@
 	third_party/WebKit/Source/core/dom/DocumentLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/DocumentMarkerController.cpp \
 	third_party/WebKit/Source/core/dom/DocumentMarker.cpp \
+	third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp \
 	third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp \
 	third_party/WebKit/Source/core/dom/DocumentParser.cpp \
 	third_party/WebKit/Source/core/dom/DocumentSharedObjectPool.cpp \
@@ -85,7 +88,6 @@
 	third_party/WebKit/Source/core/dom/EventNames.cpp \
 	third_party/WebKit/Source/core/dom/EventPathWalker.cpp \
 	third_party/WebKit/Source/core/dom/EventTarget.cpp \
-	third_party/WebKit/Source/core/dom/ExceptionBase.cpp \
 	third_party/WebKit/Source/core/dom/ExceptionCodePlaceholder.cpp \
 	third_party/WebKit/Source/core/dom/FocusEvent.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenController.cpp \
@@ -100,6 +102,7 @@
 	third_party/WebKit/Source/core/dom/MessageEvent.cpp \
 	third_party/WebKit/Source/core/dom/MessagePort.cpp \
 	third_party/WebKit/Source/core/dom/MessagePortChannel.cpp \
+	third_party/WebKit/Source/core/dom/Microtask.cpp \
 	third_party/WebKit/Source/core/dom/MouseEvent.cpp \
 	third_party/WebKit/Source/core/dom/MouseRelatedEvent.cpp \
 	third_party/WebKit/Source/core/dom/MutationEvent.cpp \
@@ -133,7 +136,6 @@
 	third_party/WebKit/Source/core/dom/PseudoElement.cpp \
 	third_party/WebKit/Source/core/dom/QualifiedName.cpp \
 	third_party/WebKit/Source/core/dom/Range.cpp \
-	third_party/WebKit/Source/core/dom/RegisteredEventListener.cpp \
 	third_party/WebKit/Source/core/dom/ResourceProgressEvent.cpp \
 	third_party/WebKit/Source/core/dom/ScopedEventQueue.cpp \
 	third_party/WebKit/Source/core/dom/ScriptElement.cpp \
@@ -147,7 +149,6 @@
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
-	third_party/WebKit/Source/core/dom/StyledElement.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextEvent.cpp \
@@ -181,7 +182,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -216,9 +217,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -240,11 +239,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -259,7 +258,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -282,10 +280,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -307,6 +304,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -330,10 +328,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -345,9 +342,175 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -364,6 +527,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_dom.target.linux-mips.mk b/Source/core/webcore_dom.target.linux-mips.mk
index 5540509..4e8a700 100644
--- a/Source/core/webcore_dom.target.linux-mips.mk
+++ b/Source/core/webcore_dom.target.linux-mips.mk
@@ -43,14 +43,16 @@
 	third_party/WebKit/Source/core/dom/CompositionEvent.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNode.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp \
-	third_party/WebKit/Source/core/dom/ContextDestructionObserver.cpp \
+	third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/ContextFeatures.cpp \
+	third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementDefinition.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementCallbackDispatcher.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistry.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.cpp \
 	third_party/WebKit/Source/core/dom/CustomEvent.cpp \
-	third_party/WebKit/Source/core/dom/DOMCoreException.cpp \
 	third_party/WebKit/Source/core/dom/DOMError.cpp \
+	third_party/WebKit/Source/core/dom/DOMException.cpp \
 	third_party/WebKit/Source/core/dom/DOMImplementation.cpp \
 	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
@@ -68,6 +70,7 @@
 	third_party/WebKit/Source/core/dom/DocumentLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/DocumentMarkerController.cpp \
 	third_party/WebKit/Source/core/dom/DocumentMarker.cpp \
+	third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp \
 	third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp \
 	third_party/WebKit/Source/core/dom/DocumentParser.cpp \
 	third_party/WebKit/Source/core/dom/DocumentSharedObjectPool.cpp \
@@ -85,7 +88,6 @@
 	third_party/WebKit/Source/core/dom/EventNames.cpp \
 	third_party/WebKit/Source/core/dom/EventPathWalker.cpp \
 	third_party/WebKit/Source/core/dom/EventTarget.cpp \
-	third_party/WebKit/Source/core/dom/ExceptionBase.cpp \
 	third_party/WebKit/Source/core/dom/ExceptionCodePlaceholder.cpp \
 	third_party/WebKit/Source/core/dom/FocusEvent.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenController.cpp \
@@ -100,6 +102,7 @@
 	third_party/WebKit/Source/core/dom/MessageEvent.cpp \
 	third_party/WebKit/Source/core/dom/MessagePort.cpp \
 	third_party/WebKit/Source/core/dom/MessagePortChannel.cpp \
+	third_party/WebKit/Source/core/dom/Microtask.cpp \
 	third_party/WebKit/Source/core/dom/MouseEvent.cpp \
 	third_party/WebKit/Source/core/dom/MouseRelatedEvent.cpp \
 	third_party/WebKit/Source/core/dom/MutationEvent.cpp \
@@ -133,7 +136,6 @@
 	third_party/WebKit/Source/core/dom/PseudoElement.cpp \
 	third_party/WebKit/Source/core/dom/QualifiedName.cpp \
 	third_party/WebKit/Source/core/dom/Range.cpp \
-	third_party/WebKit/Source/core/dom/RegisteredEventListener.cpp \
 	third_party/WebKit/Source/core/dom/ResourceProgressEvent.cpp \
 	third_party/WebKit/Source/core/dom/ScopedEventQueue.cpp \
 	third_party/WebKit/Source/core/dom/ScriptElement.cpp \
@@ -147,7 +149,6 @@
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
-	third_party/WebKit/Source/core/dom/StyledElement.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextEvent.cpp \
@@ -181,7 +182,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -216,9 +217,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -239,11 +238,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -258,7 +257,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -281,10 +279,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -306,6 +303,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -329,10 +327,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -344,9 +341,174 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -361,6 +523,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-EL \
+	-Wl,--no-keep-memory \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_dom.target.linux-x86.mk b/Source/core/webcore_dom.target.linux-x86.mk
index 84fdf1b..b5936eb 100644
--- a/Source/core/webcore_dom.target.linux-x86.mk
+++ b/Source/core/webcore_dom.target.linux-x86.mk
@@ -43,14 +43,16 @@
 	third_party/WebKit/Source/core/dom/CompositionEvent.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNode.cpp \
 	third_party/WebKit/Source/core/dom/ContainerNodeAlgorithms.cpp \
-	third_party/WebKit/Source/core/dom/ContextDestructionObserver.cpp \
+	third_party/WebKit/Source/core/dom/ContextLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/ContextFeatures.cpp \
+	third_party/WebKit/Source/core/dom/ContextLifecycleNotifier.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementDefinition.cpp \
+	third_party/WebKit/Source/core/dom/CustomElementCallbackDispatcher.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementRegistry.cpp \
 	third_party/WebKit/Source/core/dom/CustomElementUpgradeCandidateMap.cpp \
 	third_party/WebKit/Source/core/dom/CustomEvent.cpp \
-	third_party/WebKit/Source/core/dom/DOMCoreException.cpp \
 	third_party/WebKit/Source/core/dom/DOMError.cpp \
+	third_party/WebKit/Source/core/dom/DOMException.cpp \
 	third_party/WebKit/Source/core/dom/DOMImplementation.cpp \
 	third_party/WebKit/Source/core/dom/DOMNamedFlowCollection.cpp \
 	third_party/WebKit/Source/core/dom/DOMStringList.cpp \
@@ -68,6 +70,7 @@
 	third_party/WebKit/Source/core/dom/DocumentLifecycleObserver.cpp \
 	third_party/WebKit/Source/core/dom/DocumentMarkerController.cpp \
 	third_party/WebKit/Source/core/dom/DocumentMarker.cpp \
+	third_party/WebKit/Source/core/dom/DocumentOrderedList.cpp \
 	third_party/WebKit/Source/core/dom/DocumentOrderedMap.cpp \
 	third_party/WebKit/Source/core/dom/DocumentParser.cpp \
 	third_party/WebKit/Source/core/dom/DocumentSharedObjectPool.cpp \
@@ -85,7 +88,6 @@
 	third_party/WebKit/Source/core/dom/EventNames.cpp \
 	third_party/WebKit/Source/core/dom/EventPathWalker.cpp \
 	third_party/WebKit/Source/core/dom/EventTarget.cpp \
-	third_party/WebKit/Source/core/dom/ExceptionBase.cpp \
 	third_party/WebKit/Source/core/dom/ExceptionCodePlaceholder.cpp \
 	third_party/WebKit/Source/core/dom/FocusEvent.cpp \
 	third_party/WebKit/Source/core/dom/FullscreenController.cpp \
@@ -100,6 +102,7 @@
 	third_party/WebKit/Source/core/dom/MessageEvent.cpp \
 	third_party/WebKit/Source/core/dom/MessagePort.cpp \
 	third_party/WebKit/Source/core/dom/MessagePortChannel.cpp \
+	third_party/WebKit/Source/core/dom/Microtask.cpp \
 	third_party/WebKit/Source/core/dom/MouseEvent.cpp \
 	third_party/WebKit/Source/core/dom/MouseRelatedEvent.cpp \
 	third_party/WebKit/Source/core/dom/MutationEvent.cpp \
@@ -133,7 +136,6 @@
 	third_party/WebKit/Source/core/dom/PseudoElement.cpp \
 	third_party/WebKit/Source/core/dom/QualifiedName.cpp \
 	third_party/WebKit/Source/core/dom/Range.cpp \
-	third_party/WebKit/Source/core/dom/RegisteredEventListener.cpp \
 	third_party/WebKit/Source/core/dom/ResourceProgressEvent.cpp \
 	third_party/WebKit/Source/core/dom/ScopedEventQueue.cpp \
 	third_party/WebKit/Source/core/dom/ScriptElement.cpp \
@@ -147,7 +149,6 @@
 	third_party/WebKit/Source/core/dom/StaticNodeList.cpp \
 	third_party/WebKit/Source/core/dom/StringCallback.cpp \
 	third_party/WebKit/Source/core/dom/StyleElement.cpp \
-	third_party/WebKit/Source/core/dom/StyledElement.cpp \
 	third_party/WebKit/Source/core/dom/TagNodeList.cpp \
 	third_party/WebKit/Source/core/dom/Text.cpp \
 	third_party/WebKit/Source/core/dom/TextEvent.cpp \
@@ -181,7 +182,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -218,9 +219,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -242,11 +241,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -261,7 +260,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -284,10 +282,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -309,6 +306,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -332,10 +330,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -346,9 +343,178 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -363,6 +529,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-m32 \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_html.target.darwin-arm.mk b/Source/core/webcore_html.target.darwin-arm.mk
index d898651..4a85e31 100644
--- a/Source/core/webcore_html.target.darwin-arm.mk
+++ b/Source/core/webcore_html.target.darwin-arm.mk
@@ -285,7 +285,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -320,9 +320,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -344,11 +342,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -363,7 +361,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -386,10 +383,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -411,6 +407,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -434,10 +431,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -449,9 +445,175 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -468,6 +630,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_html.target.darwin-mips.mk b/Source/core/webcore_html.target.darwin-mips.mk
index 84dc0f2..58c87fb 100644
--- a/Source/core/webcore_html.target.darwin-mips.mk
+++ b/Source/core/webcore_html.target.darwin-mips.mk
@@ -285,7 +285,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -320,9 +320,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -343,11 +341,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -362,7 +360,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -385,10 +382,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -410,6 +406,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -433,10 +430,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -448,9 +444,174 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -465,6 +626,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-EL \
+	-Wl,--no-keep-memory \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_html.target.darwin-x86.mk b/Source/core/webcore_html.target.darwin-x86.mk
index 0cb7149..787c818 100644
--- a/Source/core/webcore_html.target.darwin-x86.mk
+++ b/Source/core/webcore_html.target.darwin-x86.mk
@@ -285,7 +285,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -322,9 +322,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -346,11 +344,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -365,7 +363,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -388,10 +385,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -413,6 +409,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -436,10 +433,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -450,9 +446,178 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -467,6 +632,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-m32 \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_html.target.linux-arm.mk b/Source/core/webcore_html.target.linux-arm.mk
index d898651..4a85e31 100644
--- a/Source/core/webcore_html.target.linux-arm.mk
+++ b/Source/core/webcore_html.target.linux-arm.mk
@@ -285,7 +285,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -320,9 +320,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -344,11 +342,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -363,7 +361,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -386,10 +383,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -411,6 +407,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -434,10 +431,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -449,9 +445,175 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -468,6 +630,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_html.target.linux-mips.mk b/Source/core/webcore_html.target.linux-mips.mk
index 84dc0f2..58c87fb 100644
--- a/Source/core/webcore_html.target.linux-mips.mk
+++ b/Source/core/webcore_html.target.linux-mips.mk
@@ -285,7 +285,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -320,9 +320,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -343,11 +341,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -362,7 +360,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -385,10 +382,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -410,6 +406,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -433,10 +430,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -448,9 +444,174 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -465,6 +626,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-EL \
+	-Wl,--no-keep-memory \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_html.target.linux-x86.mk b/Source/core/webcore_html.target.linux-x86.mk
index 0cb7149..787c818 100644
--- a/Source/core/webcore_html.target.linux-x86.mk
+++ b/Source/core/webcore_html.target.linux-x86.mk
@@ -285,7 +285,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -322,9 +322,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -346,11 +344,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -365,7 +363,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -388,10 +385,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -413,6 +409,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -436,10 +433,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -450,9 +446,178 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -467,6 +632,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-m32 \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_platform.target.darwin-arm.mk b/Source/core/webcore_platform.target.darwin-arm.mk
index cdd3322..6d32bc2 100644
--- a/Source/core/webcore_platform.target.darwin-arm.mk
+++ b/Source/core/webcore_platform.target.darwin-arm.mk
@@ -39,6 +39,7 @@
 	third_party/WebKit/Source/core/platform/EventTracer.cpp \
 	third_party/WebKit/Source/core/platform/FileChooser.cpp \
 	third_party/WebKit/Source/core/platform/FileIconLoader.cpp \
+	third_party/WebKit/Source/core/platform/JSONValues.cpp \
 	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
 	third_party/WebKit/Source/core/platform/Language.cpp \
 	third_party/WebKit/Source/core/platform/LayoutTestSupport.cpp \
@@ -48,6 +49,7 @@
 	third_party/WebKit/Source/core/platform/Logging.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
+	third_party/WebKit/Source/core/platform/Partitions.cpp \
 	third_party/WebKit/Source/core/platform/PlatformEvent.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformMemoryInstrumentation.cpp \
@@ -118,7 +120,6 @@
 	third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ClipboardMimeTypes.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/DragImageChromiumSkia.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FileSystemChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FileSystemChromiumLinux.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
@@ -253,8 +254,8 @@
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/FontCustomPlatformData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/skia/FontPlatformDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp \
-	third_party/WebKit/Source/core/platform/graphics/skia/ImageBufferSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/ImageSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/MemoryInstrumentationSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.cpp \
@@ -272,6 +273,7 @@
 	third_party/WebKit/Source/core/platform/graphics/transforms/TransformState.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.cpp \
+	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageReader.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp \
@@ -279,7 +281,6 @@
 	third_party/WebKit/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp \
-	third_party/WebKit/Source/core/platform/image-decoders/skia/ImageDecoderSkia.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/JPEGImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp \
@@ -291,14 +292,13 @@
 	third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
+	third_party/WebKit/Source/core/platform/midi/MIDIAccessor.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceMotionClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.cpp \
 	third_party/WebKit/Source/core/platform/network/BlobData.cpp \
-	third_party/WebKit/Source/core/platform/network/BlobRegistry.cpp \
-	third_party/WebKit/Source/core/platform/network/BlobRegistryProxy.cpp \
 	third_party/WebKit/Source/core/platform/network/DNS.cpp \
 	third_party/WebKit/Source/core/platform/network/FormData.cpp \
 	third_party/WebKit/Source/core/platform/network/FormDataBuilder.cpp \
@@ -344,7 +344,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -379,9 +379,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -403,11 +401,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -422,7 +420,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -445,10 +442,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -470,6 +466,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -494,10 +491,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -509,9 +505,176 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(LOCAL_PATH)/third_party/harfbuzz-ng/src \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -528,6 +691,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_platform.target.darwin-mips.mk b/Source/core/webcore_platform.target.darwin-mips.mk
index a47a080..8e5d890 100644
--- a/Source/core/webcore_platform.target.darwin-mips.mk
+++ b/Source/core/webcore_platform.target.darwin-mips.mk
@@ -39,6 +39,7 @@
 	third_party/WebKit/Source/core/platform/EventTracer.cpp \
 	third_party/WebKit/Source/core/platform/FileChooser.cpp \
 	third_party/WebKit/Source/core/platform/FileIconLoader.cpp \
+	third_party/WebKit/Source/core/platform/JSONValues.cpp \
 	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
 	third_party/WebKit/Source/core/platform/Language.cpp \
 	third_party/WebKit/Source/core/platform/LayoutTestSupport.cpp \
@@ -48,6 +49,7 @@
 	third_party/WebKit/Source/core/platform/Logging.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
+	third_party/WebKit/Source/core/platform/Partitions.cpp \
 	third_party/WebKit/Source/core/platform/PlatformEvent.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformMemoryInstrumentation.cpp \
@@ -118,7 +120,6 @@
 	third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ClipboardMimeTypes.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/DragImageChromiumSkia.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FileSystemChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FileSystemChromiumLinux.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
@@ -253,8 +254,8 @@
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/FontCustomPlatformData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/skia/FontPlatformDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp \
-	third_party/WebKit/Source/core/platform/graphics/skia/ImageBufferSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/ImageSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/MemoryInstrumentationSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.cpp \
@@ -272,6 +273,7 @@
 	third_party/WebKit/Source/core/platform/graphics/transforms/TransformState.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.cpp \
+	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageReader.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp \
@@ -279,7 +281,6 @@
 	third_party/WebKit/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp \
-	third_party/WebKit/Source/core/platform/image-decoders/skia/ImageDecoderSkia.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/JPEGImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp \
@@ -291,14 +292,13 @@
 	third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
+	third_party/WebKit/Source/core/platform/midi/MIDIAccessor.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceMotionClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.cpp \
 	third_party/WebKit/Source/core/platform/network/BlobData.cpp \
-	third_party/WebKit/Source/core/platform/network/BlobRegistry.cpp \
-	third_party/WebKit/Source/core/platform/network/BlobRegistryProxy.cpp \
 	third_party/WebKit/Source/core/platform/network/DNS.cpp \
 	third_party/WebKit/Source/core/platform/network/FormData.cpp \
 	third_party/WebKit/Source/core/platform/network/FormDataBuilder.cpp \
@@ -344,7 +344,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -379,9 +379,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -402,11 +400,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -421,7 +419,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -444,10 +441,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -469,6 +465,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -493,10 +490,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -508,9 +504,175 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(LOCAL_PATH)/third_party/harfbuzz-ng/src \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -525,6 +687,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-EL \
+	-Wl,--no-keep-memory \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_platform.target.darwin-x86.mk b/Source/core/webcore_platform.target.darwin-x86.mk
index b7d4dc9..3933698 100644
--- a/Source/core/webcore_platform.target.darwin-x86.mk
+++ b/Source/core/webcore_platform.target.darwin-x86.mk
@@ -39,6 +39,7 @@
 	third_party/WebKit/Source/core/platform/EventTracer.cpp \
 	third_party/WebKit/Source/core/platform/FileChooser.cpp \
 	third_party/WebKit/Source/core/platform/FileIconLoader.cpp \
+	third_party/WebKit/Source/core/platform/JSONValues.cpp \
 	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
 	third_party/WebKit/Source/core/platform/Language.cpp \
 	third_party/WebKit/Source/core/platform/LayoutTestSupport.cpp \
@@ -48,6 +49,7 @@
 	third_party/WebKit/Source/core/platform/Logging.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
+	third_party/WebKit/Source/core/platform/Partitions.cpp \
 	third_party/WebKit/Source/core/platform/PlatformEvent.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformMemoryInstrumentation.cpp \
@@ -118,7 +120,6 @@
 	third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ClipboardMimeTypes.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/DragImageChromiumSkia.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FileSystemChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FileSystemChromiumLinux.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
@@ -253,8 +254,8 @@
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/FontCustomPlatformData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/skia/FontPlatformDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp \
-	third_party/WebKit/Source/core/platform/graphics/skia/ImageBufferSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/ImageSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/MemoryInstrumentationSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.cpp \
@@ -272,6 +273,7 @@
 	third_party/WebKit/Source/core/platform/graphics/transforms/TransformState.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.cpp \
+	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageReader.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp \
@@ -279,7 +281,6 @@
 	third_party/WebKit/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp \
-	third_party/WebKit/Source/core/platform/image-decoders/skia/ImageDecoderSkia.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/JPEGImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp \
@@ -291,14 +292,13 @@
 	third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
+	third_party/WebKit/Source/core/platform/midi/MIDIAccessor.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceMotionClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.cpp \
 	third_party/WebKit/Source/core/platform/network/BlobData.cpp \
-	third_party/WebKit/Source/core/platform/network/BlobRegistry.cpp \
-	third_party/WebKit/Source/core/platform/network/BlobRegistryProxy.cpp \
 	third_party/WebKit/Source/core/platform/network/DNS.cpp \
 	third_party/WebKit/Source/core/platform/network/FormData.cpp \
 	third_party/WebKit/Source/core/platform/network/FormDataBuilder.cpp \
@@ -344,7 +344,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -381,9 +381,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -405,11 +403,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -424,7 +422,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -447,10 +444,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -472,6 +468,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -496,10 +493,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -510,9 +506,179 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(LOCAL_PATH)/third_party/harfbuzz-ng/src \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -527,6 +693,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-m32 \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_platform.target.linux-arm.mk b/Source/core/webcore_platform.target.linux-arm.mk
index cdd3322..6d32bc2 100644
--- a/Source/core/webcore_platform.target.linux-arm.mk
+++ b/Source/core/webcore_platform.target.linux-arm.mk
@@ -39,6 +39,7 @@
 	third_party/WebKit/Source/core/platform/EventTracer.cpp \
 	third_party/WebKit/Source/core/platform/FileChooser.cpp \
 	third_party/WebKit/Source/core/platform/FileIconLoader.cpp \
+	third_party/WebKit/Source/core/platform/JSONValues.cpp \
 	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
 	third_party/WebKit/Source/core/platform/Language.cpp \
 	third_party/WebKit/Source/core/platform/LayoutTestSupport.cpp \
@@ -48,6 +49,7 @@
 	third_party/WebKit/Source/core/platform/Logging.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
+	third_party/WebKit/Source/core/platform/Partitions.cpp \
 	third_party/WebKit/Source/core/platform/PlatformEvent.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformMemoryInstrumentation.cpp \
@@ -118,7 +120,6 @@
 	third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ClipboardMimeTypes.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/DragImageChromiumSkia.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FileSystemChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FileSystemChromiumLinux.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
@@ -253,8 +254,8 @@
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/FontCustomPlatformData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/skia/FontPlatformDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp \
-	third_party/WebKit/Source/core/platform/graphics/skia/ImageBufferSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/ImageSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/MemoryInstrumentationSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.cpp \
@@ -272,6 +273,7 @@
 	third_party/WebKit/Source/core/platform/graphics/transforms/TransformState.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.cpp \
+	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageReader.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp \
@@ -279,7 +281,6 @@
 	third_party/WebKit/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp \
-	third_party/WebKit/Source/core/platform/image-decoders/skia/ImageDecoderSkia.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/JPEGImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp \
@@ -291,14 +292,13 @@
 	third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
+	third_party/WebKit/Source/core/platform/midi/MIDIAccessor.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceMotionClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.cpp \
 	third_party/WebKit/Source/core/platform/network/BlobData.cpp \
-	third_party/WebKit/Source/core/platform/network/BlobRegistry.cpp \
-	third_party/WebKit/Source/core/platform/network/BlobRegistryProxy.cpp \
 	third_party/WebKit/Source/core/platform/network/DNS.cpp \
 	third_party/WebKit/Source/core/platform/network/FormData.cpp \
 	third_party/WebKit/Source/core/platform/network/FormDataBuilder.cpp \
@@ -344,7 +344,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -379,9 +379,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -403,11 +401,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -422,7 +420,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -445,10 +442,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -470,6 +466,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -494,10 +491,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -509,9 +505,176 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(LOCAL_PATH)/third_party/harfbuzz-ng/src \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -528,6 +691,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_platform.target.linux-mips.mk b/Source/core/webcore_platform.target.linux-mips.mk
index a47a080..8e5d890 100644
--- a/Source/core/webcore_platform.target.linux-mips.mk
+++ b/Source/core/webcore_platform.target.linux-mips.mk
@@ -39,6 +39,7 @@
 	third_party/WebKit/Source/core/platform/EventTracer.cpp \
 	third_party/WebKit/Source/core/platform/FileChooser.cpp \
 	third_party/WebKit/Source/core/platform/FileIconLoader.cpp \
+	third_party/WebKit/Source/core/platform/JSONValues.cpp \
 	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
 	third_party/WebKit/Source/core/platform/Language.cpp \
 	third_party/WebKit/Source/core/platform/LayoutTestSupport.cpp \
@@ -48,6 +49,7 @@
 	third_party/WebKit/Source/core/platform/Logging.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
+	third_party/WebKit/Source/core/platform/Partitions.cpp \
 	third_party/WebKit/Source/core/platform/PlatformEvent.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformMemoryInstrumentation.cpp \
@@ -118,7 +120,6 @@
 	third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ClipboardMimeTypes.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/DragImageChromiumSkia.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FileSystemChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FileSystemChromiumLinux.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
@@ -253,8 +254,8 @@
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/FontCustomPlatformData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/skia/FontPlatformDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp \
-	third_party/WebKit/Source/core/platform/graphics/skia/ImageBufferSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/ImageSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/MemoryInstrumentationSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.cpp \
@@ -272,6 +273,7 @@
 	third_party/WebKit/Source/core/platform/graphics/transforms/TransformState.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.cpp \
+	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageReader.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp \
@@ -279,7 +281,6 @@
 	third_party/WebKit/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp \
-	third_party/WebKit/Source/core/platform/image-decoders/skia/ImageDecoderSkia.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/JPEGImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp \
@@ -291,14 +292,13 @@
 	third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
+	third_party/WebKit/Source/core/platform/midi/MIDIAccessor.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceMotionClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.cpp \
 	third_party/WebKit/Source/core/platform/network/BlobData.cpp \
-	third_party/WebKit/Source/core/platform/network/BlobRegistry.cpp \
-	third_party/WebKit/Source/core/platform/network/BlobRegistryProxy.cpp \
 	third_party/WebKit/Source/core/platform/network/DNS.cpp \
 	third_party/WebKit/Source/core/platform/network/FormData.cpp \
 	third_party/WebKit/Source/core/platform/network/FormDataBuilder.cpp \
@@ -344,7 +344,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -379,9 +379,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -402,11 +400,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -421,7 +419,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -444,10 +441,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -469,6 +465,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -493,10 +490,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -508,9 +504,175 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(LOCAL_PATH)/third_party/harfbuzz-ng/src \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -525,6 +687,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-EL \
+	-Wl,--no-keep-memory \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_platform.target.linux-x86.mk b/Source/core/webcore_platform.target.linux-x86.mk
index b7d4dc9..3933698 100644
--- a/Source/core/webcore_platform.target.linux-x86.mk
+++ b/Source/core/webcore_platform.target.linux-x86.mk
@@ -39,6 +39,7 @@
 	third_party/WebKit/Source/core/platform/EventTracer.cpp \
 	third_party/WebKit/Source/core/platform/FileChooser.cpp \
 	third_party/WebKit/Source/core/platform/FileIconLoader.cpp \
+	third_party/WebKit/Source/core/platform/JSONValues.cpp \
 	third_party/WebKit/Source/core/platform/KillRingNone.cpp \
 	third_party/WebKit/Source/core/platform/Language.cpp \
 	third_party/WebKit/Source/core/platform/LayoutTestSupport.cpp \
@@ -48,6 +49,7 @@
 	third_party/WebKit/Source/core/platform/Logging.cpp \
 	third_party/WebKit/Source/core/platform/MIMETypeFromURL.cpp \
 	third_party/WebKit/Source/core/platform/NotImplemented.cpp \
+	third_party/WebKit/Source/core/platform/Partitions.cpp \
 	third_party/WebKit/Source/core/platform/PlatformEvent.cpp \
 	third_party/WebKit/Source/core/platform/PlatformInstrumentation.cpp \
 	third_party/WebKit/Source/core/platform/PlatformMemoryInstrumentation.cpp \
@@ -118,7 +120,6 @@
 	third_party/WebKit/Source/core/platform/chromium/ClipboardChromiumPosix.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ClipboardMimeTypes.cpp \
 	third_party/WebKit/Source/core/platform/chromium/ClipboardUtilitiesChromium.cpp \
-	third_party/WebKit/Source/core/platform/chromium/DragImageChromiumSkia.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FileSystemChromium.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FileSystemChromiumLinux.cpp \
 	third_party/WebKit/Source/core/platform/chromium/FramelessScrollView.cpp \
@@ -253,8 +254,8 @@
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeSanitizer.cpp \
 	third_party/WebKit/Source/core/platform/graphics/opentype/OpenTypeVerticalData.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/FontCustomPlatformData.cpp \
+	third_party/WebKit/Source/core/platform/graphics/skia/FontPlatformDataSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/GlyphPageTreeNodeSkia.cpp \
-	third_party/WebKit/Source/core/platform/graphics/skia/ImageBufferSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/ImageSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/MemoryInstrumentationSkia.cpp \
 	third_party/WebKit/Source/core/platform/graphics/skia/NativeImageSkia.cpp \
@@ -272,6 +273,7 @@
 	third_party/WebKit/Source/core/platform/graphics/transforms/TransformState.cpp \
 	third_party/WebKit/Source/core/platform/graphics/transforms/TranslateTransformOperation.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/ImageDecoder.cpp \
+	third_party/WebKit/Source/core/platform/image-decoders/ImageFrame.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/bmp/BMPImageReader.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/gif/GIFImageDecoder.cpp \
@@ -279,7 +281,6 @@
 	third_party/WebKit/Source/core/platform/image-decoders/ico/ICOImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/jpeg/JPEGImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/png/PNGImageDecoder.cpp \
-	third_party/WebKit/Source/core/platform/image-decoders/skia/ImageDecoderSkia.cpp \
 	third_party/WebKit/Source/core/platform/image-decoders/webp/WEBPImageDecoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/JPEGImageEncoder.cpp \
 	third_party/WebKit/Source/core/platform/image-encoders/skia/PNGImageEncoder.cpp \
@@ -291,14 +292,13 @@
 	third_party/WebKit/Source/core/platform/mediastream/RTCDTMFSenderHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCDataChannelHandler.cpp \
 	third_party/WebKit/Source/core/platform/mediastream/RTCPeerConnectionHandler.cpp \
+	third_party/WebKit/Source/core/platform/midi/MIDIAccessor.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceMotionClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/DeviceOrientationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/GeolocationClientMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/PlatformSpeechSynthesizerMock.cpp \
 	third_party/WebKit/Source/core/platform/mock/ScrollbarThemeMock.cpp \
 	third_party/WebKit/Source/core/platform/network/BlobData.cpp \
-	third_party/WebKit/Source/core/platform/network/BlobRegistry.cpp \
-	third_party/WebKit/Source/core/platform/network/BlobRegistryProxy.cpp \
 	third_party/WebKit/Source/core/platform/network/DNS.cpp \
 	third_party/WebKit/Source/core/platform/network/FormData.cpp \
 	third_party/WebKit/Source/core/platform/network/FormDataBuilder.cpp \
@@ -344,7 +344,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -381,9 +381,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -405,11 +403,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -424,7 +422,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -447,10 +444,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -472,6 +468,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -496,10 +493,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -510,9 +506,179 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(LOCAL_PATH)/third_party/harfbuzz-ng/src \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -527,6 +693,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-m32 \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_platform_geometry.target.darwin-arm.mk b/Source/core/webcore_platform_geometry.target.darwin-arm.mk
index 2999d52..308c04c 100644
--- a/Source/core/webcore_platform_geometry.target.darwin-arm.mk
+++ b/Source/core/webcore_platform_geometry.target.darwin-arm.mk
@@ -38,7 +38,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -73,9 +73,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -97,11 +95,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -116,7 +114,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -139,10 +136,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -164,6 +160,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -187,10 +184,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -202,9 +198,175 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -221,6 +383,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_platform_geometry.target.darwin-mips.mk b/Source/core/webcore_platform_geometry.target.darwin-mips.mk
index 5dc3c06..4f47789 100644
--- a/Source/core/webcore_platform_geometry.target.darwin-mips.mk
+++ b/Source/core/webcore_platform_geometry.target.darwin-mips.mk
@@ -38,7 +38,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -73,9 +73,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -96,11 +94,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -115,7 +113,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -138,10 +135,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -163,6 +159,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -186,10 +183,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -201,9 +197,174 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -218,6 +379,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-EL \
+	-Wl,--no-keep-memory \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_platform_geometry.target.darwin-x86.mk b/Source/core/webcore_platform_geometry.target.darwin-x86.mk
index de5ab8e..9ae7c3c 100644
--- a/Source/core/webcore_platform_geometry.target.darwin-x86.mk
+++ b/Source/core/webcore_platform_geometry.target.darwin-x86.mk
@@ -38,7 +38,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -75,9 +75,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -99,11 +97,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -118,7 +116,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -141,10 +138,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -166,6 +162,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -189,10 +186,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -203,9 +199,178 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -220,6 +385,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-m32 \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_platform_geometry.target.linux-arm.mk b/Source/core/webcore_platform_geometry.target.linux-arm.mk
index 2999d52..308c04c 100644
--- a/Source/core/webcore_platform_geometry.target.linux-arm.mk
+++ b/Source/core/webcore_platform_geometry.target.linux-arm.mk
@@ -38,7 +38,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -73,9 +73,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -97,11 +95,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -116,7 +114,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -139,10 +136,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -164,6 +160,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -187,10 +184,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -202,9 +198,175 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -221,6 +383,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_platform_geometry.target.linux-mips.mk b/Source/core/webcore_platform_geometry.target.linux-mips.mk
index 5dc3c06..4f47789 100644
--- a/Source/core/webcore_platform_geometry.target.linux-mips.mk
+++ b/Source/core/webcore_platform_geometry.target.linux-mips.mk
@@ -38,7 +38,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -73,9 +73,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -96,11 +94,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -115,7 +113,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -138,10 +135,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -163,6 +159,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -186,10 +183,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -201,9 +197,174 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -218,6 +379,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-EL \
+	-Wl,--no-keep-memory \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_platform_geometry.target.linux-x86.mk b/Source/core/webcore_platform_geometry.target.linux-x86.mk
index de5ab8e..9ae7c3c 100644
--- a/Source/core/webcore_platform_geometry.target.linux-x86.mk
+++ b/Source/core/webcore_platform_geometry.target.linux-x86.mk
@@ -38,7 +38,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -75,9 +75,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -99,11 +97,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -118,7 +116,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -141,10 +138,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -166,6 +162,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -189,10 +186,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -203,9 +199,178 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -220,6 +385,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-m32 \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_prerequisites.target.darwin-arm.mk b/Source/core/webcore_prerequisites.target.darwin-arm.mk
index bd8d641..e299d16 100644
--- a/Source/core/webcore_prerequisites.target.darwin-arm.mk
+++ b/Source/core/webcore_prerequisites.target.darwin-arm.mk
@@ -18,8 +18,8 @@
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_weborigin_weborigin_gyp)/third_party_WebKit_Source_weborigin_weborigin_gyp.a \
diff --git a/Source/core/webcore_prerequisites.target.darwin-mips.mk b/Source/core/webcore_prerequisites.target.darwin-mips.mk
index bd8d641..e299d16 100644
--- a/Source/core/webcore_prerequisites.target.darwin-mips.mk
+++ b/Source/core/webcore_prerequisites.target.darwin-mips.mk
@@ -18,8 +18,8 @@
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_weborigin_weborigin_gyp)/third_party_WebKit_Source_weborigin_weborigin_gyp.a \
diff --git a/Source/core/webcore_prerequisites.target.darwin-x86.mk b/Source/core/webcore_prerequisites.target.darwin-x86.mk
index bd8d641..e299d16 100644
--- a/Source/core/webcore_prerequisites.target.darwin-x86.mk
+++ b/Source/core/webcore_prerequisites.target.darwin-x86.mk
@@ -18,8 +18,8 @@
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_weborigin_weborigin_gyp)/third_party_WebKit_Source_weborigin_weborigin_gyp.a \
diff --git a/Source/core/webcore_prerequisites.target.linux-arm.mk b/Source/core/webcore_prerequisites.target.linux-arm.mk
index bd8d641..e299d16 100644
--- a/Source/core/webcore_prerequisites.target.linux-arm.mk
+++ b/Source/core/webcore_prerequisites.target.linux-arm.mk
@@ -18,8 +18,8 @@
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_weborigin_weborigin_gyp)/third_party_WebKit_Source_weborigin_weborigin_gyp.a \
diff --git a/Source/core/webcore_prerequisites.target.linux-mips.mk b/Source/core/webcore_prerequisites.target.linux-mips.mk
index bd8d641..e299d16 100644
--- a/Source/core/webcore_prerequisites.target.linux-mips.mk
+++ b/Source/core/webcore_prerequisites.target.linux-mips.mk
@@ -18,8 +18,8 @@
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_weborigin_weborigin_gyp)/third_party_WebKit_Source_weborigin_weborigin_gyp.a \
diff --git a/Source/core/webcore_prerequisites.target.linux-x86.mk b/Source/core/webcore_prerequisites.target.linux-x86.mk
index bd8d641..e299d16 100644
--- a/Source/core/webcore_prerequisites.target.linux-x86.mk
+++ b/Source/core/webcore_prerequisites.target.linux-x86.mk
@@ -18,8 +18,8 @@
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_overlay_page_gyp)/inspector_overlay_page.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_protocol_sources_gyp)/inspector_protocol_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_inspector_instrumentation_sources_gyp)/inspector_instrumentation_sources.stamp \
-	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_bindings_bindings_derived_sources_gyp)/bindings_derived_sources.stamp \
+	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_core_make_derived_sources_gyp)/make_derived_sources.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_wtf_wtf_gyp)/third_party_WebKit_Source_wtf_wtf_gyp.a \
 	$(call intermediates-dir-for,GYP,third_party_WebKit_Source_config_gyp)/config.stamp \
 	$(call intermediates-dir-for,STATIC_LIBRARIES,third_party_WebKit_Source_weborigin_weborigin_gyp)/third_party_WebKit_Source_weborigin_weborigin_gyp.a \
diff --git a/Source/core/webcore_remaining.target.darwin-arm.mk b/Source/core/webcore_remaining.target.darwin-arm.mk
index 5318e9a..3c68171 100644
--- a/Source/core/webcore_remaining.target.darwin-arm.mk
+++ b/Source/core/webcore_remaining.target.darwin-arm.mk
@@ -109,7 +109,6 @@
 	third_party/WebKit/Source/core/css/CSSSelector.cpp \
 	third_party/WebKit/Source/core/css/CSSSelectorList.cpp \
 	third_party/WebKit/Source/core/css/CSSShaderValue.cpp \
-	third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleRule.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleSheet.cpp \
 	third_party/WebKit/Source/core/css/CSSSupportsRule.cpp \
@@ -162,11 +161,13 @@
 	third_party/WebKit/Source/core/css/StyleSheet.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
+	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp \
+	third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp \
 	third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp \
 	third_party/WebKit/Source/core/editing/AppendNodeCommand.cpp \
@@ -222,19 +223,19 @@
 	third_party/WebKit/Source/core/editing/VisibleUnits.cpp \
 	third_party/WebKit/Source/core/editing/WrapContentsInDummySpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
-	third_party/WebKit/Source/core/editing/chromium/FrameSelectionChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
+	third_party/WebKit/Source/core/fileapi/BlobRegistry.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobURL.cpp \
 	third_party/WebKit/Source/core/fileapi/File.cpp \
-	third_party/WebKit/Source/core/fileapi/FileException.cpp \
+	third_party/WebKit/Source/core/fileapi/FileError.cpp \
 	third_party/WebKit/Source/core/fileapi/FileList.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp \
-	third_party/WebKit/Source/core/fileapi/ThreadableBlobRegistry.cpp \
+	third_party/WebKit/Source/core/fileapi/Stream.cpp \
 	third_party/WebKit/Source/core/history/BackForwardController.cpp \
 	third_party/WebKit/Source/core/history/HistoryItem.cpp \
 	third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp \
@@ -283,9 +284,9 @@
 	third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorStyleTextEditor.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorValues.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
+	third_party/WebKit/Source/core/inspector/JSONParser.cpp \
 	third_party/WebKit/Source/core/inspector/MemoryInstrumentationImpl.cpp \
 	third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp \
 	third_party/WebKit/Source/core/inspector/PageConsoleAgent.cpp \
@@ -321,6 +322,7 @@
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
 	third_party/WebKit/Source/core/loader/NavigationAction.cpp \
+	third_party/WebKit/Source/core/loader/NavigationPolicy.cpp \
 	third_party/WebKit/Source/core/loader/NavigationScheduler.cpp \
 	third_party/WebKit/Source/core/loader/PingLoader.cpp \
 	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
@@ -332,6 +334,7 @@
 	third_party/WebKit/Source/core/loader/SubframeLoader.cpp \
 	third_party/WebKit/Source/core/loader/SubstituteData.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
+	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
@@ -379,7 +382,6 @@
 	third_party/WebKit/Source/core/page/FrameDestructionObserver.cpp \
 	third_party/WebKit/Source/core/page/FrameTree.cpp \
 	third_party/WebKit/Source/core/page/FrameView.cpp \
-	third_party/WebKit/Source/core/page/GroupSettings.cpp \
 	third_party/WebKit/Source/core/page/History.cpp \
 	third_party/WebKit/Source/core/page/Location.cpp \
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
@@ -439,15 +441,15 @@
 	third_party/WebKit/Source/core/storage/Storage.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
-	third_party/WebKit/Source/core/workers/DedicatedWorkerContext.cpp \
+	third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/SharedWorker.cpp \
-	third_party/WebKit/Source/core/workers/SharedWorkerContext.cpp \
+	third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/Worker.cpp \
-	third_party/WebKit/Source/core/workers/WorkerContext.cpp \
-	third_party/WebKit/Source/core/workers/WorkerContextProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/WorkerLocation.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
@@ -464,7 +466,6 @@
 	third_party/WebKit/Source/core/xml/XMLSerializer.cpp \
 	third_party/WebKit/Source/core/xml/XMLTreeViewer.cpp \
 	third_party/WebKit/Source/core/xml/XPathEvaluator.cpp \
-	third_party/WebKit/Source/core/xml/XPathException.cpp \
 	third_party/WebKit/Source/core/xml/XPathExpression.cpp \
 	third_party/WebKit/Source/core/xml/XPathExpressionNode.cpp \
 	third_party/WebKit/Source/core/xml/XPathFunctions.cpp \
@@ -487,7 +488,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -523,9 +524,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -547,11 +546,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -566,7 +565,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -589,10 +587,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -615,6 +612,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -638,10 +636,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -653,9 +650,177 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-fno-strict-aliasing \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -672,6 +837,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_remaining.target.darwin-mips.mk b/Source/core/webcore_remaining.target.darwin-mips.mk
index 53dfec8..deb57fa 100644
--- a/Source/core/webcore_remaining.target.darwin-mips.mk
+++ b/Source/core/webcore_remaining.target.darwin-mips.mk
@@ -109,7 +109,6 @@
 	third_party/WebKit/Source/core/css/CSSSelector.cpp \
 	third_party/WebKit/Source/core/css/CSSSelectorList.cpp \
 	third_party/WebKit/Source/core/css/CSSShaderValue.cpp \
-	third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleRule.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleSheet.cpp \
 	third_party/WebKit/Source/core/css/CSSSupportsRule.cpp \
@@ -162,11 +161,13 @@
 	third_party/WebKit/Source/core/css/StyleSheet.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
+	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp \
+	third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp \
 	third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp \
 	third_party/WebKit/Source/core/editing/AppendNodeCommand.cpp \
@@ -222,19 +223,19 @@
 	third_party/WebKit/Source/core/editing/VisibleUnits.cpp \
 	third_party/WebKit/Source/core/editing/WrapContentsInDummySpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
-	third_party/WebKit/Source/core/editing/chromium/FrameSelectionChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
+	third_party/WebKit/Source/core/fileapi/BlobRegistry.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobURL.cpp \
 	third_party/WebKit/Source/core/fileapi/File.cpp \
-	third_party/WebKit/Source/core/fileapi/FileException.cpp \
+	third_party/WebKit/Source/core/fileapi/FileError.cpp \
 	third_party/WebKit/Source/core/fileapi/FileList.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp \
-	third_party/WebKit/Source/core/fileapi/ThreadableBlobRegistry.cpp \
+	third_party/WebKit/Source/core/fileapi/Stream.cpp \
 	third_party/WebKit/Source/core/history/BackForwardController.cpp \
 	third_party/WebKit/Source/core/history/HistoryItem.cpp \
 	third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp \
@@ -283,9 +284,9 @@
 	third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorStyleTextEditor.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorValues.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
+	third_party/WebKit/Source/core/inspector/JSONParser.cpp \
 	third_party/WebKit/Source/core/inspector/MemoryInstrumentationImpl.cpp \
 	third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp \
 	third_party/WebKit/Source/core/inspector/PageConsoleAgent.cpp \
@@ -321,6 +322,7 @@
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
 	third_party/WebKit/Source/core/loader/NavigationAction.cpp \
+	third_party/WebKit/Source/core/loader/NavigationPolicy.cpp \
 	third_party/WebKit/Source/core/loader/NavigationScheduler.cpp \
 	third_party/WebKit/Source/core/loader/PingLoader.cpp \
 	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
@@ -332,6 +334,7 @@
 	third_party/WebKit/Source/core/loader/SubframeLoader.cpp \
 	third_party/WebKit/Source/core/loader/SubstituteData.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
+	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
@@ -379,7 +382,6 @@
 	third_party/WebKit/Source/core/page/FrameDestructionObserver.cpp \
 	third_party/WebKit/Source/core/page/FrameTree.cpp \
 	third_party/WebKit/Source/core/page/FrameView.cpp \
-	third_party/WebKit/Source/core/page/GroupSettings.cpp \
 	third_party/WebKit/Source/core/page/History.cpp \
 	third_party/WebKit/Source/core/page/Location.cpp \
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
@@ -439,15 +441,15 @@
 	third_party/WebKit/Source/core/storage/Storage.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
-	third_party/WebKit/Source/core/workers/DedicatedWorkerContext.cpp \
+	third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/SharedWorker.cpp \
-	third_party/WebKit/Source/core/workers/SharedWorkerContext.cpp \
+	third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/Worker.cpp \
-	third_party/WebKit/Source/core/workers/WorkerContext.cpp \
-	third_party/WebKit/Source/core/workers/WorkerContextProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/WorkerLocation.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
@@ -464,7 +466,6 @@
 	third_party/WebKit/Source/core/xml/XMLSerializer.cpp \
 	third_party/WebKit/Source/core/xml/XMLTreeViewer.cpp \
 	third_party/WebKit/Source/core/xml/XPathEvaluator.cpp \
-	third_party/WebKit/Source/core/xml/XPathException.cpp \
 	third_party/WebKit/Source/core/xml/XPathExpression.cpp \
 	third_party/WebKit/Source/core/xml/XPathExpressionNode.cpp \
 	third_party/WebKit/Source/core/xml/XPathFunctions.cpp \
@@ -487,7 +488,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -523,9 +524,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -546,11 +545,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -565,7 +564,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -588,10 +586,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -614,6 +611,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -637,10 +635,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -652,9 +649,176 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-fno-strict-aliasing \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -669,6 +833,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-EL \
+	-Wl,--no-keep-memory \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_remaining.target.darwin-x86.mk b/Source/core/webcore_remaining.target.darwin-x86.mk
index b7ddbb3..2af3021 100644
--- a/Source/core/webcore_remaining.target.darwin-x86.mk
+++ b/Source/core/webcore_remaining.target.darwin-x86.mk
@@ -109,7 +109,6 @@
 	third_party/WebKit/Source/core/css/CSSSelector.cpp \
 	third_party/WebKit/Source/core/css/CSSSelectorList.cpp \
 	third_party/WebKit/Source/core/css/CSSShaderValue.cpp \
-	third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleRule.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleSheet.cpp \
 	third_party/WebKit/Source/core/css/CSSSupportsRule.cpp \
@@ -162,11 +161,13 @@
 	third_party/WebKit/Source/core/css/StyleSheet.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
+	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp \
+	third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp \
 	third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp \
 	third_party/WebKit/Source/core/editing/AppendNodeCommand.cpp \
@@ -222,19 +223,19 @@
 	third_party/WebKit/Source/core/editing/VisibleUnits.cpp \
 	third_party/WebKit/Source/core/editing/WrapContentsInDummySpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
-	third_party/WebKit/Source/core/editing/chromium/FrameSelectionChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
+	third_party/WebKit/Source/core/fileapi/BlobRegistry.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobURL.cpp \
 	third_party/WebKit/Source/core/fileapi/File.cpp \
-	third_party/WebKit/Source/core/fileapi/FileException.cpp \
+	third_party/WebKit/Source/core/fileapi/FileError.cpp \
 	third_party/WebKit/Source/core/fileapi/FileList.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp \
-	third_party/WebKit/Source/core/fileapi/ThreadableBlobRegistry.cpp \
+	third_party/WebKit/Source/core/fileapi/Stream.cpp \
 	third_party/WebKit/Source/core/history/BackForwardController.cpp \
 	third_party/WebKit/Source/core/history/HistoryItem.cpp \
 	third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp \
@@ -283,9 +284,9 @@
 	third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorStyleTextEditor.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorValues.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
+	third_party/WebKit/Source/core/inspector/JSONParser.cpp \
 	third_party/WebKit/Source/core/inspector/MemoryInstrumentationImpl.cpp \
 	third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp \
 	third_party/WebKit/Source/core/inspector/PageConsoleAgent.cpp \
@@ -321,6 +322,7 @@
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
 	third_party/WebKit/Source/core/loader/NavigationAction.cpp \
+	third_party/WebKit/Source/core/loader/NavigationPolicy.cpp \
 	third_party/WebKit/Source/core/loader/NavigationScheduler.cpp \
 	third_party/WebKit/Source/core/loader/PingLoader.cpp \
 	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
@@ -332,6 +334,7 @@
 	third_party/WebKit/Source/core/loader/SubframeLoader.cpp \
 	third_party/WebKit/Source/core/loader/SubstituteData.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
+	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
@@ -379,7 +382,6 @@
 	third_party/WebKit/Source/core/page/FrameDestructionObserver.cpp \
 	third_party/WebKit/Source/core/page/FrameTree.cpp \
 	third_party/WebKit/Source/core/page/FrameView.cpp \
-	third_party/WebKit/Source/core/page/GroupSettings.cpp \
 	third_party/WebKit/Source/core/page/History.cpp \
 	third_party/WebKit/Source/core/page/Location.cpp \
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
@@ -439,15 +441,15 @@
 	third_party/WebKit/Source/core/storage/Storage.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
-	third_party/WebKit/Source/core/workers/DedicatedWorkerContext.cpp \
+	third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/SharedWorker.cpp \
-	third_party/WebKit/Source/core/workers/SharedWorkerContext.cpp \
+	third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/Worker.cpp \
-	third_party/WebKit/Source/core/workers/WorkerContext.cpp \
-	third_party/WebKit/Source/core/workers/WorkerContextProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/WorkerLocation.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
@@ -464,7 +466,6 @@
 	third_party/WebKit/Source/core/xml/XMLSerializer.cpp \
 	third_party/WebKit/Source/core/xml/XMLTreeViewer.cpp \
 	third_party/WebKit/Source/core/xml/XPathEvaluator.cpp \
-	third_party/WebKit/Source/core/xml/XPathException.cpp \
 	third_party/WebKit/Source/core/xml/XPathExpression.cpp \
 	third_party/WebKit/Source/core/xml/XPathExpressionNode.cpp \
 	third_party/WebKit/Source/core/xml/XPathFunctions.cpp \
@@ -487,7 +488,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -525,9 +526,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -549,11 +548,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -568,7 +567,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -591,10 +589,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -617,6 +614,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -640,10 +638,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -654,9 +651,180 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-fno-strict-aliasing \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -671,6 +839,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-m32 \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_remaining.target.linux-arm.mk b/Source/core/webcore_remaining.target.linux-arm.mk
index 5318e9a..3c68171 100644
--- a/Source/core/webcore_remaining.target.linux-arm.mk
+++ b/Source/core/webcore_remaining.target.linux-arm.mk
@@ -109,7 +109,6 @@
 	third_party/WebKit/Source/core/css/CSSSelector.cpp \
 	third_party/WebKit/Source/core/css/CSSSelectorList.cpp \
 	third_party/WebKit/Source/core/css/CSSShaderValue.cpp \
-	third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleRule.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleSheet.cpp \
 	third_party/WebKit/Source/core/css/CSSSupportsRule.cpp \
@@ -162,11 +161,13 @@
 	third_party/WebKit/Source/core/css/StyleSheet.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
+	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp \
+	third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp \
 	third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp \
 	third_party/WebKit/Source/core/editing/AppendNodeCommand.cpp \
@@ -222,19 +223,19 @@
 	third_party/WebKit/Source/core/editing/VisibleUnits.cpp \
 	third_party/WebKit/Source/core/editing/WrapContentsInDummySpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
-	third_party/WebKit/Source/core/editing/chromium/FrameSelectionChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
+	third_party/WebKit/Source/core/fileapi/BlobRegistry.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobURL.cpp \
 	third_party/WebKit/Source/core/fileapi/File.cpp \
-	third_party/WebKit/Source/core/fileapi/FileException.cpp \
+	third_party/WebKit/Source/core/fileapi/FileError.cpp \
 	third_party/WebKit/Source/core/fileapi/FileList.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp \
-	third_party/WebKit/Source/core/fileapi/ThreadableBlobRegistry.cpp \
+	third_party/WebKit/Source/core/fileapi/Stream.cpp \
 	third_party/WebKit/Source/core/history/BackForwardController.cpp \
 	third_party/WebKit/Source/core/history/HistoryItem.cpp \
 	third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp \
@@ -283,9 +284,9 @@
 	third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorStyleTextEditor.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorValues.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
+	third_party/WebKit/Source/core/inspector/JSONParser.cpp \
 	third_party/WebKit/Source/core/inspector/MemoryInstrumentationImpl.cpp \
 	third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp \
 	third_party/WebKit/Source/core/inspector/PageConsoleAgent.cpp \
@@ -321,6 +322,7 @@
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
 	third_party/WebKit/Source/core/loader/NavigationAction.cpp \
+	third_party/WebKit/Source/core/loader/NavigationPolicy.cpp \
 	third_party/WebKit/Source/core/loader/NavigationScheduler.cpp \
 	third_party/WebKit/Source/core/loader/PingLoader.cpp \
 	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
@@ -332,6 +334,7 @@
 	third_party/WebKit/Source/core/loader/SubframeLoader.cpp \
 	third_party/WebKit/Source/core/loader/SubstituteData.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
+	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
@@ -379,7 +382,6 @@
 	third_party/WebKit/Source/core/page/FrameDestructionObserver.cpp \
 	third_party/WebKit/Source/core/page/FrameTree.cpp \
 	third_party/WebKit/Source/core/page/FrameView.cpp \
-	third_party/WebKit/Source/core/page/GroupSettings.cpp \
 	third_party/WebKit/Source/core/page/History.cpp \
 	third_party/WebKit/Source/core/page/Location.cpp \
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
@@ -439,15 +441,15 @@
 	third_party/WebKit/Source/core/storage/Storage.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
-	third_party/WebKit/Source/core/workers/DedicatedWorkerContext.cpp \
+	third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/SharedWorker.cpp \
-	third_party/WebKit/Source/core/workers/SharedWorkerContext.cpp \
+	third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/Worker.cpp \
-	third_party/WebKit/Source/core/workers/WorkerContext.cpp \
-	third_party/WebKit/Source/core/workers/WorkerContextProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/WorkerLocation.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
@@ -464,7 +466,6 @@
 	third_party/WebKit/Source/core/xml/XMLSerializer.cpp \
 	third_party/WebKit/Source/core/xml/XMLTreeViewer.cpp \
 	third_party/WebKit/Source/core/xml/XPathEvaluator.cpp \
-	third_party/WebKit/Source/core/xml/XPathException.cpp \
 	third_party/WebKit/Source/core/xml/XPathExpression.cpp \
 	third_party/WebKit/Source/core/xml/XPathExpressionNode.cpp \
 	third_party/WebKit/Source/core/xml/XPathFunctions.cpp \
@@ -487,7 +488,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -523,9 +524,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -547,11 +546,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -566,7 +565,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -589,10 +587,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -615,6 +612,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -638,10 +636,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -653,9 +650,177 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-fno-strict-aliasing \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -672,6 +837,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_remaining.target.linux-mips.mk b/Source/core/webcore_remaining.target.linux-mips.mk
index 53dfec8..deb57fa 100644
--- a/Source/core/webcore_remaining.target.linux-mips.mk
+++ b/Source/core/webcore_remaining.target.linux-mips.mk
@@ -109,7 +109,6 @@
 	third_party/WebKit/Source/core/css/CSSSelector.cpp \
 	third_party/WebKit/Source/core/css/CSSSelectorList.cpp \
 	third_party/WebKit/Source/core/css/CSSShaderValue.cpp \
-	third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleRule.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleSheet.cpp \
 	third_party/WebKit/Source/core/css/CSSSupportsRule.cpp \
@@ -162,11 +161,13 @@
 	third_party/WebKit/Source/core/css/StyleSheet.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
+	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp \
+	third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp \
 	third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp \
 	third_party/WebKit/Source/core/editing/AppendNodeCommand.cpp \
@@ -222,19 +223,19 @@
 	third_party/WebKit/Source/core/editing/VisibleUnits.cpp \
 	third_party/WebKit/Source/core/editing/WrapContentsInDummySpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
-	third_party/WebKit/Source/core/editing/chromium/FrameSelectionChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
+	third_party/WebKit/Source/core/fileapi/BlobRegistry.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobURL.cpp \
 	third_party/WebKit/Source/core/fileapi/File.cpp \
-	third_party/WebKit/Source/core/fileapi/FileException.cpp \
+	third_party/WebKit/Source/core/fileapi/FileError.cpp \
 	third_party/WebKit/Source/core/fileapi/FileList.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp \
-	third_party/WebKit/Source/core/fileapi/ThreadableBlobRegistry.cpp \
+	third_party/WebKit/Source/core/fileapi/Stream.cpp \
 	third_party/WebKit/Source/core/history/BackForwardController.cpp \
 	third_party/WebKit/Source/core/history/HistoryItem.cpp \
 	third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp \
@@ -283,9 +284,9 @@
 	third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorStyleTextEditor.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorValues.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
+	third_party/WebKit/Source/core/inspector/JSONParser.cpp \
 	third_party/WebKit/Source/core/inspector/MemoryInstrumentationImpl.cpp \
 	third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp \
 	third_party/WebKit/Source/core/inspector/PageConsoleAgent.cpp \
@@ -321,6 +322,7 @@
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
 	third_party/WebKit/Source/core/loader/NavigationAction.cpp \
+	third_party/WebKit/Source/core/loader/NavigationPolicy.cpp \
 	third_party/WebKit/Source/core/loader/NavigationScheduler.cpp \
 	third_party/WebKit/Source/core/loader/PingLoader.cpp \
 	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
@@ -332,6 +334,7 @@
 	third_party/WebKit/Source/core/loader/SubframeLoader.cpp \
 	third_party/WebKit/Source/core/loader/SubstituteData.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
+	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
@@ -379,7 +382,6 @@
 	third_party/WebKit/Source/core/page/FrameDestructionObserver.cpp \
 	third_party/WebKit/Source/core/page/FrameTree.cpp \
 	third_party/WebKit/Source/core/page/FrameView.cpp \
-	third_party/WebKit/Source/core/page/GroupSettings.cpp \
 	third_party/WebKit/Source/core/page/History.cpp \
 	third_party/WebKit/Source/core/page/Location.cpp \
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
@@ -439,15 +441,15 @@
 	third_party/WebKit/Source/core/storage/Storage.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
-	third_party/WebKit/Source/core/workers/DedicatedWorkerContext.cpp \
+	third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/SharedWorker.cpp \
-	third_party/WebKit/Source/core/workers/SharedWorkerContext.cpp \
+	third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/Worker.cpp \
-	third_party/WebKit/Source/core/workers/WorkerContext.cpp \
-	third_party/WebKit/Source/core/workers/WorkerContextProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/WorkerLocation.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
@@ -464,7 +466,6 @@
 	third_party/WebKit/Source/core/xml/XMLSerializer.cpp \
 	third_party/WebKit/Source/core/xml/XMLTreeViewer.cpp \
 	third_party/WebKit/Source/core/xml/XPathEvaluator.cpp \
-	third_party/WebKit/Source/core/xml/XPathException.cpp \
 	third_party/WebKit/Source/core/xml/XPathExpression.cpp \
 	third_party/WebKit/Source/core/xml/XPathExpressionNode.cpp \
 	third_party/WebKit/Source/core/xml/XPathFunctions.cpp \
@@ -487,7 +488,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -523,9 +524,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -546,11 +545,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -565,7 +564,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -588,10 +586,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -614,6 +611,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -637,10 +635,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -652,9 +649,176 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-fno-strict-aliasing \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -669,6 +833,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-EL \
+	-Wl,--no-keep-memory \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_remaining.target.linux-x86.mk b/Source/core/webcore_remaining.target.linux-x86.mk
index b7ddbb3..2af3021 100644
--- a/Source/core/webcore_remaining.target.linux-x86.mk
+++ b/Source/core/webcore_remaining.target.linux-x86.mk
@@ -109,7 +109,6 @@
 	third_party/WebKit/Source/core/css/CSSSelector.cpp \
 	third_party/WebKit/Source/core/css/CSSSelectorList.cpp \
 	third_party/WebKit/Source/core/css/CSSShaderValue.cpp \
-	third_party/WebKit/Source/core/css/CSSStyleDeclaration.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleRule.cpp \
 	third_party/WebKit/Source/core/css/CSSStyleSheet.cpp \
 	third_party/WebKit/Source/core/css/CSSSupportsRule.cpp \
@@ -162,11 +161,13 @@
 	third_party/WebKit/Source/core/css/StyleSheet.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetContents.cpp \
 	third_party/WebKit/Source/core/css/StyleSheetList.cpp \
+	third_party/WebKit/Source/core/css/resolver/ElementStyleResources.cpp \
 	third_party/WebKit/Source/core/css/resolver/FilterOperationResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/ScopedStyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleBuilderCustom.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolver.cpp \
 	third_party/WebKit/Source/core/css/resolver/StyleResolverState.cpp \
+	third_party/WebKit/Source/core/css/resolver/StyleResourceLoader.cpp \
 	third_party/WebKit/Source/core/css/resolver/TransformBuilder.cpp \
 	third_party/WebKit/Source/core/css/resolver/ViewportStyleResolver.cpp \
 	third_party/WebKit/Source/core/editing/AppendNodeCommand.cpp \
@@ -222,19 +223,19 @@
 	third_party/WebKit/Source/core/editing/VisibleUnits.cpp \
 	third_party/WebKit/Source/core/editing/WrapContentsInDummySpanCommand.cpp \
 	third_party/WebKit/Source/core/editing/chromium/EditorChromium.cpp \
-	third_party/WebKit/Source/core/editing/chromium/FrameSelectionChromium.cpp \
 	third_party/WebKit/Source/core/editing/htmlediting.cpp \
 	third_party/WebKit/Source/core/editing/markup.cpp \
 	third_party/WebKit/Source/core/fileapi/Blob.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobBuilder.cpp \
+	third_party/WebKit/Source/core/fileapi/BlobRegistry.cpp \
 	third_party/WebKit/Source/core/fileapi/BlobURL.cpp \
 	third_party/WebKit/Source/core/fileapi/File.cpp \
-	third_party/WebKit/Source/core/fileapi/FileException.cpp \
+	third_party/WebKit/Source/core/fileapi/FileError.cpp \
 	third_party/WebKit/Source/core/fileapi/FileList.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderLoader.cpp \
 	third_party/WebKit/Source/core/fileapi/FileReaderSync.cpp \
-	third_party/WebKit/Source/core/fileapi/ThreadableBlobRegistry.cpp \
+	third_party/WebKit/Source/core/fileapi/Stream.cpp \
 	third_party/WebKit/Source/core/history/BackForwardController.cpp \
 	third_party/WebKit/Source/core/history/HistoryItem.cpp \
 	third_party/WebKit/Source/core/inspector/ConsoleMessage.cpp \
@@ -283,9 +284,9 @@
 	third_party/WebKit/Source/core/inspector/InspectorStyleSheet.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorStyleTextEditor.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorTimelineAgent.cpp \
-	third_party/WebKit/Source/core/inspector/InspectorValues.cpp \
 	third_party/WebKit/Source/core/inspector/InspectorWorkerAgent.cpp \
 	third_party/WebKit/Source/core/inspector/JavaScriptCallFrame.cpp \
+	third_party/WebKit/Source/core/inspector/JSONParser.cpp \
 	third_party/WebKit/Source/core/inspector/MemoryInstrumentationImpl.cpp \
 	third_party/WebKit/Source/core/inspector/NetworkResourcesData.cpp \
 	third_party/WebKit/Source/core/inspector/PageConsoleAgent.cpp \
@@ -321,6 +322,7 @@
 	third_party/WebKit/Source/core/loader/LinkLoader.cpp \
 	third_party/WebKit/Source/core/loader/MixedContentChecker.cpp \
 	third_party/WebKit/Source/core/loader/NavigationAction.cpp \
+	third_party/WebKit/Source/core/loader/NavigationPolicy.cpp \
 	third_party/WebKit/Source/core/loader/NavigationScheduler.cpp \
 	third_party/WebKit/Source/core/loader/PingLoader.cpp \
 	third_party/WebKit/Source/core/loader/Prerenderer.cpp \
@@ -332,6 +334,7 @@
 	third_party/WebKit/Source/core/loader/SubframeLoader.cpp \
 	third_party/WebKit/Source/core/loader/SubstituteData.cpp \
 	third_party/WebKit/Source/core/loader/TextResourceDecoder.cpp \
+	third_party/WebKit/Source/core/loader/TextResourceDecoderBuilder.cpp \
 	third_party/WebKit/Source/core/loader/TextTrackLoader.cpp \
 	third_party/WebKit/Source/core/loader/ThreadableLoader.cpp \
 	third_party/WebKit/Source/core/loader/UniqueIdentifier.cpp \
@@ -379,7 +382,6 @@
 	third_party/WebKit/Source/core/page/FrameDestructionObserver.cpp \
 	third_party/WebKit/Source/core/page/FrameTree.cpp \
 	third_party/WebKit/Source/core/page/FrameView.cpp \
-	third_party/WebKit/Source/core/page/GroupSettings.cpp \
 	third_party/WebKit/Source/core/page/History.cpp \
 	third_party/WebKit/Source/core/page/Location.cpp \
 	third_party/WebKit/Source/core/page/MemoryInfo.cpp \
@@ -439,15 +441,15 @@
 	third_party/WebKit/Source/core/storage/Storage.cpp \
 	third_party/WebKit/Source/core/storage/StorageEvent.cpp \
 	third_party/WebKit/Source/core/workers/AbstractWorker.cpp \
-	third_party/WebKit/Source/core/workers/DedicatedWorkerContext.cpp \
+	third_party/WebKit/Source/core/workers/DedicatedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/DedicatedWorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/SharedWorker.cpp \
-	third_party/WebKit/Source/core/workers/SharedWorkerContext.cpp \
+	third_party/WebKit/Source/core/workers/SharedWorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/SharedWorkerThread.cpp \
 	third_party/WebKit/Source/core/workers/Worker.cpp \
-	third_party/WebKit/Source/core/workers/WorkerContext.cpp \
-	third_party/WebKit/Source/core/workers/WorkerContextProxy.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScopeProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerEventQueue.cpp \
+	third_party/WebKit/Source/core/workers/WorkerGlobalScope.cpp \
 	third_party/WebKit/Source/core/workers/WorkerLocation.cpp \
 	third_party/WebKit/Source/core/workers/WorkerMessagingProxy.cpp \
 	third_party/WebKit/Source/core/workers/WorkerRunLoop.cpp \
@@ -464,7 +466,6 @@
 	third_party/WebKit/Source/core/xml/XMLSerializer.cpp \
 	third_party/WebKit/Source/core/xml/XMLTreeViewer.cpp \
 	third_party/WebKit/Source/core/xml/XPathEvaluator.cpp \
-	third_party/WebKit/Source/core/xml/XPathException.cpp \
 	third_party/WebKit/Source/core/xml/XPathExpression.cpp \
 	third_party/WebKit/Source/core/xml/XPathExpressionNode.cpp \
 	third_party/WebKit/Source/core/xml/XPathFunctions.cpp \
@@ -487,7 +488,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -525,9 +526,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -549,11 +548,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -568,7 +567,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -591,10 +589,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -617,6 +614,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -640,10 +638,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -654,9 +651,180 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-fno-strict-aliasing \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -671,6 +839,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-m32 \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_rendering.target.darwin-arm.mk b/Source/core/webcore_rendering.target.darwin-arm.mk
index ee34d79..36cf7f3 100644
--- a/Source/core/webcore_rendering.target.darwin-arm.mk
+++ b/Source/core/webcore_rendering.target.darwin-arm.mk
@@ -28,13 +28,6 @@
 	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionInterval.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionPolygon.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionRectangle.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShape.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeInfo.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeInsideInfo.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
 	third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
@@ -47,6 +40,7 @@
 	third_party/WebKit/Source/core/rendering/InlineTextBox.cpp \
 	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
+	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
@@ -143,6 +137,13 @@
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp \
 	third_party/WebKit/Source/core/rendering/style/ContentData.cpp \
 	third_party/WebKit/Source/core/rendering/style/CounterDirectives.cpp \
@@ -176,7 +177,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -211,9 +212,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -235,11 +234,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -254,7 +253,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -277,10 +275,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -302,6 +299,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -325,10 +323,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -340,9 +337,175 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -359,6 +522,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_rendering.target.darwin-mips.mk b/Source/core/webcore_rendering.target.darwin-mips.mk
index b1a97d5..77f60bc 100644
--- a/Source/core/webcore_rendering.target.darwin-mips.mk
+++ b/Source/core/webcore_rendering.target.darwin-mips.mk
@@ -28,13 +28,6 @@
 	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionInterval.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionPolygon.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionRectangle.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShape.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeInfo.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeInsideInfo.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
 	third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
@@ -47,6 +40,7 @@
 	third_party/WebKit/Source/core/rendering/InlineTextBox.cpp \
 	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
+	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
@@ -143,6 +137,13 @@
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp \
 	third_party/WebKit/Source/core/rendering/style/ContentData.cpp \
 	third_party/WebKit/Source/core/rendering/style/CounterDirectives.cpp \
@@ -176,7 +177,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -211,9 +212,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -234,11 +233,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -253,7 +252,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -276,10 +274,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -301,6 +298,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -324,10 +322,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -339,9 +336,174 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -356,6 +518,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-EL \
+	-Wl,--no-keep-memory \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_rendering.target.darwin-x86.mk b/Source/core/webcore_rendering.target.darwin-x86.mk
index 6ab418b..be84b2c 100644
--- a/Source/core/webcore_rendering.target.darwin-x86.mk
+++ b/Source/core/webcore_rendering.target.darwin-x86.mk
@@ -28,13 +28,6 @@
 	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionInterval.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionPolygon.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionRectangle.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShape.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeInfo.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeInsideInfo.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
 	third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
@@ -47,6 +40,7 @@
 	third_party/WebKit/Source/core/rendering/InlineTextBox.cpp \
 	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
+	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
@@ -143,6 +137,13 @@
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp \
 	third_party/WebKit/Source/core/rendering/style/ContentData.cpp \
 	third_party/WebKit/Source/core/rendering/style/CounterDirectives.cpp \
@@ -176,7 +177,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -214,9 +215,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -238,11 +237,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -257,7 +256,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -280,10 +278,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -305,6 +302,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -328,10 +326,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -342,9 +339,179 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-uninitialized \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -359,6 +526,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-m32 \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_rendering.target.linux-arm.mk b/Source/core/webcore_rendering.target.linux-arm.mk
index ee34d79..36cf7f3 100644
--- a/Source/core/webcore_rendering.target.linux-arm.mk
+++ b/Source/core/webcore_rendering.target.linux-arm.mk
@@ -28,13 +28,6 @@
 	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionInterval.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionPolygon.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionRectangle.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShape.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeInfo.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeInsideInfo.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
 	third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
@@ -47,6 +40,7 @@
 	third_party/WebKit/Source/core/rendering/InlineTextBox.cpp \
 	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
+	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
@@ -143,6 +137,13 @@
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp \
 	third_party/WebKit/Source/core/rendering/style/ContentData.cpp \
 	third_party/WebKit/Source/core/rendering/style/CounterDirectives.cpp \
@@ -176,7 +177,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -211,9 +212,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -235,11 +234,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -254,7 +253,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -277,10 +275,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -302,6 +299,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -325,10 +323,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -340,9 +337,175 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -359,6 +522,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_rendering.target.linux-mips.mk b/Source/core/webcore_rendering.target.linux-mips.mk
index b1a97d5..77f60bc 100644
--- a/Source/core/webcore_rendering.target.linux-mips.mk
+++ b/Source/core/webcore_rendering.target.linux-mips.mk
@@ -28,13 +28,6 @@
 	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionInterval.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionPolygon.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionRectangle.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShape.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeInfo.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeInsideInfo.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
 	third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
@@ -47,6 +40,7 @@
 	third_party/WebKit/Source/core/rendering/InlineTextBox.cpp \
 	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
+	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
@@ -143,6 +137,13 @@
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp \
 	third_party/WebKit/Source/core/rendering/style/ContentData.cpp \
 	third_party/WebKit/Source/core/rendering/style/CounterDirectives.cpp \
@@ -176,7 +177,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -211,9 +212,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -234,11 +233,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -253,7 +252,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -276,10 +274,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -301,6 +298,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -324,10 +322,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -339,9 +336,174 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -356,6 +518,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-EL \
+	-Wl,--no-keep-memory \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_rendering.target.linux-x86.mk b/Source/core/webcore_rendering.target.linux-x86.mk
index 6ab418b..be84b2c 100644
--- a/Source/core/webcore_rendering.target.linux-x86.mk
+++ b/Source/core/webcore_rendering.target.linux-x86.mk
@@ -28,13 +28,6 @@
 	third_party/WebKit/Source/core/rendering/BidiRun.cpp \
 	third_party/WebKit/Source/core/rendering/CounterNode.cpp \
 	third_party/WebKit/Source/core/rendering/EllipsisBox.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionInterval.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionPolygon.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionRectangle.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShape.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeInfo.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeInsideInfo.cpp \
-	third_party/WebKit/Source/core/rendering/exclusions/ExclusionShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/FilterEffectRenderer.cpp \
 	third_party/WebKit/Source/core/rendering/FixedTableLayout.cpp \
 	third_party/WebKit/Source/core/rendering/FlowThreadController.cpp \
@@ -47,6 +40,7 @@
 	third_party/WebKit/Source/core/rendering/InlineTextBox.cpp \
 	third_party/WebKit/Source/core/rendering/ImageQualityController.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutState.cpp \
+	third_party/WebKit/Source/core/rendering/OrderIterator.cpp \
 	third_party/WebKit/Source/core/rendering/LayoutRepainter.cpp \
 	third_party/WebKit/Source/core/rendering/PointerEventsHitRules.cpp \
 	third_party/WebKit/Source/core/rendering/RenderApplet.cpp \
@@ -143,6 +137,13 @@
 	third_party/WebKit/Source/core/rendering/RootInlineBox.cpp \
 	third_party/WebKit/Source/core/rendering/ScrollBehavior.cpp \
 	third_party/WebKit/Source/core/rendering/break_lines.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/PolygonShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/RectangleShape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/Shape.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInfo.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInsideInfo.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeInterval.cpp \
+	third_party/WebKit/Source/core/rendering/shapes/ShapeOutsideInfo.cpp \
 	third_party/WebKit/Source/core/rendering/style/BasicShapes.cpp \
 	third_party/WebKit/Source/core/rendering/style/ContentData.cpp \
 	third_party/WebKit/Source/core/rendering/style/CounterDirectives.cpp \
@@ -176,7 +177,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -214,9 +215,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -238,11 +237,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -257,7 +256,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -280,10 +278,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -305,6 +302,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -328,10 +326,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -342,9 +339,179 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-uninitialized \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -359,6 +526,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-m32 \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_svg.target.darwin-arm.mk b/Source/core/webcore_svg.target.darwin-arm.mk
index 58a03fe..62076fd 100644
--- a/Source/core/webcore_svg.target.darwin-arm.mk
+++ b/Source/core/webcore_svg.target.darwin-arm.mk
@@ -120,7 +120,6 @@
 	third_party/WebKit/Source/core/svg/SVGElementInstance.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp \
 	third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGException.cpp \
 	third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp \
@@ -163,6 +162,7 @@
 	third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGradientElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageLoader.cpp \
@@ -209,8 +209,6 @@
 	third_party/WebKit/Source/core/svg/SVGStringList.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyledElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGStyledLocatableElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGStyledTransformableElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTRefElement.cpp \
@@ -246,7 +244,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -281,9 +279,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -305,11 +301,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -324,7 +320,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -347,10 +342,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -372,6 +366,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -395,10 +390,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -410,9 +404,175 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -429,6 +589,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_svg.target.darwin-mips.mk b/Source/core/webcore_svg.target.darwin-mips.mk
index 3e5bbcd..2679ec7 100644
--- a/Source/core/webcore_svg.target.darwin-mips.mk
+++ b/Source/core/webcore_svg.target.darwin-mips.mk
@@ -120,7 +120,6 @@
 	third_party/WebKit/Source/core/svg/SVGElementInstance.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp \
 	third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGException.cpp \
 	third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp \
@@ -163,6 +162,7 @@
 	third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGradientElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageLoader.cpp \
@@ -209,8 +209,6 @@
 	third_party/WebKit/Source/core/svg/SVGStringList.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyledElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGStyledLocatableElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGStyledTransformableElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTRefElement.cpp \
@@ -246,7 +244,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -281,9 +279,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -304,11 +300,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -323,7 +319,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -346,10 +341,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -371,6 +365,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -394,10 +389,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -409,9 +403,174 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -426,6 +585,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-EL \
+	-Wl,--no-keep-memory \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_svg.target.darwin-x86.mk b/Source/core/webcore_svg.target.darwin-x86.mk
index 1b4b0f2..aae016f 100644
--- a/Source/core/webcore_svg.target.darwin-x86.mk
+++ b/Source/core/webcore_svg.target.darwin-x86.mk
@@ -120,7 +120,6 @@
 	third_party/WebKit/Source/core/svg/SVGElementInstance.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp \
 	third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGException.cpp \
 	third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp \
@@ -163,6 +162,7 @@
 	third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGradientElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageLoader.cpp \
@@ -209,8 +209,6 @@
 	third_party/WebKit/Source/core/svg/SVGStringList.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyledElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGStyledLocatableElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGStyledTransformableElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTRefElement.cpp \
@@ -246,7 +244,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -283,9 +281,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -307,11 +303,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -326,7 +322,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -349,10 +344,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -374,6 +368,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -397,10 +392,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -411,9 +405,178 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -428,6 +591,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-m32 \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_svg.target.linux-arm.mk b/Source/core/webcore_svg.target.linux-arm.mk
index 58a03fe..62076fd 100644
--- a/Source/core/webcore_svg.target.linux-arm.mk
+++ b/Source/core/webcore_svg.target.linux-arm.mk
@@ -120,7 +120,6 @@
 	third_party/WebKit/Source/core/svg/SVGElementInstance.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp \
 	third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGException.cpp \
 	third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp \
@@ -163,6 +162,7 @@
 	third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGradientElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageLoader.cpp \
@@ -209,8 +209,6 @@
 	third_party/WebKit/Source/core/svg/SVGStringList.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyledElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGStyledLocatableElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGStyledTransformableElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTRefElement.cpp \
@@ -246,7 +244,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
@@ -281,9 +279,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -305,11 +301,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -324,7 +320,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -347,10 +342,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -372,6 +366,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -395,10 +390,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -410,9 +404,175 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-fno-tree-sra \
+	-fuse-ld=gold \
+	-Wno-psabi \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-abi \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -429,6 +589,25 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-Wl,-z,relro \
+	-Wl,-z,now \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,--icf=safe \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_svg.target.linux-mips.mk b/Source/core/webcore_svg.target.linux-mips.mk
index 3e5bbcd..2679ec7 100644
--- a/Source/core/webcore_svg.target.linux-mips.mk
+++ b/Source/core/webcore_svg.target.linux-mips.mk
@@ -120,7 +120,6 @@
 	third_party/WebKit/Source/core/svg/SVGElementInstance.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp \
 	third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGException.cpp \
 	third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp \
@@ -163,6 +162,7 @@
 	third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGradientElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageLoader.cpp \
@@ -209,8 +209,6 @@
 	third_party/WebKit/Source/core/svg/SVGStringList.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyledElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGStyledLocatableElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGStyledTransformableElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTRefElement.cpp \
@@ -246,7 +244,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	-fstack-protector \
 	--param=ssp-buffer-size=4 \
 	 \
@@ -281,9 +279,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DNO_TCMALLOC' \
@@ -304,11 +300,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -323,7 +319,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -346,10 +341,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -371,6 +365,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -394,10 +389,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -409,9 +403,174 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	-fstack-protector \
+	--param=ssp-buffer-size=4 \
+	 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-EL \
+	-mhard-float \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fstack-protector \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-uninitialized \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -426,6 +585,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-EL \
+	-Wl,--no-keep-memory \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/webcore_svg.target.linux-x86.mk b/Source/core/webcore_svg.target.linux-x86.mk
index 1b4b0f2..aae016f 100644
--- a/Source/core/webcore_svg.target.linux-x86.mk
+++ b/Source/core/webcore_svg.target.linux-x86.mk
@@ -120,7 +120,6 @@
 	third_party/WebKit/Source/core/svg/SVGElementInstance.cpp \
 	third_party/WebKit/Source/core/svg/SVGElementInstanceList.cpp \
 	third_party/WebKit/Source/core/svg/SVGEllipseElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGException.cpp \
 	third_party/WebKit/Source/core/svg/SVGExternalResourcesRequired.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEBlendElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGFEColorMatrixElement.cpp \
@@ -163,6 +162,7 @@
 	third_party/WebKit/Source/core/svg/SVGGlyphElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGlyphRefElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGGradientElement.cpp \
+	third_party/WebKit/Source/core/svg/SVGGraphicsElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGHKernElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGImageLoader.cpp \
@@ -209,8 +209,6 @@
 	third_party/WebKit/Source/core/svg/SVGStringList.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyleElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGStyledElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGStyledLocatableElement.cpp \
-	third_party/WebKit/Source/core/svg/SVGStyledTransformableElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSwitchElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGSymbolElement.cpp \
 	third_party/WebKit/Source/core/svg/SVGTRefElement.cpp \
@@ -246,7 +244,7 @@
 
 
 # Flags passed to both C and C++ files.
-MY_CFLAGS := \
+MY_CFLAGS_Debug := \
 	--param=ssp-buffer-size=4 \
 	-fno-exceptions \
 	-fno-strict-aliasing \
@@ -283,9 +281,7 @@
 	-fdata-sections \
 	-ffunction-sections
 
-MY_CFLAGS_C :=
-
-MY_DEFS := \
+MY_DEFS_Debug := \
 	'-DANGLE_DX11' \
 	'-D_FILE_OFFSET_BITS=64' \
 	'-DUSE_LINUX_BREAKPAD' \
@@ -307,11 +303,11 @@
 	'-DENABLE_CSS_REGIONS=1' \
 	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
 	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
-	'-DENABLE_GRAPHICS_CONTEXT_ANNOTATIONS=0' \
 	'-DENABLE_SVG_FONTS=1' \
 	'-DENABLE_TOUCH_ICON_LOADING=1' \
 	'-DENABLE_XHR_TIMEOUT=0' \
 	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
 	'-DENABLE_CALENDAR_PICKER=0' \
 	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
@@ -326,7 +322,6 @@
 	'-DENABLE_8BIT_TEXTRUN=1' \
 	'-DENABLE_OPENTYPE_VERTICAL=1' \
 	'-DWTF_USE_HARFBUZZ=1' \
-	'-DENABLE_PARTITION_ALLOC=1' \
 	'-DU_USING_ICU_NAMESPACE=0' \
 	'-DSK_BUILD_NO_IMAGE_ENCODE' \
 	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
@@ -349,10 +344,9 @@
 	'-DWTF_USE_DYNAMIC_ANNOTATIONS=1' \
 	'-D_DEBUG'
 
-LOCAL_CFLAGS := $(MY_CFLAGS_C) $(MY_CFLAGS) $(MY_DEFS)
 
 # Include paths placed before CFLAGS/CPPFLAGS
-LOCAL_C_INCLUDES := \
+LOCAL_C_INCLUDES_Debug := \
 	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
 	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
@@ -374,6 +368,7 @@
 	$(LOCAL_PATH)/third_party/skia/include/pdf \
 	$(LOCAL_PATH)/third_party/skia/include/gpu \
 	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
 	$(LOCAL_PATH)/third_party/skia/include/pathops \
 	$(LOCAL_PATH)/third_party/skia/include/pipe \
 	$(LOCAL_PATH)/third_party/skia/include/ports \
@@ -397,10 +392,9 @@
 	$(PWD)/bionic \
 	$(PWD)/external/stlport/stlport
 
-LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES)
 
 # Flags passed to only C++ (and not C) files.
-LOCAL_CPPFLAGS := \
+LOCAL_CPPFLAGS_Debug := \
 	-fno-rtti \
 	-fno-threadsafe-statics \
 	-fvisibility-inlines-hidden \
@@ -411,9 +405,178 @@
 	-Wno-sign-promo \
 	-Wno-non-virtual-dtor
 
+
+# Flags passed to both C and C++ files.
+MY_CFLAGS_Release := \
+	--param=ssp-buffer-size=4 \
+	-fno-exceptions \
+	-fno-strict-aliasing \
+	-Wno-unused-parameter \
+	-Wno-missing-field-initializers \
+	-fvisibility=hidden \
+	-pipe \
+	-fPIC \
+	-Wno-format \
+	-m32 \
+	-mmmx \
+	-march=pentium4 \
+	-msse2 \
+	-mfpmath=sse \
+	-fuse-ld=gold \
+	-ffunction-sections \
+	-funwind-tables \
+	-g \
+	-fno-short-enums \
+	-finline-limit=64 \
+	-Wa,--noexecstack \
+	-U_FORTIFY_SOURCE \
+	-Wno-extra \
+	-Wno-ignored-qualifiers \
+	-Wno-type-limits \
+	-Wno-address \
+	-Wno-format-security \
+	-Wno-return-type \
+	-Wno-sequence-point \
+	-fno-stack-protector \
+	-Os \
+	-fno-ident \
+	-fdata-sections \
+	-ffunction-sections \
+	-fomit-frame-pointer \
+	-fno-unwind-tables \
+	-fno-asynchronous-unwind-tables
+
+MY_DEFS_Release := \
+	'-DANGLE_DX11' \
+	'-D_FILE_OFFSET_BITS=64' \
+	'-DUSE_LINUX_BREAKPAD' \
+	'-DNO_TCMALLOC' \
+	'-DDISABLE_NACL' \
+	'-DCHROMIUM_BUILD' \
+	'-DUSE_LIBJPEG_TURBO=1' \
+	'-DUSE_PROPRIETARY_CODECS' \
+	'-DENABLE_GPU=1' \
+	'-DUSE_OPENSSL=1' \
+	'-DENABLE_EGLIMAGE=1' \
+	'-DENABLE_LANGUAGE_DETECTION=1' \
+	'-DWEBCORE_NAVIGATOR_VENDOR="Google Inc."' \
+	'-DWEBKIT_IMPLEMENTATION=1' \
+	'-DINSIDE_WEBKIT' \
+	'-DENABLE_CANVAS_USES_MAILBOX=1' \
+	'-DENABLE_CSS3_TEXT=0' \
+	'-DENABLE_CSS_EXCLUSIONS=1' \
+	'-DENABLE_CSS_REGIONS=1' \
+	'-DENABLE_CUSTOM_SCHEME_HANDLER=0' \
+	'-DENABLE_ENCRYPTED_MEDIA_V2=1' \
+	'-DENABLE_SVG_FONTS=1' \
+	'-DENABLE_TOUCH_ICON_LOADING=1' \
+	'-DENABLE_XHR_TIMEOUT=0' \
+	'-DENABLE_GDI_FONTS_ON_WINDOWS=1' \
+	'-DENABLE_PARTITION_ALLOC=1' \
+	'-DWTF_USE_CONCATENATED_IMPULSE_RESPONSES=1' \
+	'-DENABLE_CALENDAR_PICKER=0' \
+	'-DENABLE_FAST_MOBILE_SCROLLING=1' \
+	'-DENABLE_INPUT_SPEECH=0' \
+	'-DENABLE_LEGACY_NOTIFICATIONS=0' \
+	'-DENABLE_MEDIA_CAPTURE=1' \
+	'-DENABLE_NOTIFICATIONS=0' \
+	'-DENABLE_ORIENTATION_EVENTS=1' \
+	'-DENABLE_PRINTING=0' \
+	'-DENABLE_NAVIGATOR_CONTENT_UTILS=0' \
+	'-DWTF_USE_NATIVE_FULLSCREEN_VIDEO=1' \
+	'-DENABLE_8BIT_TEXTRUN=1' \
+	'-DENABLE_OPENTYPE_VERTICAL=1' \
+	'-DWTF_USE_HARFBUZZ=1' \
+	'-DU_USING_ICU_NAMESPACE=0' \
+	'-DSK_BUILD_NO_IMAGE_ENCODE' \
+	'-DSK_DEFERRED_CANVAS_USES_GPIPE=1' \
+	'-DGR_GL_CUSTOM_SETUP_HEADER="GrGLConfig_chrome.h"' \
+	'-DGR_AGGRESSIVE_SHADER_OPTS=1' \
+	'-DSK_ENABLE_INST_COUNT=0' \
+	'-DSK_USE_POSIX_THREADS' \
+	'-DSK_BUILD_FOR_ANDROID' \
+	'-DCHROME_PNG_WRITE_SUPPORT' \
+	'-DPNG_USER_CONFIG' \
+	'-DLIBXML_STATIC' \
+	'-DLIBXSLT_STATIC' \
+	'-DUSE_SYSTEM_LIBJPEG' \
+	'-DANDROID' \
+	'-D__GNU_SOURCE=1' \
+	'-DUSE_STLPORT=1' \
+	'-D_STLP_USE_PTR_SPECIALIZATIONS=1' \
+	'-DCHROME_BUILD_ID=""' \
+	'-DNDEBUG' \
+	'-DNVALGRIND' \
+	'-DDYNAMIC_ANNOTATIONS_ENABLED=0'
+
+
+# Include paths placed before CFLAGS/CPPFLAGS
+LOCAL_C_INCLUDES_Release := \
+	$(gyp_shared_intermediate_dir)/shim_headers/icui18n/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/icuuc/target \
+	$(gyp_shared_intermediate_dir)/shim_headers/ashmem/target \
+	$(LOCAL_PATH)/third_party/khronos \
+	$(LOCAL_PATH)/gpu \
+	$(LOCAL_PATH) \
+	$(LOCAL_PATH)/third_party/WebKit \
+	$(LOCAL_PATH)/third_party/WebKit/Source \
+	$(gyp_shared_intermediate_dir)/webkit \
+	$(gyp_shared_intermediate_dir)/webkit/bindings \
+	$(LOCAL_PATH)/third_party/angle_dx11/include/GLSLANG \
+	$(PWD)/external/icu4c/common \
+	$(PWD)/external/icu4c/i18n \
+	$(LOCAL_PATH)/skia/config \
+	$(LOCAL_PATH)/third_party/skia/src/core \
+	$(LOCAL_PATH)/third_party/skia/include/config \
+	$(LOCAL_PATH)/third_party/skia/include/core \
+	$(LOCAL_PATH)/third_party/skia/include/effects \
+	$(LOCAL_PATH)/third_party/skia/include/pdf \
+	$(LOCAL_PATH)/third_party/skia/include/gpu \
+	$(LOCAL_PATH)/third_party/skia/include/gpu/gl \
+	$(LOCAL_PATH)/third_party/skia/include/lazy \
+	$(LOCAL_PATH)/third_party/skia/include/pathops \
+	$(LOCAL_PATH)/third_party/skia/include/pipe \
+	$(LOCAL_PATH)/third_party/skia/include/ports \
+	$(LOCAL_PATH)/third_party/skia/include/utils \
+	$(LOCAL_PATH)/skia/ext \
+	$(LOCAL_PATH)/third_party/iccjpeg \
+	$(LOCAL_PATH)/third_party/libpng \
+	$(LOCAL_PATH)/third_party/libwebp \
+	$(LOCAL_PATH)/third_party/libxml/linux/include \
+	$(LOCAL_PATH)/third_party/libxml/src/include \
+	$(LOCAL_PATH)/third_party/libxslt \
+	$(LOCAL_PATH)/third_party/npapi \
+	$(LOCAL_PATH)/third_party/npapi/bindings \
+	$(LOCAL_PATH)/third_party/ots/include \
+	$(LOCAL_PATH)/third_party/qcms/src \
+	$(LOCAL_PATH)/third_party/sqlite \
+	$(LOCAL_PATH)/third_party/zlib \
+	$(LOCAL_PATH)/v8/include \
+	$(PWD)/external/jpeg \
+	$(PWD)/frameworks/wilhelm/include \
+	$(PWD)/bionic \
+	$(PWD)/external/stlport/stlport
+
+
+# Flags passed to only C++ (and not C) files.
+LOCAL_CPPFLAGS_Release := \
+	-fno-rtti \
+	-fno-threadsafe-statics \
+	-fvisibility-inlines-hidden \
+	-Wno-c++0x-compat \
+	-Wno-deprecated \
+	-Wno-error=c++0x-compat \
+	-Wno-non-virtual-dtor \
+	-Wno-sign-promo \
+	-Wno-non-virtual-dtor
+
+
+LOCAL_CFLAGS := $(MY_CFLAGS_$(GYP_CONFIGURATION)) $(MY_DEFS_$(GYP_CONFIGURATION))
+LOCAL_C_INCLUDES := $(GYP_COPIED_SOURCE_ORIGIN_DIRS) $(LOCAL_C_INCLUDES_$(GYP_CONFIGURATION))
+LOCAL_CPPFLAGS := $(LOCAL_CPPFLAGS_$(GYP_CONFIGURATION))
 ### Rules for final target.
 
-LOCAL_LDFLAGS := \
+LOCAL_LDFLAGS_Debug := \
 	-Wl,-z,now \
 	-Wl,-z,relro \
 	-Wl,-z,noexecstack \
@@ -428,6 +591,23 @@
 	-Wl,--as-needed
 
 
+LOCAL_LDFLAGS_Release := \
+	-Wl,-z,now \
+	-Wl,-z,relro \
+	-Wl,-z,noexecstack \
+	-fPIC \
+	-m32 \
+	-fuse-ld=gold \
+	-nostdlib \
+	-Wl,--no-undefined \
+	-Wl,--exclude-libs=ALL \
+	-Wl,-O1 \
+	-Wl,--as-needed \
+	-Wl,--gc-sections
+
+
+LOCAL_LDFLAGS := $(LOCAL_LDFLAGS_$(GYP_CONFIGURATION))
+
 LOCAL_STATIC_LIBRARIES := \
 	skia_skia_gyp
 
diff --git a/Source/core/workers/AbstractWorker.cpp b/Source/core/workers/AbstractWorker.cpp
index 3ca3320..fded518 100644
--- a/Source/core/workers/AbstractWorker.cpp
+++ b/Source/core/workers/AbstractWorker.cpp
@@ -43,7 +43,6 @@
 AbstractWorker::AbstractWorker(ScriptExecutionContext* context)
     : ActiveDOMObject(context)
 {
-    ScriptWrappable::init(this);
 }
 
 AbstractWorker::~AbstractWorker()
@@ -52,7 +51,7 @@
 
 void AbstractWorker::contextDestroyed()
 {
-    ActiveDOMObject::contextDestroyed(); 
+    ActiveDOMObject::contextDestroyed();
 }
 
 KURL AbstractWorker::resolveURL(const String& url, ExceptionCode& ec)
diff --git a/Source/core/workers/AbstractWorker.h b/Source/core/workers/AbstractWorker.h
index e73baf2..13bb929 100644
--- a/Source/core/workers/AbstractWorker.h
+++ b/Source/core/workers/AbstractWorker.h
@@ -46,7 +46,7 @@
     class KURL;
     class ScriptExecutionContext;
 
-    class AbstractWorker : public RefCounted<AbstractWorker>, public ScriptWrappable, public ActiveDOMObject, public EventTarget {
+    class AbstractWorker : public RefCounted<AbstractWorker>, public EventTarget, public ActiveDOMObject {
     public:
         // EventTarget APIs
         virtual ScriptExecutionContext* scriptExecutionContext() const OVERRIDE { return ActiveDOMObject::scriptExecutionContext(); }
diff --git a/Source/core/workers/AbstractWorker.idl b/Source/core/workers/AbstractWorker.idl
index 4a0da0d..4211e68 100644
--- a/Source/core/workers/AbstractWorker.idl
+++ b/Source/core/workers/AbstractWorker.idl
@@ -30,19 +30,8 @@
  */
 
 [
-    NoInterfaceObject,
-    ActiveDOMObject,
-    EventTarget
+    NoInterfaceObject
 ] interface AbstractWorker {
-
     attribute EventListener onerror;
-
-    void addEventListener(DOMString type,
-                          EventListener listener,
-                          optional boolean useCapture);
-    void removeEventListener(DOMString type,
-                             EventListener listener,
-                             optional boolean useCapture);
-    [RaisesException] boolean dispatchEvent(Event evt);
 };
 
diff --git a/Source/core/workers/DedicatedWorkerContext.cpp b/Source/core/workers/DedicatedWorkerGlobalScope.cpp
similarity index 65%
rename from Source/core/workers/DedicatedWorkerContext.cpp
rename to Source/core/workers/DedicatedWorkerGlobalScope.cpp
index 1300ed7..0992639 100644
--- a/Source/core/workers/DedicatedWorkerContext.cpp
+++ b/Source/core/workers/DedicatedWorkerGlobalScope.cpp
@@ -30,7 +30,7 @@
 
 #include "config.h"
 
-#include "core/workers/DedicatedWorkerContext.h"
+#include "core/workers/DedicatedWorkerGlobalScope.h"
 
 #include "core/page/DOMWindow.h"
 #include "core/workers/DedicatedWorkerThread.h"
@@ -38,29 +38,29 @@
 
 namespace WebCore {
 
-PassRefPtr<DedicatedWorkerContext> DedicatedWorkerContext::create(const KURL& url, const String& userAgent, PassOwnPtr<GroupSettings> settings, DedicatedWorkerThread* thread, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, PassRefPtr<SecurityOrigin> topOrigin, double timeOrigin)
+PassRefPtr<DedicatedWorkerGlobalScope> DedicatedWorkerGlobalScope::create(const KURL& url, const String& userAgent, DedicatedWorkerThread* thread, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, PassRefPtr<SecurityOrigin> topOrigin, double timeOrigin)
 {
-    RefPtr<DedicatedWorkerContext> context = adoptRef(new DedicatedWorkerContext(url, userAgent, settings, thread, topOrigin, timeOrigin));
+    RefPtr<DedicatedWorkerGlobalScope> context = adoptRef(new DedicatedWorkerGlobalScope(url, userAgent, thread, topOrigin, timeOrigin));
     context->applyContentSecurityPolicyFromString(contentSecurityPolicy, contentSecurityPolicyType);
     return context.release();
 }
 
-DedicatedWorkerContext::DedicatedWorkerContext(const KURL& url, const String& userAgent, PassOwnPtr<GroupSettings> settings, DedicatedWorkerThread* thread, PassRefPtr<SecurityOrigin> topOrigin, double timeOrigin)
-    : WorkerContext(url, userAgent, settings, thread, topOrigin, timeOrigin)
+DedicatedWorkerGlobalScope::DedicatedWorkerGlobalScope(const KURL& url, const String& userAgent, DedicatedWorkerThread* thread, PassRefPtr<SecurityOrigin> topOrigin, double timeOrigin)
+    : WorkerGlobalScope(url, userAgent, thread, topOrigin, timeOrigin)
 {
     ScriptWrappable::init(this);
 }
 
-DedicatedWorkerContext::~DedicatedWorkerContext()
+DedicatedWorkerGlobalScope::~DedicatedWorkerGlobalScope()
 {
 }
 
-const AtomicString& DedicatedWorkerContext::interfaceName() const
+const AtomicString& DedicatedWorkerGlobalScope::interfaceName() const
 {
-    return eventNames().interfaceForDedicatedWorkerContext;
+    return eventNames().interfaceForDedicatedWorkerGlobalScope;
 }
 
-void DedicatedWorkerContext::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionCode& ec)
+void DedicatedWorkerGlobalScope::postMessage(PassRefPtr<SerializedScriptValue> message, const MessagePortArray* ports, ExceptionCode& ec)
 {
     // Disentangle the port in preparation for sending it to the remote context.
     OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, ec);
@@ -69,13 +69,13 @@
     thread()->workerObjectProxy().postMessageToWorkerObject(message, channels.release());
 }
 
-void DedicatedWorkerContext::importScripts(const Vector<String>& urls, ExceptionCode& ec)
+void DedicatedWorkerGlobalScope::importScripts(const Vector<String>& urls, ExceptionCode& ec)
 {
     Base::importScripts(urls, ec);
     thread()->workerObjectProxy().reportPendingActivity(hasPendingActivity());
 }
 
-DedicatedWorkerThread* DedicatedWorkerContext::thread()
+DedicatedWorkerThread* DedicatedWorkerGlobalScope::thread()
 {
     return static_cast<DedicatedWorkerThread*>(Base::thread());
 }
diff --git a/Source/core/workers/DedicatedWorkerContext.h b/Source/core/workers/DedicatedWorkerGlobalScope.h
similarity index 72%
rename from Source/core/workers/DedicatedWorkerContext.h
rename to Source/core/workers/DedicatedWorkerGlobalScope.h
index dfbdbae..9654a46 100644
--- a/Source/core/workers/DedicatedWorkerContext.h
+++ b/Source/core/workers/DedicatedWorkerGlobalScope.h
@@ -28,24 +28,24 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef DedicatedWorkerContext_h
-#define DedicatedWorkerContext_h
+#ifndef DedicatedWorkerGlobalScope_h
+#define DedicatedWorkerGlobalScope_h
 
 #include "core/dom/MessagePort.h"
 #include "core/page/ContentSecurityPolicy.h"
-#include "core/workers/WorkerContext.h"
+#include "core/workers/WorkerGlobalScope.h"
 
 namespace WebCore {
 
     class DedicatedWorkerThread;
 
-    class DedicatedWorkerContext : public WorkerContext {
+    class DedicatedWorkerGlobalScope : public WorkerGlobalScope {
     public:
-        typedef WorkerContext Base;
-        static PassRefPtr<DedicatedWorkerContext> create(const KURL&, const String& userAgent, PassOwnPtr<GroupSettings>, DedicatedWorkerThread*, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, PassRefPtr<SecurityOrigin> topOrigin, double timeOrigin);
-        virtual ~DedicatedWorkerContext();
+        typedef WorkerGlobalScope Base;
+        static PassRefPtr<DedicatedWorkerGlobalScope> create(const KURL&, const String& userAgent, DedicatedWorkerThread*, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, PassRefPtr<SecurityOrigin> topOrigin, double timeOrigin);
+        virtual ~DedicatedWorkerGlobalScope();
 
-        virtual bool isDedicatedWorkerContext() const OVERRIDE { return true; }
+        virtual bool isDedicatedWorkerGlobalScope() const OVERRIDE { return true; }
 
         // Overridden to allow us to check our pending activity after executing imported script.
         virtual void importScripts(const Vector<String>& urls, ExceptionCode&) OVERRIDE;
@@ -60,9 +60,9 @@
         DedicatedWorkerThread* thread();
 
     private:
-        DedicatedWorkerContext(const KURL&, const String& userAgent, PassOwnPtr<GroupSettings>, DedicatedWorkerThread*, PassRefPtr<SecurityOrigin> topOrigin, double timeOrigin);
+        DedicatedWorkerGlobalScope(const KURL&, const String& userAgent, DedicatedWorkerThread*, PassRefPtr<SecurityOrigin> topOrigin, double timeOrigin);
     };
 
 } // namespace WebCore
 
-#endif // DedicatedWorkerContext_h
+#endif // DedicatedWorkerGlobalScope_h
diff --git a/Source/core/workers/DedicatedWorkerContext.idl b/Source/core/workers/DedicatedWorkerGlobalScope.idl
similarity index 93%
rename from Source/core/workers/DedicatedWorkerContext.idl
rename to Source/core/workers/DedicatedWorkerGlobalScope.idl
index 3f4f45c..7cb9399 100644
--- a/Source/core/workers/DedicatedWorkerContext.idl
+++ b/Source/core/workers/DedicatedWorkerGlobalScope.idl
@@ -29,8 +29,8 @@
  */
 
 [
-    NoInterfaceObject
-] interface DedicatedWorkerContext : WorkerContext {
+    GlobalContext=DedicatedWorkerGlobalScope
+] interface DedicatedWorkerGlobalScope : WorkerGlobalScope {
     [Custom, RaisesException] void postMessage(any message, optional Array messagePorts);
     attribute EventListener onmessage;
 };
diff --git a/Source/core/workers/DedicatedWorkerThread.cpp b/Source/core/workers/DedicatedWorkerThread.cpp
index 353ac41..30c44f9 100644
--- a/Source/core/workers/DedicatedWorkerThread.cpp
+++ b/Source/core/workers/DedicatedWorkerThread.cpp
@@ -32,18 +32,18 @@
 
 #include "core/workers/DedicatedWorkerThread.h"
 
-#include "core/workers/DedicatedWorkerContext.h"
+#include "core/workers/DedicatedWorkerGlobalScope.h"
 #include "core/workers/WorkerObjectProxy.h"
 
 namespace WebCore {
 
-PassRefPtr<DedicatedWorkerThread> DedicatedWorkerThread::create(const KURL& scriptURL, const String& userAgent, const GroupSettings* settings, const String& sourceCode, WorkerLoaderProxy& workerLoaderProxy, WorkerObjectProxy& workerObjectProxy, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, const SecurityOrigin* topOrigin, double timeOrigin)
+PassRefPtr<DedicatedWorkerThread> DedicatedWorkerThread::create(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerLoaderProxy& workerLoaderProxy, WorkerObjectProxy& workerObjectProxy, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, const SecurityOrigin* topOrigin, double timeOrigin)
 {
-    return adoptRef(new DedicatedWorkerThread(scriptURL, userAgent, settings, sourceCode, workerLoaderProxy, workerObjectProxy, startMode, contentSecurityPolicy, contentSecurityPolicyType, topOrigin, timeOrigin));
+    return adoptRef(new DedicatedWorkerThread(scriptURL, userAgent, sourceCode, workerLoaderProxy, workerObjectProxy, startMode, contentSecurityPolicy, contentSecurityPolicyType, topOrigin, timeOrigin));
 }
 
-DedicatedWorkerThread::DedicatedWorkerThread(const KURL& url, const String& userAgent, const GroupSettings* settings, const String& sourceCode, WorkerLoaderProxy& workerLoaderProxy, WorkerObjectProxy& workerObjectProxy, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, const SecurityOrigin* topOrigin, double timeOrigin)
-    : WorkerThread(url, userAgent, settings, sourceCode, workerLoaderProxy, workerObjectProxy, startMode, contentSecurityPolicy, contentSecurityPolicyType, topOrigin)
+DedicatedWorkerThread::DedicatedWorkerThread(const KURL& url, const String& userAgent, const String& sourceCode, WorkerLoaderProxy& workerLoaderProxy, WorkerObjectProxy& workerObjectProxy, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, const SecurityOrigin* topOrigin, double timeOrigin)
+    : WorkerThread(url, userAgent, sourceCode, workerLoaderProxy, workerObjectProxy, startMode, contentSecurityPolicy, contentSecurityPolicyType, topOrigin)
     , m_workerObjectProxy(workerObjectProxy)
     , m_timeOrigin(timeOrigin)
 {
@@ -53,15 +53,15 @@
 {
 }
 
-PassRefPtr<WorkerContext> DedicatedWorkerThread::createWorkerContext(const KURL& url, const String& userAgent, PassOwnPtr<GroupSettings> settings, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, PassRefPtr<SecurityOrigin> topOrigin)
+PassRefPtr<WorkerGlobalScope> DedicatedWorkerThread::createWorkerGlobalScope(const KURL& url, const String& userAgent, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, PassRefPtr<SecurityOrigin> topOrigin)
 {
-    return DedicatedWorkerContext::create(url, userAgent, settings, this, contentSecurityPolicy, contentSecurityPolicyType, topOrigin, m_timeOrigin);
+    return DedicatedWorkerGlobalScope::create(url, userAgent, this, contentSecurityPolicy, contentSecurityPolicyType, topOrigin, m_timeOrigin);
 }
 
 void DedicatedWorkerThread::runEventLoop()
 {
     // Notify the parent object of our current active state before calling the superclass to run the event loop.
-    m_workerObjectProxy.reportPendingActivity(workerContext()->hasPendingActivity());
+    m_workerObjectProxy.reportPendingActivity(workerGlobalScope()->hasPendingActivity());
     WorkerThread::runEventLoop();
 }
 
diff --git a/Source/core/workers/DedicatedWorkerThread.h b/Source/core/workers/DedicatedWorkerThread.h
index f386506..d4440e1 100644
--- a/Source/core/workers/DedicatedWorkerThread.h
+++ b/Source/core/workers/DedicatedWorkerThread.h
@@ -39,16 +39,16 @@
 
     class DedicatedWorkerThread : public WorkerThread {
     public:
-        static PassRefPtr<DedicatedWorkerThread> create(const KURL& scriptURL, const String& userAgent, const GroupSettings*, const String& sourceCode, WorkerLoaderProxy&, WorkerObjectProxy&, WorkerThreadStartMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType, const SecurityOrigin* topOrigin, double timeOrigin);
+        static PassRefPtr<DedicatedWorkerThread> create(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerLoaderProxy&, WorkerObjectProxy&, WorkerThreadStartMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType, const SecurityOrigin* topOrigin, double timeOrigin);
         WorkerObjectProxy& workerObjectProxy() const { return m_workerObjectProxy; }
         virtual ~DedicatedWorkerThread();
 
     protected:
-        virtual PassRefPtr<WorkerContext> createWorkerContext(const KURL&, const String& userAgent, PassOwnPtr<GroupSettings>, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType, PassRefPtr<SecurityOrigin> topOrigin) OVERRIDE;
+        virtual PassRefPtr<WorkerGlobalScope> createWorkerGlobalScope(const KURL&, const String& userAgent, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType, PassRefPtr<SecurityOrigin> topOrigin) OVERRIDE;
         virtual void runEventLoop() OVERRIDE;
 
     private:
-        DedicatedWorkerThread(const KURL&, const String& userAgent, const GroupSettings*, const String& sourceCode, WorkerLoaderProxy&, WorkerObjectProxy&, WorkerThreadStartMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType, const SecurityOrigin* topOrigin, double timeOrigin);
+        DedicatedWorkerThread(const KURL&, const String& userAgent, const String& sourceCode, WorkerLoaderProxy&, WorkerObjectProxy&, WorkerThreadStartMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType, const SecurityOrigin* topOrigin, double timeOrigin);
 
         WorkerObjectProxy& m_workerObjectProxy;
         double m_timeOrigin;
diff --git a/Source/core/workers/SharedWorker.cpp b/Source/core/workers/SharedWorker.cpp
index 28298c3..df13db8 100644
--- a/Source/core/workers/SharedWorker.cpp
+++ b/Source/core/workers/SharedWorker.cpp
@@ -54,7 +54,7 @@
 PassRefPtr<SharedWorker> SharedWorker::create(ScriptExecutionContext* context, const String& url, const String& name, ExceptionCode& ec)
 {
     ASSERT(isMainThread());
-    UseCounter::count(static_cast<Document*>(context)->domWindow(), UseCounter::SharedWorkerStart);
+    UseCounter::count(toDocument(context)->domWindow(), UseCounter::SharedWorkerStart);
 
     RefPtr<SharedWorker> worker = adoptRef(new SharedWorker(context));
 
@@ -71,7 +71,7 @@
 
     // We don't currently support nested workers, so workers can only be created from documents.
     ASSERT_WITH_SECURITY_IMPLICATION(context->isDocument());
-    Document* document = static_cast<Document*>(context);
+    Document* document = toDocument(context);
     if (!document->securityOrigin()->canAccessSharedWorkers(document->topOrigin())) {
         ec = SECURITY_ERR;
         return 0;
diff --git a/Source/core/workers/SharedWorker.h b/Source/core/workers/SharedWorker.h
index 859c0c6..a84449b 100644
--- a/Source/core/workers/SharedWorker.h
+++ b/Source/core/workers/SharedWorker.h
@@ -36,7 +36,7 @@
 
 namespace WebCore {
 
-    class SharedWorker : public AbstractWorker {
+    class SharedWorker : public AbstractWorker, public ScriptWrappable {
     public:
         static PassRefPtr<SharedWorker> create(ScriptExecutionContext*, const String& url, const String& name, ExceptionCode&);
         virtual ~SharedWorker();
diff --git a/Source/core/workers/SharedWorker.idl b/Source/core/workers/SharedWorker.idl
index afa905e..90fa944 100644
--- a/Source/core/workers/SharedWorker.idl
+++ b/Source/core/workers/SharedWorker.idl
@@ -33,8 +33,11 @@
     EnabledAtRuntime,
     Constructor(DOMString scriptURL, [Default=NullString] optional DOMString name),
     ConstructorCallWith=ScriptExecutionContext,
-    ConstructorRaisesException
-] interface SharedWorker : AbstractWorker {
+    ConstructorRaisesException,
+    ActiveDOMObject
+] interface SharedWorker : EventTarget {
     readonly attribute MessagePort port;
 };
 
+SharedWorker implements AbstractWorker;
+
diff --git a/Source/core/workers/SharedWorkerContext.cpp b/Source/core/workers/SharedWorkerGlobalScope.cpp
similarity index 68%
rename from Source/core/workers/SharedWorkerContext.cpp
rename to Source/core/workers/SharedWorkerGlobalScope.cpp
index e3352ba..3f74aa0 100644
--- a/Source/core/workers/SharedWorkerContext.cpp
+++ b/Source/core/workers/SharedWorkerGlobalScope.cpp
@@ -30,7 +30,7 @@
 
 #include "config.h"
 
-#include "core/workers/SharedWorkerContext.h"
+#include "core/workers/SharedWorkerGlobalScope.h"
 
 #include "core/dom/EventNames.h"
 #include "core/dom/MessageEvent.h"
@@ -49,37 +49,37 @@
 }
 
 // static
-PassRefPtr<SharedWorkerContext> SharedWorkerContext::create(const String& name, const KURL& url, const String& userAgent, PassOwnPtr<GroupSettings> settings, SharedWorkerThread* thread, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType)
+PassRefPtr<SharedWorkerGlobalScope> SharedWorkerGlobalScope::create(const String& name, const KURL& url, const String& userAgent, SharedWorkerThread* thread, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType)
 {
-    RefPtr<SharedWorkerContext> context = adoptRef(new SharedWorkerContext(name, url, userAgent, settings, thread));
+    RefPtr<SharedWorkerGlobalScope> context = adoptRef(new SharedWorkerGlobalScope(name, url, userAgent, thread));
     context->applyContentSecurityPolicyFromString(contentSecurityPolicy, contentSecurityPolicyType);
     return context.release();
 }
 
-SharedWorkerContext::SharedWorkerContext(const String& name, const KURL& url, const String& userAgent, PassOwnPtr<GroupSettings> settings, SharedWorkerThread* thread)
-    : WorkerContext(url, userAgent, settings, thread, 0, monotonicallyIncreasingTime())
+SharedWorkerGlobalScope::SharedWorkerGlobalScope(const String& name, const KURL& url, const String& userAgent, SharedWorkerThread* thread)
+    : WorkerGlobalScope(url, userAgent, thread, 0, monotonicallyIncreasingTime())
     , m_name(name)
 {
     ScriptWrappable::init(this);
 }
 
-SharedWorkerContext::~SharedWorkerContext()
+SharedWorkerGlobalScope::~SharedWorkerGlobalScope()
 {
 }
 
-const AtomicString& SharedWorkerContext::interfaceName() const
+const AtomicString& SharedWorkerGlobalScope::interfaceName() const
 {
-    return eventNames().interfaceForSharedWorkerContext;
+    return eventNames().interfaceForSharedWorkerGlobalScope;
 }
 
-SharedWorkerThread* SharedWorkerContext::thread()
+SharedWorkerThread* SharedWorkerGlobalScope::thread()
 {
     return static_cast<SharedWorkerThread*>(Base::thread());
 }
 
-void SharedWorkerContext::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack> callStack)
+void SharedWorkerGlobalScope::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack> callStack)
 {
-    WorkerContext::logExceptionToConsole(errorMessage, sourceURL, lineNumber, callStack);
+    WorkerGlobalScope::logExceptionToConsole(errorMessage, sourceURL, lineNumber, callStack);
     addMessageToWorkerConsole(JSMessageSource, ErrorMessageLevel, errorMessage, sourceURL, lineNumber, callStack);
 }
 
diff --git a/Source/core/workers/SharedWorkerContext.h b/Source/core/workers/SharedWorkerGlobalScope.h
similarity index 73%
rename from Source/core/workers/SharedWorkerContext.h
rename to Source/core/workers/SharedWorkerGlobalScope.h
index b43f6ea..1d4a48f 100644
--- a/Source/core/workers/SharedWorkerContext.h
+++ b/Source/core/workers/SharedWorkerGlobalScope.h
@@ -28,36 +28,36 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef SharedWorkerContext_h
-#define SharedWorkerContext_h
+#ifndef SharedWorkerGlobalScope_h
+#define SharedWorkerGlobalScope_h
 
 #include "core/page/ContentSecurityPolicy.h"
-#include "core/workers/WorkerContext.h"
+#include "core/workers/WorkerGlobalScope.h"
 
 namespace WebCore {
 
     class MessageEvent;
     class SharedWorkerThread;
 
-    class SharedWorkerContext : public WorkerContext {
+    class SharedWorkerGlobalScope : public WorkerGlobalScope {
     public:
-        typedef WorkerContext Base;
-        static PassRefPtr<SharedWorkerContext> create(const String& name, const KURL&, const String& userAgent, PassOwnPtr<GroupSettings>, SharedWorkerThread*, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType);
-        virtual ~SharedWorkerContext();
+        typedef WorkerGlobalScope Base;
+        static PassRefPtr<SharedWorkerGlobalScope> create(const String& name, const KURL&, const String& userAgent, SharedWorkerThread*, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType);
+        virtual ~SharedWorkerGlobalScope();
 
-        virtual bool isSharedWorkerContext() const OVERRIDE { return true; }
+        virtual bool isSharedWorkerGlobalScope() const OVERRIDE { return true; }
 
         // EventTarget
         virtual const AtomicString& interfaceName() const OVERRIDE;
 
-        // Setters/Getters for attributes in SharedWorkerContext.idl
+        // Setters/Getters for attributes in SharedWorkerGlobalScope.idl
         DEFINE_ATTRIBUTE_EVENT_LISTENER(connect);
         String name() const { return m_name; }
 
         SharedWorkerThread* thread();
 
     private:
-        SharedWorkerContext(const String& name, const KURL&, const String& userAgent, PassOwnPtr<GroupSettings>, SharedWorkerThread*);
+        SharedWorkerGlobalScope(const String& name, const KURL&, const String& userAgent, SharedWorkerThread*);
         virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack>) OVERRIDE;
 
         String m_name;
@@ -67,4 +67,4 @@
 
 } // namespace WebCore
 
-#endif // SharedWorkerContext_h
+#endif // SharedWorkerGlobalScope_h
diff --git a/Source/core/workers/SharedWorkerContext.idl b/Source/core/workers/SharedWorkerGlobalScope.idl
similarity index 93%
rename from Source/core/workers/SharedWorkerContext.idl
rename to Source/core/workers/SharedWorkerGlobalScope.idl
index 52fc0a2..4c930a4 100644
--- a/Source/core/workers/SharedWorkerContext.idl
+++ b/Source/core/workers/SharedWorkerGlobalScope.idl
@@ -29,8 +29,8 @@
  */
 
 [
-    NoInterfaceObject
-] interface SharedWorkerContext : WorkerContext {
+    GlobalContext=SharedWorkerGlobalScope
+] interface SharedWorkerGlobalScope : WorkerGlobalScope {
     readonly attribute DOMString name;
              attribute EventListener onconnect;
 };
diff --git a/Source/core/workers/SharedWorkerThread.cpp b/Source/core/workers/SharedWorkerThread.cpp
index 032af44..3688eb1 100644
--- a/Source/core/workers/SharedWorkerThread.cpp
+++ b/Source/core/workers/SharedWorkerThread.cpp
@@ -32,17 +32,17 @@
 
 #include "core/workers/SharedWorkerThread.h"
 
-#include "core/workers/SharedWorkerContext.h"
+#include "core/workers/SharedWorkerGlobalScope.h"
 
 namespace WebCore {
 
-PassRefPtr<SharedWorkerThread> SharedWorkerThread::create(const String& name, const KURL& scriptURL, const String& userAgent, const GroupSettings* settings, const String& sourceCode, WorkerLoaderProxy& workerLoaderProxy, WorkerReportingProxy& workerReportingProxy, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType)
+PassRefPtr<SharedWorkerThread> SharedWorkerThread::create(const String& name, const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerLoaderProxy& workerLoaderProxy, WorkerReportingProxy& workerReportingProxy, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType)
 {
-    return adoptRef(new SharedWorkerThread(name, scriptURL, userAgent, settings, sourceCode, workerLoaderProxy, workerReportingProxy, startMode, contentSecurityPolicy, contentSecurityPolicyType));
+    return adoptRef(new SharedWorkerThread(name, scriptURL, userAgent, sourceCode, workerLoaderProxy, workerReportingProxy, startMode, contentSecurityPolicy, contentSecurityPolicyType));
 }
 
-SharedWorkerThread::SharedWorkerThread(const String& name, const KURL& url, const String& userAgent, const GroupSettings* settings, const String& sourceCode, WorkerLoaderProxy& workerLoaderProxy, WorkerReportingProxy& workerReportingProxy, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType)
-    : WorkerThread(url, userAgent, settings, sourceCode, workerLoaderProxy, workerReportingProxy, startMode, contentSecurityPolicy, contentSecurityPolicyType, 0)
+SharedWorkerThread::SharedWorkerThread(const String& name, const KURL& url, const String& userAgent, const String& sourceCode, WorkerLoaderProxy& workerLoaderProxy, WorkerReportingProxy& workerReportingProxy, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType)
+    : WorkerThread(url, userAgent, sourceCode, workerLoaderProxy, workerReportingProxy, startMode, contentSecurityPolicy, contentSecurityPolicyType, 0)
     , m_name(name.isolatedCopy())
 {
 }
@@ -51,9 +51,9 @@
 {
 }
 
-PassRefPtr<WorkerContext> SharedWorkerThread::createWorkerContext(const KURL& url, const String& userAgent, PassOwnPtr<GroupSettings> settings, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, PassRefPtr<SecurityOrigin>)
+PassRefPtr<WorkerGlobalScope> SharedWorkerThread::createWorkerGlobalScope(const KURL& url, const String& userAgent, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, PassRefPtr<SecurityOrigin>)
 {
-    return SharedWorkerContext::create(m_name, url, userAgent, settings, this, contentSecurityPolicy, contentSecurityPolicyType);
+    return SharedWorkerGlobalScope::create(m_name, url, userAgent, this, contentSecurityPolicy, contentSecurityPolicyType);
 }
 
 } // namespace WebCore
diff --git a/Source/core/workers/SharedWorkerThread.h b/Source/core/workers/SharedWorkerThread.h
index e30509a..955ce4f 100644
--- a/Source/core/workers/SharedWorkerThread.h
+++ b/Source/core/workers/SharedWorkerThread.h
@@ -37,14 +37,14 @@
 
     class SharedWorkerThread : public WorkerThread {
     public:
-        static PassRefPtr<SharedWorkerThread> create(const String& name, const KURL&, const String& userAgent, const GroupSettings*, const String& sourceCode, WorkerLoaderProxy&, WorkerReportingProxy&, WorkerThreadStartMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType);
+        static PassRefPtr<SharedWorkerThread> create(const String& name, const KURL&, const String& userAgent, const String& sourceCode, WorkerLoaderProxy&, WorkerReportingProxy&, WorkerThreadStartMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType);
         virtual ~SharedWorkerThread();
 
     protected:
-        virtual PassRefPtr<WorkerContext> createWorkerContext(const KURL&, const String& userAgent, PassOwnPtr<GroupSettings>, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType, PassRefPtr<SecurityOrigin> topOrigin) OVERRIDE;
+        virtual PassRefPtr<WorkerGlobalScope> createWorkerGlobalScope(const KURL&, const String& userAgent, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType, PassRefPtr<SecurityOrigin> topOrigin) OVERRIDE;
 
     private:
-        SharedWorkerThread(const String& name, const KURL&, const String& userAgent, const GroupSettings*, const String& sourceCode, WorkerLoaderProxy&, WorkerReportingProxy&, WorkerThreadStartMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType);
+        SharedWorkerThread(const String& name, const KURL&, const String& userAgent, const String& sourceCode, WorkerLoaderProxy&, WorkerReportingProxy&, WorkerThreadStartMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType);
 
         String m_name;
     };
diff --git a/Source/core/workers/Worker.cpp b/Source/core/workers/Worker.cpp
index 00389db..a5f8893 100644
--- a/Source/core/workers/Worker.cpp
+++ b/Source/core/workers/Worker.cpp
@@ -40,7 +40,7 @@
 #include "core/page/DOMWindow.h"
 #include "core/page/Frame.h"
 #include "core/page/UseCounter.h"
-#include "core/workers/WorkerContextProxy.h"
+#include "core/workers/WorkerGlobalScopeProxy.h"
 #include "core/workers/WorkerScriptLoader.h"
 #include "core/workers/WorkerThread.h"
 #include "wtf/MainThread.h"
@@ -49,7 +49,7 @@
 
 inline Worker::Worker(ScriptExecutionContext* context)
     : AbstractWorker(context)
-    , m_contextProxy(WorkerContextProxy::create(this))
+    , m_contextProxy(WorkerGlobalScopeProxy::create(this))
 {
     ScriptWrappable::init(this);
 }
@@ -57,7 +57,7 @@
 PassRefPtr<Worker> Worker::create(ScriptExecutionContext* context, const String& url, ExceptionCode& ec)
 {
     ASSERT(isMainThread());
-    UseCounter::count(static_cast<Document*>(context)->domWindow(), UseCounter::WorkerStart);
+    UseCounter::count(toDocument(context)->domWindow(), UseCounter::WorkerStart);
 
     RefPtr<Worker> worker = adoptRef(new Worker(context));
 
@@ -94,12 +94,12 @@
     OwnPtr<MessagePortChannelArray> channels = MessagePort::disentanglePorts(ports, ec);
     if (ec)
         return;
-    m_contextProxy->postMessageToWorkerContext(message, channels.release());
+    m_contextProxy->postMessageToWorkerGlobalScope(message, channels.release());
 }
 
 void Worker::terminate()
 {
-    m_contextProxy->terminateWorkerContext();
+    m_contextProxy->terminateWorkerGlobalScope();
 }
 
 bool Worker::canSuspend() const
@@ -128,10 +128,10 @@
     if (m_scriptLoader->failed())
         dispatchEvent(Event::create(eventNames().errorEvent, false, true));
     else {
-        WorkerThreadStartMode startMode = DontPauseWorkerContextOnStart;
+        WorkerThreadStartMode startMode = DontPauseWorkerGlobalScopeOnStart;
         if (InspectorInstrumentation::shouldPauseDedicatedWorkerOnStart(scriptExecutionContext()))
-            startMode = PauseWorkerContextOnStart;
-        m_contextProxy->startWorkerContext(m_scriptLoader->url(), scriptExecutionContext()->userAgent(m_scriptLoader->url()), m_scriptLoader->script(), startMode);
+            startMode = PauseWorkerGlobalScopeOnStart;
+        m_contextProxy->startWorkerGlobalScope(m_scriptLoader->url(), scriptExecutionContext()->userAgent(m_scriptLoader->url()), m_scriptLoader->script(), startMode);
         InspectorInstrumentation::scriptImported(scriptExecutionContext(), m_scriptLoader->identifier(), m_scriptLoader->script());
     }
     m_scriptLoader = nullptr;
diff --git a/Source/core/workers/Worker.h b/Source/core/workers/Worker.h
index 64100b0..b11bf48 100644
--- a/Source/core/workers/Worker.h
+++ b/Source/core/workers/Worker.h
@@ -42,12 +42,12 @@
 namespace WebCore {
 
     class ScriptExecutionContext;
-    class WorkerContextProxy;
+    class WorkerGlobalScopeProxy;
     class WorkerScriptLoader;
 
     typedef int ExceptionCode;
 
-    class Worker : public AbstractWorker, private WorkerScriptLoaderClient {
+    class Worker : public AbstractWorker, public ScriptWrappable, private WorkerScriptLoaderClient {
     public:
         static PassRefPtr<Worker> create(ScriptExecutionContext*, const String& url, ExceptionCode&);
         virtual ~Worker();
@@ -61,7 +61,7 @@
         virtual bool canSuspend() const OVERRIDE;
         virtual void stop() OVERRIDE;
         virtual bool hasPendingActivity() const OVERRIDE;
-    
+
         DEFINE_ATTRIBUTE_EVENT_LISTENER(message);
 
     private:
@@ -75,7 +75,7 @@
         virtual void derefEventTarget() OVERRIDE { deref(); }
 
         RefPtr<WorkerScriptLoader> m_scriptLoader;
-        WorkerContextProxy* m_contextProxy; // The proxy outlives the worker to perform thread shutdown.
+        WorkerGlobalScopeProxy* m_contextProxy; // The proxy outlives the worker to perform thread shutdown.
     };
 
 } // namespace WebCore
diff --git a/Source/core/workers/Worker.idl b/Source/core/workers/Worker.idl
index 4315ab9..ab7f280 100644
--- a/Source/core/workers/Worker.idl
+++ b/Source/core/workers/Worker.idl
@@ -28,8 +28,9 @@
 [
     Constructor(DOMString scriptUrl),
     ConstructorCallWith=ScriptExecutionContext,
-    ConstructorRaisesException
-] interface Worker : AbstractWorker {
+    ConstructorRaisesException,
+    ActiveDOMObject
+] interface Worker : EventTarget {
 
     attribute EventListener onmessage;
 
@@ -37,3 +38,5 @@
     void terminate();
 };
 
+Worker implements AbstractWorker;
+
diff --git a/Source/core/workers/WorkerContext.cpp b/Source/core/workers/WorkerGlobalScope.cpp
similarity index 67%
rename from Source/core/workers/WorkerContext.cpp
rename to Source/core/workers/WorkerGlobalScope.cpp
index e6b5010..cc45d63 100644
--- a/Source/core/workers/WorkerContext.cpp
+++ b/Source/core/workers/WorkerGlobalScope.cpp
@@ -27,14 +27,13 @@
 
 #include "config.h"
 
-#include "core/workers/WorkerContext.h"
+#include "core/workers/WorkerGlobalScope.h"
 
-#include <wtf/RefPtr.h>
-#include <wtf/UnusedParam.h>
 #include "bindings/v8/ScheduledAction.h"
 #include "bindings/v8/ScriptSourceCode.h"
 #include "bindings/v8/ScriptValue.h"
 #include "core/dom/ActiveDOMObject.h"
+#include "core/dom/ContextLifecycleNotifier.h"
 #include "core/dom/ErrorEvent.h"
 #include "core/dom/Event.h"
 #include "core/dom/MessagePort.h"
@@ -54,6 +53,8 @@
 #include "core/workers/WorkerThread.h"
 #include "weborigin/KURL.h"
 #include "weborigin/SecurityOrigin.h"
+#include "wtf/RefPtr.h"
+#include "wtf/UnusedParam.h"
 
 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
 #include "modules/notifications/NotificationCenter.h"
@@ -63,28 +64,26 @@
 
 namespace WebCore {
 
-class CloseWorkerContextTask : public ScriptExecutionContext::Task {
+class CloseWorkerGlobalScopeTask : public ScriptExecutionContext::Task {
 public:
-    static PassOwnPtr<CloseWorkerContextTask> create()
+    static PassOwnPtr<CloseWorkerGlobalScopeTask> create()
     {
-        return adoptPtr(new CloseWorkerContextTask);
+        return adoptPtr(new CloseWorkerGlobalScopeTask);
     }
 
     virtual void performTask(ScriptExecutionContext *context)
     {
-        ASSERT_WITH_SECURITY_IMPLICATION(context->isWorkerContext());
-        WorkerContext* workerContext = static_cast<WorkerContext*>(context);
+        WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
         // Notify parent that this context is closed. Parent is responsible for calling WorkerThread::stop().
-        workerContext->thread()->workerReportingProxy().workerContextClosed();
+        workerGlobalScope->thread()->workerReportingProxy().workerGlobalScopeClosed();
     }
 
     virtual bool isCleanupTask() const { return true; }
 };
 
-WorkerContext::WorkerContext(const KURL& url, const String& userAgent, PassOwnPtr<GroupSettings> settings, WorkerThread* thread, PassRefPtr<SecurityOrigin> topOrigin, double timeOrigin)
+WorkerGlobalScope::WorkerGlobalScope(const KURL& url, const String& userAgent, WorkerThread* thread, PassRefPtr<SecurityOrigin> topOrigin, double timeOrigin)
     : m_url(url)
     , m_userAgent(userAgent)
-    , m_groupSettings(settings)
     , m_script(adoptPtr(new WorkerScriptController(this)))
     , m_thread(thread)
     , m_workerInspectorController(adoptPtr(new WorkerInspectorController(this)))
@@ -97,7 +96,7 @@
     setSecurityOrigin(SecurityOrigin::create(url));
 }
 
-WorkerContext::~WorkerContext()
+WorkerGlobalScope::~WorkerGlobalScope()
 {
     ASSERT(thread()->isCurrentThread());
 
@@ -105,31 +104,31 @@
     notifyObserversOfStop();
 
     // Notify proxy that we are going away. This can free the WorkerThread object, so do not access it after this.
-    thread()->workerReportingProxy().workerContextDestroyed();
+    thread()->workerReportingProxy().workerGlobalScopeDestroyed();
 }
 
-void WorkerContext::applyContentSecurityPolicyFromString(const String& policy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType)
+void WorkerGlobalScope::applyContentSecurityPolicyFromString(const String& policy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType)
 {
     setContentSecurityPolicy(ContentSecurityPolicy::create(this));
     contentSecurityPolicy()->didReceiveHeader(policy, contentSecurityPolicyType);
 }
 
-ScriptExecutionContext* WorkerContext::scriptExecutionContext() const
+ScriptExecutionContext* WorkerGlobalScope::scriptExecutionContext() const
 {
-    return const_cast<WorkerContext*>(this);
+    return const_cast<WorkerGlobalScope*>(this);
 }
 
-const KURL& WorkerContext::virtualURL() const
+const KURL& WorkerGlobalScope::virtualURL() const
 {
     return m_url;
 }
 
-KURL WorkerContext::virtualCompleteURL(const String& url) const
+KURL WorkerGlobalScope::virtualCompleteURL(const String& url) const
 {
     return completeURL(url);
 }
 
-KURL WorkerContext::completeURL(const String& url) const
+KURL WorkerGlobalScope::completeURL(const String& url) const
 {
     // Always return a null URL when passed a null string.
     // FIXME: Should we change the KURL constructor to have this behavior?
@@ -139,24 +138,24 @@
     return KURL(m_url, url);
 }
 
-String WorkerContext::userAgent(const KURL&) const
+String WorkerGlobalScope::userAgent(const KURL&) const
 {
     return m_userAgent;
 }
 
-void WorkerContext::disableEval(const String& errorMessage)
+void WorkerGlobalScope::disableEval(const String& errorMessage)
 {
     m_script->disableEval(errorMessage);
 }
 
-WorkerLocation* WorkerContext::location() const
+WorkerLocation* WorkerGlobalScope::location() const
 {
     if (!m_location)
         m_location = WorkerLocation::create(m_url);
     return m_location.get();
 }
 
-void WorkerContext::close()
+void WorkerGlobalScope::close()
 {
     if (m_closing)
         return;
@@ -165,64 +164,47 @@
     // After m_closing is set, all the tasks in the queue continue to be fetched but only
     // tasks with isCleanupTask()==true will be executed.
     m_closing = true;
-    postTask(CloseWorkerContextTask::create());
+    postTask(CloseWorkerGlobalScopeTask::create());
 }
 
-WorkerNavigator* WorkerContext::navigator() const
+WorkerNavigator* WorkerGlobalScope::navigator() const
 {
     if (!m_navigator)
         m_navigator = WorkerNavigator::create(m_userAgent);
     return m_navigator.get();
 }
 
-bool WorkerContext::hasPendingActivity() const
-{
-    ActiveDOMObjectsSet::const_iterator activeObjectsEnd = activeDOMObjects().end();
-    for (ActiveDOMObjectsSet::const_iterator iter = activeDOMObjects().begin(); iter != activeObjectsEnd; ++iter) {
-        if ((*iter)->hasPendingActivity())
-            return true;
-    }
-
-    HashSet<MessagePort*>::const_iterator messagePortsEnd = messagePorts().end();
-    for (HashSet<MessagePort*>::const_iterator iter = messagePorts().begin(); iter != messagePortsEnd; ++iter) {
-        if ((*iter)->hasPendingActivity())
-            return true;
-    }
-
-    return false;
-}
-
-void WorkerContext::postTask(PassOwnPtr<Task> task)
+void WorkerGlobalScope::postTask(PassOwnPtr<Task> task)
 {
     thread()->runLoop().postTask(task);
 }
 
-int WorkerContext::setTimeout(PassOwnPtr<ScheduledAction> action, int timeout)
+int WorkerGlobalScope::setTimeout(PassOwnPtr<ScheduledAction> action, int timeout)
 {
     return DOMTimer::install(scriptExecutionContext(), action, timeout, true);
 }
 
-void WorkerContext::clearTimeout(int timeoutId)
+void WorkerGlobalScope::clearTimeout(int timeoutId)
 {
     DOMTimer::removeById(scriptExecutionContext(), timeoutId);
 }
 
-void WorkerContext::clearInspector()
+void WorkerGlobalScope::clearInspector()
 {
     m_workerInspectorController.clear();
 }
 
-int WorkerContext::setInterval(PassOwnPtr<ScheduledAction> action, int timeout)
+int WorkerGlobalScope::setInterval(PassOwnPtr<ScheduledAction> action, int timeout)
 {
     return DOMTimer::install(scriptExecutionContext(), action, timeout, false);
 }
 
-void WorkerContext::clearInterval(int timeoutId)
+void WorkerGlobalScope::clearInterval(int timeoutId)
 {
     DOMTimer::removeById(scriptExecutionContext(), timeoutId);
 }
 
-void WorkerContext::importScripts(const Vector<String>& urls, ExceptionCode& ec)
+void WorkerGlobalScope::importScripts(const Vector<String>& urls, ExceptionCode& ec)
 {
     ASSERT(contentSecurityPolicy());
     ec = 0;
@@ -260,17 +242,17 @@
     }
 }
 
-EventTarget* WorkerContext::errorEventTarget()
+EventTarget* WorkerGlobalScope::errorEventTarget()
 {
     return this;
 }
 
-void WorkerContext::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack>)
+void WorkerGlobalScope::logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack>)
 {
     thread()->workerReportingProxy().postExceptionToWorkerObject(errorMessage, lineNumber, sourceURL);
 }
 
-void WorkerContext::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
+void WorkerGlobalScope::addConsoleMessage(MessageSource source, MessageLevel level, const String& message, unsigned long requestIdentifier)
 {
     if (!isContextThread()) {
         postTask(AddConsoleMessageTask::create(source, level, message));
@@ -281,7 +263,7 @@
     addMessageToWorkerConsole(source, level, message, String(), 0, 0, 0, requestIdentifier);
 }
 
-void WorkerContext::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state, unsigned long requestIdentifier)
+void WorkerGlobalScope::addMessage(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state, unsigned long requestIdentifier)
 {
     if (!isContextThread()) {
         postTask(AddConsoleMessageTask::create(source, level, message));
@@ -291,43 +273,43 @@
     addMessageToWorkerConsole(source, level, message, sourceURL, lineNumber, callStack, state, requestIdentifier);
 }
 
-void WorkerContext::addMessageToWorkerConsole(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state, unsigned long requestIdentifier)
+void WorkerGlobalScope::addMessageToWorkerConsole(MessageSource source, MessageLevel level, const String& message, const String& sourceURL, unsigned lineNumber, PassRefPtr<ScriptCallStack> callStack, ScriptState* state, unsigned long requestIdentifier)
 {
     ASSERT(isContextThread());
     if (callStack)
         InspectorInstrumentation::addMessageToConsole(this, source, LogMessageType, level, message, callStack, requestIdentifier);
     else
-        InspectorInstrumentation::addMessageToConsole(this, source, LogMessageType, level, message, sourceURL, lineNumber, state, requestIdentifier);
+        InspectorInstrumentation::addMessageToConsole(this, source, LogMessageType, level, message, sourceURL, lineNumber, 0, state, requestIdentifier);
 }
 
-bool WorkerContext::isContextThread() const
+bool WorkerGlobalScope::isContextThread() const
 {
     return thread()->isCurrentThread();
 }
 
-bool WorkerContext::isJSExecutionForbidden() const
+bool WorkerGlobalScope::isJSExecutionForbidden() const
 {
     return m_script->isExecutionForbidden();
 }
 
-EventTargetData* WorkerContext::eventTargetData()
+EventTargetData* WorkerGlobalScope::eventTargetData()
 {
     return &m_eventTargetData;
 }
 
-EventTargetData* WorkerContext::ensureEventTargetData()
+EventTargetData* WorkerGlobalScope::ensureEventTargetData()
 {
     return &m_eventTargetData;
 }
 
-WorkerContext::Observer::Observer(WorkerContext* context)
+WorkerGlobalScope::Observer::Observer(WorkerGlobalScope* context)
     : m_context(context)
 {
     ASSERT(m_context && m_context->isContextThread());
     m_context->registerObserver(this);
 }
 
-WorkerContext::Observer::~Observer()
+WorkerGlobalScope::Observer::~Observer()
 {
     if (!m_context)
         return;
@@ -335,7 +317,7 @@
     m_context->unregisterObserver(this);
 }
 
-void WorkerContext::Observer::stopObserving()
+void WorkerGlobalScope::Observer::stopObserving()
 {
     if (!m_context)
         return;
@@ -344,30 +326,30 @@
     m_context = 0;
 }
 
-void WorkerContext::registerObserver(Observer* observer)
+void WorkerGlobalScope::registerObserver(Observer* observer)
 {
     ASSERT(observer);
     m_workerObservers.add(observer);
 }
 
-void WorkerContext::unregisterObserver(Observer* observer)
+void WorkerGlobalScope::unregisterObserver(Observer* observer)
 {
     ASSERT(observer);
     m_workerObservers.remove(observer);
 }
 
-void WorkerContext::notifyObserversOfStop()
+void WorkerGlobalScope::notifyObserversOfStop()
 {
     HashSet<Observer*>::iterator iter = m_workerObservers.begin();
     while (iter != m_workerObservers.end()) {
-        WorkerContext::Observer* observer = *iter;
+        WorkerGlobalScope::Observer* observer = *iter;
         observer->stopObserving();
         observer->notifyStop();
         iter = m_workerObservers.begin();
     }
 }
 
-WorkerEventQueue* WorkerContext::eventQueue() const
+WorkerEventQueue* WorkerGlobalScope::eventQueue() const
 {
     return m_eventQueue.get();
 }
diff --git a/Source/core/workers/WorkerContext.h b/Source/core/workers/WorkerGlobalScope.h
similarity index 81%
rename from Source/core/workers/WorkerContext.h
rename to Source/core/workers/WorkerGlobalScope.h
index a015af3..d8826a5 100644
--- a/Source/core/workers/WorkerContext.h
+++ b/Source/core/workers/WorkerGlobalScope.h
@@ -24,8 +24,8 @@
  *
  */
 
-#ifndef WorkerContext_h
-#define WorkerContext_h
+#ifndef WorkerGlobalScope_h
+#define WorkerGlobalScope_h
 
 #include "bindings/v8/ScriptWrappable.h"
 #include "bindings/v8/WorkerScriptController.h"
@@ -34,15 +34,14 @@
 #include "core/dom/EventTarget.h"
 #include "core/dom/ScriptExecutionContext.h"
 #include "core/page/ContentSecurityPolicy.h"
-#include "core/page/GroupSettings.h"
 #include "core/workers/WorkerEventQueue.h"
-#include <wtf/Assertions.h>
-#include <wtf/HashMap.h>
-#include <wtf/OwnPtr.h>
-#include <wtf/PassRefPtr.h>
-#include <wtf/RefCounted.h>
-#include <wtf/RefPtr.h>
-#include <wtf/text/AtomicStringHash.h>
+#include "wtf/Assertions.h"
+#include "wtf/HashMap.h"
+#include "wtf/OwnPtr.h"
+#include "wtf/PassRefPtr.h"
+#include "wtf/RefCounted.h"
+#include "wtf/RefPtr.h"
+#include "wtf/text/AtomicStringHash.h"
 
 namespace WebCore {
 
@@ -54,21 +53,20 @@
     class WorkerNavigator;
     class WorkerThread;
 
-    class WorkerContext : public RefCounted<WorkerContext>, public ScriptWrappable, public ScriptExecutionContext, public EventTarget {
+    class WorkerGlobalScope : public RefCounted<WorkerGlobalScope>, public ScriptWrappable, public ScriptExecutionContext, public EventTarget {
     public:
-        virtual ~WorkerContext();
+        virtual ~WorkerGlobalScope();
 
-        virtual bool isWorkerContext() const OVERRIDE { return true; }
+        virtual bool isWorkerGlobalScope() const OVERRIDE { return true; }
 
         virtual ScriptExecutionContext* scriptExecutionContext() const OVERRIDE;
 
-        virtual bool isSharedWorkerContext() const { return false; }
-        virtual bool isDedicatedWorkerContext() const { return false; }
+        virtual bool isSharedWorkerGlobalScope() const { return false; }
+        virtual bool isDedicatedWorkerGlobalScope() const { return false; }
 
         const KURL& url() const { return m_url; }
         KURL completeURL(const String&) const;
 
-        const GroupSettings* groupSettings() { return m_groupSettings.get(); }
         virtual String userAgent(const KURL&) const;
 
         virtual void disableEval(const String& errorMessage) OVERRIDE;
@@ -79,12 +77,10 @@
 
         WorkerThread* thread() const { return m_thread; }
 
-        bool hasPendingActivity() const;
-
         virtual void postTask(PassOwnPtr<Task>) OVERRIDE; // Executes the task on context's thread asynchronously.
 
         // WorkerGlobalScope
-        WorkerContext* self() { return this; }
+        WorkerGlobalScope* self() { return this; }
         WorkerLocation* location() const;
         void close();
 
@@ -107,13 +103,13 @@
         virtual bool isJSExecutionForbidden() const OVERRIDE;
 
         WorkerInspectorController* workerInspectorController() { return m_workerInspectorController.get(); }
-        // These methods are used for GC marking. See JSWorkerContext::visitChildrenVirtual(SlotVisitor&) in
-        // JSWorkerContextCustom.cpp.
+        // These methods are used for GC marking. See JSWorkerGlobalScope::visitChildrenVirtual(SlotVisitor&) in
+        // JSWorkerGlobalScopeCustom.cpp.
         WorkerNavigator* optionalNavigator() const { return m_navigator.get(); }
         WorkerLocation* optionalLocation() const { return m_location.get(); }
 
-        using RefCounted<WorkerContext>::ref;
-        using RefCounted<WorkerContext>::deref;
+        using RefCounted<WorkerGlobalScope>::ref;
+        using RefCounted<WorkerGlobalScope>::deref;
 
         bool isClosing() { return m_closing; }
 
@@ -121,12 +117,12 @@
         class Observer {
             WTF_MAKE_NONCOPYABLE(Observer);
         public:
-            Observer(WorkerContext*);
+            Observer(WorkerGlobalScope*);
             virtual ~Observer();
             virtual void notifyStop() = 0;
             void stopObserving();
         private:
-            WorkerContext* m_context;
+            WorkerGlobalScope* m_context;
         };
         friend class Observer;
         void registerObserver(Observer*);
@@ -138,7 +134,7 @@
         double timeOrigin() const { return m_timeOrigin; }
 
     protected:
-        WorkerContext(const KURL&, const String& userAgent, PassOwnPtr<GroupSettings>, WorkerThread*, PassRefPtr<SecurityOrigin> topOrigin, double timeOrigin);
+        WorkerGlobalScope(const KURL&, const String& userAgent, WorkerThread*, PassRefPtr<SecurityOrigin> topOrigin, double timeOrigin);
         void applyContentSecurityPolicyFromString(const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType);
 
         virtual void logExceptionToConsole(const String& errorMessage, const String& sourceURL, int lineNumber, PassRefPtr<ScriptCallStack>) OVERRIDE;
@@ -163,7 +159,6 @@
 
         KURL m_url;
         String m_userAgent;
-        OwnPtr<GroupSettings> m_groupSettings;
 
         mutable RefPtr<WorkerLocation> m_location;
         mutable RefPtr<WorkerNavigator> m_navigator;
@@ -185,6 +180,12 @@
         double m_timeOrigin;
     };
 
+inline WorkerGlobalScope* toWorkerGlobalScope(ScriptExecutionContext* context)
+{
+    ASSERT_WITH_SECURITY_IMPLICATION(!context || context->isWorkerGlobalScope());
+    return static_cast<WorkerGlobalScope*>(context);
+}
+
 } // namespace WebCore
 
-#endif // WorkerContext_h
+#endif // WorkerGlobalScope_h
diff --git a/Source/core/workers/WorkerContext.idl b/Source/core/workers/WorkerGlobalScope.idl
similarity index 76%
rename from Source/core/workers/WorkerContext.idl
rename to Source/core/workers/WorkerGlobalScope.idl
index e513baf..f00ed3f 100644
--- a/Source/core/workers/WorkerContext.idl
+++ b/Source/core/workers/WorkerGlobalScope.idl
@@ -25,28 +25,21 @@
  */
 
 [
-    NoInterfaceObject,
+    GlobalContext=WorkerGlobalScope,
     EventTarget,
     CustomToV8,
     DoNotGenerateWrap
-] interface WorkerContext {
+] interface WorkerGlobalScope {
 
     // WorkerGlobalScope
-             [Replaceable] readonly attribute  WorkerContext self;
-             [Replaceable] readonly attribute WorkerLocation location;
+    [Replaceable] readonly attribute WorkerGlobalScope self;
+    [Replaceable] readonly attribute WorkerLocation location;
     void close();
-             attribute EventListener onerror;
+    attribute EventListener onerror;
 
     // WorkerUtils
     [Custom] void importScripts(/*[Variadic] in DOMString urls */);
-             [Replaceable] readonly attribute WorkerNavigator navigator;
-
-    // Timers
-    [Custom] long setTimeout(any handler, [Default=Undefined] optional long timeout);
-    void clearTimeout([Default=Undefined] optional long handle);
-    [Custom] long setInterval(any handler, [Default=Undefined] optional long timeout);
-    void clearInterval([Default=Undefined] optional long handle);
-
+    [Replaceable] readonly attribute WorkerNavigator navigator;
 
     // EventTarget interface
     void addEventListener(DOMString type, 
@@ -61,3 +54,5 @@
     attribute URLConstructor webkitURL; // FIXME: deprecate this.
 };
 
+WorkerGlobalScope implements WindowTimers;
+
diff --git a/Source/core/workers/WorkerContextProxy.cpp b/Source/core/workers/WorkerGlobalScopeProxy.cpp
similarity index 92%
rename from Source/core/workers/WorkerContextProxy.cpp
rename to Source/core/workers/WorkerGlobalScopeProxy.cpp
index 7f0ff2e..06471bb 100644
--- a/Source/core/workers/WorkerContextProxy.cpp
+++ b/Source/core/workers/WorkerGlobalScopeProxy.cpp
@@ -29,10 +29,10 @@
  */
 
 #include "config.h"
-#include "core/workers/WorkerContextProxy.h"
+#include "core/workers/WorkerGlobalScopeProxy.h"
 
 namespace WebCore {
 
-WorkerContextProxy::CreateDelegate* WorkerContextProxy::s_createDelegate = 0;
+WorkerGlobalScopeProxy::CreateDelegate* WorkerGlobalScopeProxy::s_createDelegate = 0;
 
 } // namespace WebCore
diff --git a/Source/core/workers/WorkerContextProxy.h b/Source/core/workers/WorkerGlobalScopeProxy.h
similarity index 76%
rename from Source/core/workers/WorkerContextProxy.h
rename to Source/core/workers/WorkerGlobalScopeProxy.h
index 6b1858e..67ffca3 100644
--- a/Source/core/workers/WorkerContextProxy.h
+++ b/Source/core/workers/WorkerGlobalScopeProxy.h
@@ -28,36 +28,36 @@
  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  */
 
-#ifndef WorkerContextProxy_h
-#define WorkerContextProxy_h
+#ifndef WorkerGlobalScopeProxy_h
+#define WorkerGlobalScopeProxy_h
 
 #include "core/dom/MessagePort.h"
 #include "core/workers/WorkerThread.h"
-#include <wtf/Forward.h>
-#include <wtf/PassOwnPtr.h>
+#include "wtf/Forward.h"
+#include "wtf/PassOwnPtr.h"
 
 namespace WebCore {
 
     class KURL;
     class Worker;
 
-    // A proxy to talk to the worker context.
-    class WorkerContextProxy {
+    // A proxy to talk to the worker global scope.
+    class WorkerGlobalScopeProxy {
     public:
-        typedef WorkerContextProxy* CreateDelegate(Worker*);
+        typedef WorkerGlobalScopeProxy* CreateDelegate(Worker*);
 
         // FIXME: Instead of delegating through a static factory function we
         // should probably go through some client interface like ChromeClient.
-        static WorkerContextProxy* create(Worker* worker) { return s_createDelegate(worker); }
+        static WorkerGlobalScopeProxy* create(Worker* worker) { return s_createDelegate(worker); }
         static void setCreateDelegate(CreateDelegate* delegate) { s_createDelegate = delegate; }
 
-        virtual ~WorkerContextProxy() {}
+        virtual ~WorkerGlobalScopeProxy() { }
 
-        virtual void startWorkerContext(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode) = 0;
+        virtual void startWorkerGlobalScope(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode) = 0;
 
-        virtual void terminateWorkerContext() = 0;
+        virtual void terminateWorkerGlobalScope() = 0;
 
-        virtual void postMessageToWorkerContext(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>) = 0;
+        virtual void postMessageToWorkerGlobalScope(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>) = 0;
 
         virtual bool hasPendingActivity() const = 0;
 
@@ -78,4 +78,4 @@
 
 } // namespace WebCore
 
-#endif // WorkerContextProxy_h
+#endif // WorkerGlobalScopeProxy_h
diff --git a/Source/core/workers/WorkerLoaderProxy.h b/Source/core/workers/WorkerLoaderProxy.h
index ac5bc48..3342d90 100644
--- a/Source/core/workers/WorkerLoaderProxy.h
+++ b/Source/core/workers/WorkerLoaderProxy.h
@@ -53,10 +53,10 @@
         // Posts a task to the thread which runs the loading code (normally, the main thread).
         virtual void postTaskToLoader(PassOwnPtr<ScriptExecutionContext::Task>) = 0;
 
-        // Posts callbacks from loading code to the WorkerContext. The 'mode' is used to differentiate
+        // Posts callbacks from loading code to the WorkerGlobalScope. The 'mode' is used to differentiate
         // specific synchronous loading requests so they can be 'nested', per spec.
         // Returns true if the task was posted successfully.
-        virtual bool postTaskForModeToWorkerContext(PassOwnPtr<ScriptExecutionContext::Task>, const String& mode) = 0;
+        virtual bool postTaskForModeToWorkerGlobalScope(PassOwnPtr<ScriptExecutionContext::Task>, const String& mode) = 0;
 
         // Spans divergent class hierarchies for dedicated and shared workers.
         virtual WebKit::WebWorkerBase* toWebWorkerBase() = 0;
diff --git a/Source/core/workers/WorkerLocation.idl b/Source/core/workers/WorkerLocation.idl
index 55eabda..1debf60 100644
--- a/Source/core/workers/WorkerLocation.idl
+++ b/Source/core/workers/WorkerLocation.idl
@@ -27,7 +27,7 @@
  */
 
 [
-    GlobalContext=WorkerOnly
+    GlobalContext=WorkerGlobalScope
 ] interface WorkerLocation {
     readonly attribute DOMString href;
     readonly attribute DOMString protocol;
diff --git a/Source/core/workers/WorkerMessagingProxy.cpp b/Source/core/workers/WorkerMessagingProxy.cpp
index fe17c5c..c31a70d 100644
--- a/Source/core/workers/WorkerMessagingProxy.cpp
+++ b/Source/core/workers/WorkerMessagingProxy.cpp
@@ -45,22 +45,22 @@
 #include "core/page/DOMWindow.h"
 #include "core/page/PageGroup.h"
 #include "core/platform/NotImplemented.h"
-#include "core/workers/DedicatedWorkerContext.h"
+#include "core/workers/DedicatedWorkerGlobalScope.h"
 #include "core/workers/DedicatedWorkerThread.h"
 #include "core/workers/Worker.h"
 #include <wtf/MainThread.h>
 
 namespace WebCore {
 
-class MessageWorkerContextTask : public ScriptExecutionContext::Task {
+class MessageWorkerGlobalScopeTask : public ScriptExecutionContext::Task {
 public:
-    static PassOwnPtr<MessageWorkerContextTask> create(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
+    static PassOwnPtr<MessageWorkerGlobalScopeTask> create(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
     {
-        return adoptPtr(new MessageWorkerContextTask(message, channels));
+        return adoptPtr(new MessageWorkerGlobalScopeTask(message, channels));
     }
 
 private:
-    MessageWorkerContextTask(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
+    MessageWorkerGlobalScopeTask(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
         : m_message(message)
         , m_channels(channels)
     {
@@ -68,8 +68,8 @@
 
     virtual void performTask(ScriptExecutionContext* scriptContext)
     {
-        ASSERT_WITH_SECURITY_IMPLICATION(scriptContext->isWorkerContext());
-        DedicatedWorkerContext* context = static_cast<DedicatedWorkerContext*>(scriptContext);
+        ASSERT_WITH_SECURITY_IMPLICATION(scriptContext->isWorkerGlobalScope());
+        DedicatedWorkerGlobalScope* context = static_cast<DedicatedWorkerGlobalScope*>(scriptContext);
         OwnPtr<MessagePortArray> ports = MessagePort::entanglePorts(*scriptContext, m_channels.release());
         context->dispatchEvent(MessageEvent::create(ports.release(), m_message));
         context->thread()->workerObjectProxy().confirmMessageFromWorkerObject(context->hasPendingActivity());
@@ -147,22 +147,22 @@
     WorkerMessagingProxy* m_messagingProxy;
 };
 
-class WorkerContextDestroyedTask : public ScriptExecutionContext::Task {
+class WorkerGlobalScopeDestroyedTask : public ScriptExecutionContext::Task {
 public:
-    static PassOwnPtr<WorkerContextDestroyedTask> create(WorkerMessagingProxy* messagingProxy)
+    static PassOwnPtr<WorkerGlobalScopeDestroyedTask> create(WorkerMessagingProxy* messagingProxy)
     {
-        return adoptPtr(new WorkerContextDestroyedTask(messagingProxy));
+        return adoptPtr(new WorkerGlobalScopeDestroyedTask(messagingProxy));
     }
 
 private:
-    WorkerContextDestroyedTask(WorkerMessagingProxy* messagingProxy)
+    WorkerGlobalScopeDestroyedTask(WorkerMessagingProxy* messagingProxy)
         : m_messagingProxy(messagingProxy)
     {
     }
 
     virtual void performTask(ScriptExecutionContext*)
     {
-        m_messagingProxy->workerContextDestroyedInternal();
+        m_messagingProxy->workerGlobalScopeDestroyedInternal();
     }
 
     WorkerMessagingProxy* m_messagingProxy;
@@ -183,7 +183,7 @@
 
     virtual void performTask(ScriptExecutionContext*)
     {
-        m_messagingProxy->terminateWorkerContext();
+        m_messagingProxy->terminateWorkerGlobalScope();
     }
 
     WorkerMessagingProxy* m_messagingProxy;
@@ -230,7 +230,7 @@
 
     virtual void performTask(ScriptExecutionContext*)
     {
-        if (WorkerContextProxy::PageInspector* pageInspector = m_messagingProxy->m_pageInspector)
+        if (WorkerGlobalScopeProxy::PageInspector* pageInspector = m_messagingProxy->m_pageInspector)
             pageInspector->dispatchMessageFromWorker(m_message);
     }
 
@@ -249,28 +249,25 @@
 {
     ASSERT(m_workerObject);
     ASSERT((m_scriptExecutionContext->isDocument() && isMainThread())
-           || (m_scriptExecutionContext->isWorkerContext() && static_cast<WorkerContext*>(m_scriptExecutionContext.get())->thread()->isCurrentThread()));
+        || (m_scriptExecutionContext->isWorkerGlobalScope() && toWorkerGlobalScope(m_scriptExecutionContext.get())->thread()->isCurrentThread()));
 }
 
 WorkerMessagingProxy::~WorkerMessagingProxy()
 {
     ASSERT(!m_workerObject);
     ASSERT((m_scriptExecutionContext->isDocument() && isMainThread())
-           || (m_scriptExecutionContext->isWorkerContext() && static_cast<WorkerContext*>(m_scriptExecutionContext.get())->thread()->isCurrentThread()));
+        || (m_scriptExecutionContext->isWorkerGlobalScope() && toWorkerGlobalScope(m_scriptExecutionContext.get())->thread()->isCurrentThread()));
 }
 
-void WorkerMessagingProxy::startWorkerContext(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode startMode)
+void WorkerMessagingProxy::startWorkerGlobalScope(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode startMode)
 {
     // FIXME: This need to be revisited when we support nested worker one day
     ASSERT(m_scriptExecutionContext->isDocument());
-    Document* document = static_cast<Document*>(m_scriptExecutionContext.get());
-    GroupSettings* settings = 0;
-    if (document->page())
-        settings = document->page()->group().groupSettings();
-    RefPtr<DedicatedWorkerThread> thread = DedicatedWorkerThread::create(scriptURL, userAgent, settings, sourceCode, *this, *this, startMode, document->contentSecurityPolicy()->deprecatedHeader(), document->contentSecurityPolicy()->deprecatedHeaderType(), document->topOrigin(), document->loader()->timing()->referenceMonotonicTime());
+    Document* document = toDocument(m_scriptExecutionContext.get());
+    RefPtr<DedicatedWorkerThread> thread = DedicatedWorkerThread::create(scriptURL, userAgent, sourceCode, *this, *this, startMode, document->contentSecurityPolicy()->deprecatedHeader(), document->contentSecurityPolicy()->deprecatedHeaderType(), document->topOrigin(), document->loader()->timing()->referenceMonotonicTime());
     workerThreadCreated(thread);
     thread->start();
-    InspectorInstrumentation::didStartWorkerContext(m_scriptExecutionContext.get(), this, scriptURL);
+    InspectorInstrumentation::didStartWorkerGlobalScope(m_scriptExecutionContext.get(), this, scriptURL);
 }
 
 void WorkerMessagingProxy::postMessageToWorkerObject(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
@@ -278,19 +275,19 @@
     m_scriptExecutionContext->postTask(MessageWorkerTask::create(message, channels, this));
 }
 
-void WorkerMessagingProxy::postMessageToWorkerContext(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
+void WorkerMessagingProxy::postMessageToWorkerGlobalScope(PassRefPtr<SerializedScriptValue> message, PassOwnPtr<MessagePortChannelArray> channels)
 {
     if (m_askedToTerminate)
         return;
 
     if (m_workerThread) {
         ++m_unconfirmedMessageCount;
-        m_workerThread->runLoop().postTask(MessageWorkerContextTask::create(message, channels));
+        m_workerThread->runLoop().postTask(MessageWorkerGlobalScopeTask::create(message, channels));
     } else
-        m_queuedEarlyTasks.append(MessageWorkerContextTask::create(message, channels));
+        m_queuedEarlyTasks.append(MessageWorkerGlobalScopeTask::create(message, channels));
 }
 
-bool WorkerMessagingProxy::postTaskForModeToWorkerContext(PassOwnPtr<ScriptExecutionContext::Task> task, const String& mode)
+bool WorkerMessagingProxy::postTaskForModeToWorkerGlobalScope(PassOwnPtr<ScriptExecutionContext::Task> task, const String& mode)
 {
     if (m_askedToTerminate)
         return false;
@@ -353,30 +350,28 @@
 {
     proxy->m_mayBeDestroyed = true;
     if (proxy->m_workerThread)
-        proxy->terminateWorkerContext();
+        proxy->terminateWorkerGlobalScope();
     else
-        proxy->workerContextDestroyedInternal();
+        proxy->workerGlobalScopeDestroyedInternal();
 }
 
-static void connectToWorkerContextInspectorTask(ScriptExecutionContext* context, bool)
+static void connectToWorkerGlobalScopeInspectorTask(ScriptExecutionContext* context, bool)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(context->isWorkerContext());
-    static_cast<WorkerContext*>(context)->workerInspectorController()->connectFrontend();
+    toWorkerGlobalScope(context)->workerInspectorController()->connectFrontend();
 }
 
-void WorkerMessagingProxy::connectToInspector(WorkerContextProxy::PageInspector* pageInspector)
+void WorkerMessagingProxy::connectToInspector(WorkerGlobalScopeProxy::PageInspector* pageInspector)
 {
     if (m_askedToTerminate)
         return;
     ASSERT(!m_pageInspector);
     m_pageInspector = pageInspector;
-    m_workerThread->runLoop().postTaskForMode(createCallbackTask(connectToWorkerContextInspectorTask, true), WorkerDebuggerAgent::debuggerTaskMode);
+    m_workerThread->runLoop().postTaskForMode(createCallbackTask(connectToWorkerGlobalScopeInspectorTask, true), WorkerDebuggerAgent::debuggerTaskMode);
 }
 
-static void disconnectFromWorkerContextInspectorTask(ScriptExecutionContext* context, bool)
+static void disconnectFromWorkerGlobalScopeInspectorTask(ScriptExecutionContext* context, bool)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(context->isWorkerContext());
-    static_cast<WorkerContext*>(context)->workerInspectorController()->disconnectFrontend();
+    toWorkerGlobalScope(context)->workerInspectorController()->disconnectFrontend();
 }
 
 void WorkerMessagingProxy::disconnectFromInspector()
@@ -384,13 +379,12 @@
     m_pageInspector = 0;
     if (m_askedToTerminate)
         return;
-    m_workerThread->runLoop().postTaskForMode(createCallbackTask(disconnectFromWorkerContextInspectorTask, true), WorkerDebuggerAgent::debuggerTaskMode);
+    m_workerThread->runLoop().postTaskForMode(createCallbackTask(disconnectFromWorkerGlobalScopeInspectorTask, true), WorkerDebuggerAgent::debuggerTaskMode);
 }
 
 static void dispatchOnInspectorBackendTask(ScriptExecutionContext* context, const String& message)
 {
-    ASSERT_WITH_SECURITY_IMPLICATION(context->isWorkerContext());
-    static_cast<WorkerContext*>(context)->workerInspectorController()->dispatchMessageFromFrontend(message);
+    toWorkerGlobalScope(context)->workerInspectorController()->dispatchMessageFromFrontend(message);
 }
 
 void WorkerMessagingProxy::sendMessageToInspector(const String& message)
@@ -401,32 +395,32 @@
     WorkerDebuggerAgent::interruptAndDispatchInspectorCommands(m_workerThread.get());
 }
 
-void WorkerMessagingProxy::workerContextDestroyed()
+void WorkerMessagingProxy::workerGlobalScopeDestroyed()
 {
-    m_scriptExecutionContext->postTask(WorkerContextDestroyedTask::create(this));
-    // Will execute workerContextDestroyedInternal() on context's thread.
+    m_scriptExecutionContext->postTask(WorkerGlobalScopeDestroyedTask::create(this));
+    // Will execute workerGlobalScopeDestroyedInternal() on context's thread.
 }
 
-void WorkerMessagingProxy::workerContextClosed()
+void WorkerMessagingProxy::workerGlobalScopeClosed()
 {
-    // Executes terminateWorkerContext() on parent context's thread.
+    // Executes terminateWorkerGlobalScope() on parent context's thread.
     m_scriptExecutionContext->postTask(WorkerTerminateTask::create(this));
 }
 
-void WorkerMessagingProxy::workerContextDestroyedInternal()
+void WorkerMessagingProxy::workerGlobalScopeDestroyedInternal()
 {
-    // WorkerContextDestroyedTask is always the last to be performed, so the proxy is not needed for communication
+    // WorkerGlobalScopeDestroyedTask is always the last to be performed, so the proxy is not needed for communication
     // in either side any more. However, the Worker object may still exist, and it assumes that the proxy exists, too.
     m_askedToTerminate = true;
     m_workerThread = 0;
 
-    InspectorInstrumentation::workerContextTerminated(m_scriptExecutionContext.get(), this);
+    InspectorInstrumentation::workerGlobalScopeTerminated(m_scriptExecutionContext.get(), this);
 
     if (m_mayBeDestroyed)
         delete this;
 }
 
-void WorkerMessagingProxy::terminateWorkerContext()
+void WorkerMessagingProxy::terminateWorkerGlobalScope()
 {
     if (m_askedToTerminate)
         return;
@@ -435,7 +429,7 @@
     if (m_workerThread)
         m_workerThread->stop();
 
-    InspectorInstrumentation::workerContextTerminated(m_scriptExecutionContext.get(), this);
+    InspectorInstrumentation::workerGlobalScopeTerminated(m_scriptExecutionContext.get(), this);
 }
 
 void WorkerMessagingProxy::postMessageToPageInspector(const String& message)
diff --git a/Source/core/workers/WorkerMessagingProxy.h b/Source/core/workers/WorkerMessagingProxy.h
index 57dfa4b..3a12604 100644
--- a/Source/core/workers/WorkerMessagingProxy.h
+++ b/Source/core/workers/WorkerMessagingProxy.h
@@ -28,7 +28,7 @@
 #define WorkerMessagingProxy_h
 
 #include "core/dom/ScriptExecutionContext.h"
-#include "core/workers/WorkerContextProxy.h"
+#include "core/workers/WorkerGlobalScopeProxy.h"
 #include "core/workers/WorkerLoaderProxy.h"
 #include "core/workers/WorkerObjectProxy.h"
 #include <wtf/Forward.h>
@@ -44,19 +44,19 @@
     class ScriptExecutionContext;
     class Worker;
 
-    class WorkerMessagingProxy : public WorkerContextProxy, public WorkerObjectProxy, public WorkerLoaderProxy {
+    class WorkerMessagingProxy : public WorkerGlobalScopeProxy, public WorkerObjectProxy, public WorkerLoaderProxy {
         WTF_MAKE_NONCOPYABLE(WorkerMessagingProxy); WTF_MAKE_FAST_ALLOCATED;
     public:
         explicit WorkerMessagingProxy(Worker*);
 
-        // Implementations of WorkerContextProxy.
+        // Implementations of WorkerGlobalScopeProxy.
         // (Only use these methods in the worker object thread.)
-        virtual void startWorkerContext(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode) OVERRIDE;
-        virtual void terminateWorkerContext() OVERRIDE;
-        virtual void postMessageToWorkerContext(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>) OVERRIDE;
+        virtual void startWorkerGlobalScope(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode) OVERRIDE;
+        virtual void terminateWorkerGlobalScope() OVERRIDE;
+        virtual void postMessageToWorkerGlobalScope(PassRefPtr<SerializedScriptValue>, PassOwnPtr<MessagePortChannelArray>) OVERRIDE;
         virtual bool hasPendingActivity() const OVERRIDE;
         virtual void workerObjectDestroyed() OVERRIDE;
-        virtual void connectToInspector(WorkerContextProxy::PageInspector*) OVERRIDE;
+        virtual void connectToInspector(WorkerGlobalScopeProxy::PageInspector*) OVERRIDE;
         virtual void disconnectFromInspector() OVERRIDE;
         virtual void sendMessageToInspector(const String&) OVERRIDE;
 
@@ -69,14 +69,14 @@
         virtual void updateInspectorStateCookie(const String&) OVERRIDE;
         virtual void confirmMessageFromWorkerObject(bool hasPendingActivity) OVERRIDE;
         virtual void reportPendingActivity(bool hasPendingActivity) OVERRIDE;
-        virtual void workerContextClosed() OVERRIDE;
-        virtual void workerContextDestroyed() OVERRIDE;
+        virtual void workerGlobalScopeClosed() OVERRIDE;
+        virtual void workerGlobalScopeDestroyed() OVERRIDE;
 
         // Implementation of WorkerLoaderProxy.
         // These methods are called on different threads to schedule loading
-        // requests and to send callbacks back to WorkerContext.
+        // requests and to send callbacks back to WorkerGlobalScope.
         virtual void postTaskToLoader(PassOwnPtr<ScriptExecutionContext::Task>) OVERRIDE;
-        virtual bool postTaskForModeToWorkerContext(PassOwnPtr<ScriptExecutionContext::Task>, const String& mode) OVERRIDE;
+        virtual bool postTaskForModeToWorkerGlobalScope(PassOwnPtr<ScriptExecutionContext::Task>, const String& mode) OVERRIDE;
 
         void workerThreadCreated(PassRefPtr<DedicatedWorkerThread>);
 
@@ -89,11 +89,11 @@
     private:
         friend class MessageWorkerTask;
         friend class PostMessageToPageInspectorTask;
-        friend class WorkerContextDestroyedTask;
+        friend class WorkerGlobalScopeDestroyedTask;
         friend class WorkerExceptionTask;
         friend class WorkerThreadActivityReportTask;
 
-        void workerContextDestroyedInternal();
+        void workerGlobalScopeDestroyedInternal();
         static void workerObjectDestroyedInternal(ScriptExecutionContext*, WorkerMessagingProxy*);
         void reportPendingActivityInternal(bool confirmingMessage, bool hasPendingActivity);
         Worker* workerObject() const { return m_workerObject; }
@@ -109,7 +109,7 @@
         bool m_askedToTerminate;
 
         Vector<OwnPtr<ScriptExecutionContext::Task> > m_queuedEarlyTasks; // Tasks are queued here until there's a thread object created.
-        WorkerContextProxy::PageInspector* m_pageInspector;
+        WorkerGlobalScopeProxy::PageInspector* m_pageInspector;
     };
 
 } // namespace WebCore
diff --git a/Source/core/workers/WorkerObjectProxy.h b/Source/core/workers/WorkerObjectProxy.h
index 7d7ae3e..d4da869 100644
--- a/Source/core/workers/WorkerObjectProxy.h
+++ b/Source/core/workers/WorkerObjectProxy.h
@@ -48,7 +48,7 @@
         virtual void reportPendingActivity(bool hasPendingActivity) = 0;
 
         // No need to notify the parent page context when dedicated workers are closing.
-        virtual void workerContextClosed() OVERRIDE { }
+        virtual void workerGlobalScopeClosed() OVERRIDE { }
     };
 
 } // namespace WebCore
diff --git a/Source/core/workers/WorkerReportingProxy.h b/Source/core/workers/WorkerReportingProxy.h
index 59edca0..7ecc015 100644
--- a/Source/core/workers/WorkerReportingProxy.h
+++ b/Source/core/workers/WorkerReportingProxy.h
@@ -47,10 +47,10 @@
         virtual void postMessageToPageInspector(const String&) = 0;
         virtual void updateInspectorStateCookie(const String&) = 0;
         // Invoked when close() is invoked on the worker context.
-        virtual void workerContextClosed() = 0;
+        virtual void workerGlobalScopeClosed() = 0;
 
         // Invoked when the thread has stopped.
-        virtual void workerContextDestroyed() = 0;
+        virtual void workerGlobalScopeDestroyed() = 0;
     };
 
 } // namespace WebCore
diff --git a/Source/core/workers/WorkerRunLoop.cpp b/Source/core/workers/WorkerRunLoop.cpp
index 9c6ffd4..365d191 100644
--- a/Source/core/workers/WorkerRunLoop.cpp
+++ b/Source/core/workers/WorkerRunLoop.cpp
@@ -34,7 +34,7 @@
 #include "core/platform/SharedTimer.h"
 #include "core/platform/ThreadGlobalData.h"
 #include "core/platform/ThreadTimers.h"
-#include "core/workers/WorkerContext.h"
+#include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerRunLoop.h"
 #include "core/workers/WorkerThread.h"
 #include <wtf/CurrentTime.h>
@@ -124,7 +124,7 @@
     WorkerRunLoop& m_runLoop;
 };
 
-void WorkerRunLoop::run(WorkerContext* context)
+void WorkerRunLoop::run(WorkerGlobalScope* context)
 {
     RunLoopSetup setup(*this);
     ModePredicate modePredicate(defaultMode());
@@ -135,7 +135,7 @@
     runCleanupTasks(context);
 }
 
-MessageQueueWaitResult WorkerRunLoop::runInMode(WorkerContext* context, const String& mode, WaitMode waitMode)
+MessageQueueWaitResult WorkerRunLoop::runInMode(WorkerGlobalScope* context, const String& mode, WaitMode waitMode)
 {
     RunLoopSetup setup(*this);
     ModePredicate modePredicate(mode);
@@ -143,7 +143,7 @@
     return result;
 }
 
-MessageQueueWaitResult WorkerRunLoop::runInMode(WorkerContext* context, const ModePredicate& predicate, WaitMode waitMode)
+MessageQueueWaitResult WorkerRunLoop::runInMode(WorkerGlobalScope* context, const ModePredicate& predicate, WaitMode waitMode)
 {
     ASSERT(context);
     ASSERT(context->thread());
@@ -174,7 +174,7 @@
     return result;
 }
 
-void WorkerRunLoop::runCleanupTasks(WorkerContext* context)
+void WorkerRunLoop::runCleanupTasks(WorkerGlobalScope* context)
 {
     ASSERT(context);
     ASSERT(context->thread());
@@ -216,8 +216,8 @@
 
 void WorkerRunLoop::Task::performTask(const WorkerRunLoop& runLoop, ScriptExecutionContext* context)
 {
-    WorkerContext* workerContext = static_cast<WorkerContext *>(context);
-    if ((!workerContext->isClosing() && !runLoop.terminated()) || m_task->isCleanupTask())
+    WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
+    if ((!workerGlobalScope->isClosing() && !runLoop.terminated()) || m_task->isCleanupTask())
         m_task->performTask(context);
 }
 
diff --git a/Source/core/workers/WorkerRunLoop.h b/Source/core/workers/WorkerRunLoop.h
index 8d61fb1..40e3e27 100644
--- a/Source/core/workers/WorkerRunLoop.h
+++ b/Source/core/workers/WorkerRunLoop.h
@@ -39,7 +39,7 @@
 namespace WebCore {
 
     class ModePredicate;
-    class WorkerContext;
+    class WorkerGlobalScope;
     class WorkerSharedTimer;
 
     class WorkerRunLoop {
@@ -48,12 +48,12 @@
         ~WorkerRunLoop();
         
         // Blocking call. Waits for tasks and timers, invokes the callbacks.
-        void run(WorkerContext*);
+        void run(WorkerGlobalScope*);
 
         enum WaitMode { WaitForMessage, DontWaitForMessage };
 
         // Waits for a single task and returns.
-        MessageQueueWaitResult runInMode(WorkerContext*, const String& mode, WaitMode = WaitForMessage);
+        MessageQueueWaitResult runInMode(WorkerGlobalScope*, const String& mode, WaitMode = WaitForMessage);
 
         void terminate();
         bool terminated() const { return m_messageQueue.killed(); }
@@ -83,11 +83,11 @@
 
     private:
         friend class RunLoopSetup;
-        MessageQueueWaitResult runInMode(WorkerContext*, const ModePredicate&, WaitMode);
+        MessageQueueWaitResult runInMode(WorkerGlobalScope*, const ModePredicate&, WaitMode);
 
         // Runs any clean up tasks that are currently in the queue and returns.
         // This should only be called when the context is closed or loop has been terminated.
-        void runCleanupTasks(WorkerContext*);
+        void runCleanupTasks(WorkerGlobalScope*);
 
         MessageQueue<Task> m_messageQueue;
         OwnPtr<WorkerSharedTimer> m_sharedTimer;
diff --git a/Source/core/workers/WorkerScriptLoader.cpp b/Source/core/workers/WorkerScriptLoader.cpp
index d0530d3..ff40c3d 100644
--- a/Source/core/workers/WorkerScriptLoader.cpp
+++ b/Source/core/workers/WorkerScriptLoader.cpp
@@ -33,7 +33,7 @@
 #include "core/loader/TextResourceDecoder.h"
 #include "core/loader/WorkerThreadableLoader.h"
 #include "core/platform/network/ResourceResponse.h"
-#include "core/workers/WorkerContext.h"
+#include "core/workers/WorkerGlobalScope.h"
 #include "core/workers/WorkerScriptLoaderClient.h"
 
 #include <wtf/OwnPtr.h>
@@ -63,7 +63,7 @@
     if (!request)
         return;
 
-    ASSERT_WITH_SECURITY_IMPLICATION(scriptExecutionContext->isWorkerContext());
+    ASSERT_WITH_SECURITY_IMPLICATION(scriptExecutionContext->isWorkerGlobalScope());
 
     ThreadableLoaderOptions options;
     options.allowCredentials = AllowStoredCredentials;
@@ -72,7 +72,7 @@
     // FIXME: Should we add EnforceScriptSrcDirective here?
     options.contentSecurityPolicyEnforcement = DoNotEnforceContentSecurityPolicy;
 
-    WorkerThreadableLoader::loadResourceSynchronously(static_cast<WorkerContext*>(scriptExecutionContext), *request, *this, options);
+    WorkerThreadableLoader::loadResourceSynchronously(toWorkerGlobalScope(scriptExecutionContext), *request, *this, options);
 }
     
 void WorkerScriptLoader::loadAsynchronously(ScriptExecutionContext* scriptExecutionContext, const KURL& url, CrossOriginRequestPolicy crossOriginRequestPolicy, WorkerScriptLoaderClient* client)
diff --git a/Source/core/workers/WorkerThread.cpp b/Source/core/workers/WorkerThread.cpp
index 2a92e3b..d6d185b 100644
--- a/Source/core/workers/WorkerThread.cpp
+++ b/Source/core/workers/WorkerThread.cpp
@@ -32,7 +32,7 @@
 #include "bindings/v8/ScriptValue.h"
 #include "core/inspector/InspectorInstrumentation.h"
 #include "core/platform/ThreadGlobalData.h"
-#include "core/workers/DedicatedWorkerContext.h"
+#include "core/workers/DedicatedWorkerGlobalScope.h"
 #include "modules/webdatabase/DatabaseManager.h"
 #include "modules/webdatabase/DatabaseTask.h"
 #include "public/platform/Platform.h"
@@ -66,24 +66,23 @@
 struct WorkerThreadStartupData {
     WTF_MAKE_NONCOPYABLE(WorkerThreadStartupData); WTF_MAKE_FAST_ALLOCATED;
 public:
-    static PassOwnPtr<WorkerThreadStartupData> create(const KURL& scriptURL, const String& userAgent, const GroupSettings* settings, const String& sourceCode, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, const SecurityOrigin* topOrigin)
+    static PassOwnPtr<WorkerThreadStartupData> create(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, const SecurityOrigin* topOrigin)
     {
-        return adoptPtr(new WorkerThreadStartupData(scriptURL, userAgent, settings, sourceCode, startMode, contentSecurityPolicy, contentSecurityPolicyType, topOrigin));
+        return adoptPtr(new WorkerThreadStartupData(scriptURL, userAgent, sourceCode, startMode, contentSecurityPolicy, contentSecurityPolicyType, topOrigin));
     }
 
     KURL m_scriptURL;
     String m_userAgent;
-    OwnPtr<GroupSettings> m_groupSettings;
     String m_sourceCode;
     WorkerThreadStartMode m_startMode;
     String m_contentSecurityPolicy;
     ContentSecurityPolicy::HeaderType m_contentSecurityPolicyType;
     RefPtr<SecurityOrigin> m_topOrigin;
 private:
-    WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const GroupSettings*, const String& sourceCode, WorkerThreadStartMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, const SecurityOrigin* topOrigin);
+    WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, const SecurityOrigin* topOrigin);
 };
 
-WorkerThreadStartupData::WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const GroupSettings* settings, const String& sourceCode, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, const SecurityOrigin* topOrigin)
+WorkerThreadStartupData::WorkerThreadStartupData(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, const SecurityOrigin* topOrigin)
     : m_scriptURL(scriptURL.copy())
     , m_userAgent(userAgent.isolatedCopy())
     , m_sourceCode(sourceCode.isolatedCopy())
@@ -92,20 +91,13 @@
     , m_contentSecurityPolicyType(contentSecurityPolicyType)
     , m_topOrigin(topOrigin ? topOrigin->isolatedCopy() : 0)
 {
-    if (!settings)
-        return;
-
-    m_groupSettings = GroupSettings::create();
-    m_groupSettings->setLocalStorageQuotaBytes(settings->localStorageQuotaBytes());
-    m_groupSettings->setIndexedDBQuotaBytes(settings->indexedDBQuotaBytes());
-    m_groupSettings->setIndexedDBDatabasePath(settings->indexedDBDatabasePath().isolatedCopy());
 }
 
-WorkerThread::WorkerThread(const KURL& scriptURL, const String& userAgent, const GroupSettings* settings, const String& sourceCode, WorkerLoaderProxy& workerLoaderProxy, WorkerReportingProxy& workerReportingProxy, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, const SecurityOrigin* topOrigin)
+WorkerThread::WorkerThread(const KURL& scriptURL, const String& userAgent, const String& sourceCode, WorkerLoaderProxy& workerLoaderProxy, WorkerReportingProxy& workerReportingProxy, WorkerThreadStartMode startMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType contentSecurityPolicyType, const SecurityOrigin* topOrigin)
     : m_threadID(0)
     , m_workerLoaderProxy(workerLoaderProxy)
     , m_workerReportingProxy(workerReportingProxy)
-    , m_startupData(WorkerThreadStartupData::create(scriptURL, userAgent, settings, sourceCode, startMode, contentSecurityPolicy, contentSecurityPolicyType, topOrigin))
+    , m_startupData(WorkerThreadStartupData::create(scriptURL, userAgent, sourceCode, startMode, contentSecurityPolicy, contentSecurityPolicyType, topOrigin))
 #if ENABLE(NOTIFICATIONS) || ENABLE(LEGACY_NOTIFICATIONS)
     , m_notificationClient(0)
 #endif
@@ -143,20 +135,20 @@
 {
     {
         MutexLocker lock(m_threadCreationMutex);
-        m_workerContext = createWorkerContext(m_startupData->m_scriptURL, m_startupData->m_userAgent, m_startupData->m_groupSettings.release(), m_startupData->m_contentSecurityPolicy, m_startupData->m_contentSecurityPolicyType, m_startupData->m_topOrigin.release());
+        m_workerGlobalScope = createWorkerGlobalScope(m_startupData->m_scriptURL, m_startupData->m_userAgent, m_startupData->m_contentSecurityPolicy, m_startupData->m_contentSecurityPolicyType, m_startupData->m_topOrigin.release());
 
         if (m_runLoop.terminated()) {
             // The worker was terminated before the thread had a chance to run. Since the context didn't exist yet,
             // forbidExecution() couldn't be called from stop().
-           m_workerContext->script()->forbidExecution();
+            m_workerGlobalScope->script()->forbidExecution();
         }
     }
     // The corresponding call to didStopWorkerRunLoop is in
     // ~WorkerScriptController.
     WebKit::Platform::current()->didStartWorkerRunLoop(WebKit::WebWorkerRunLoop(&m_runLoop));
 
-    WorkerScriptController* script = m_workerContext->script();
-    InspectorInstrumentation::willEvaluateWorkerScript(workerContext(), m_startupData->m_startMode);
+    WorkerScriptController* script = m_workerGlobalScope->script();
+    InspectorInstrumentation::willEvaluateWorkerScript(workerGlobalScope(), m_startupData->m_startMode);
     script->evaluate(ScriptSourceCode(m_startupData->m_sourceCode, m_startupData->m_scriptURL));
     // Free the startup data to cause its member variable deref's happen on the worker's thread (since
     // all ref/derefs of these objects are happening on the thread at this point). Note that
@@ -167,11 +159,11 @@
 
     ThreadIdentifier threadID = m_threadID;
 
-    ASSERT(m_workerContext->hasOneRef());
+    ASSERT(m_workerGlobalScope->hasOneRef());
 
     // The below assignment will destroy the context, which will in turn notify messaging proxy.
     // We cannot let any objects survive past thread exit, because no other thread will run GC or otherwise destroy them.
-    m_workerContext = 0;
+    m_workerGlobalScope = 0;
 
     // Clean up WebCore::ThreadGlobalData before WTF::WTFThreadData goes away!
     threadGlobalData().destroy();
@@ -183,7 +175,7 @@
 void WorkerThread::runEventLoop()
 {
     // Does not return until terminated.
-    m_runLoop.run(m_workerContext.get());
+    m_runLoop.run(m_workerGlobalScope.get());
 }
 
 class WorkerThreadShutdownFinishTask : public ScriptExecutionContext::Task {
@@ -195,11 +187,10 @@
 
     virtual void performTask(ScriptExecutionContext *context)
     {
-        ASSERT_WITH_SECURITY_IMPLICATION(context->isWorkerContext());
-        WorkerContext* workerContext = static_cast<WorkerContext*>(context);
-        workerContext->clearInspector();
+        WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
+        workerGlobalScope->clearInspector();
         // It's not safe to call clearScript until all the cleanup tasks posted by functions initiated by WorkerThreadShutdownStartTask have completed.
-        workerContext->clearScript();
+        workerGlobalScope->clearScript();
     }
 
     virtual bool isCleanupTask() const { return true; }
@@ -214,20 +205,19 @@
 
     virtual void performTask(ScriptExecutionContext *context)
     {
-        ASSERT_WITH_SECURITY_IMPLICATION(context->isWorkerContext());
-        WorkerContext* workerContext = static_cast<WorkerContext*>(context);
+        WorkerGlobalScope* workerGlobalScope = toWorkerGlobalScope(context);
 
         // FIXME: Should we stop the databases as part of stopActiveDOMObjects() below?
         DatabaseTaskSynchronizer cleanupSync;
-        DatabaseManager::manager().stopDatabases(workerContext, &cleanupSync);
+        DatabaseManager::manager().stopDatabases(workerGlobalScope, &cleanupSync);
 
-        workerContext->stopActiveDOMObjects();
+        workerGlobalScope->stopActiveDOMObjects();
 
-        workerContext->notifyObserversOfStop();
+        workerGlobalScope->notifyObserversOfStop();
 
         // Event listeners would keep DOMWrapperWorld objects alive for too long. Also, they have references to JS objects,
         // which become dangling once Heap is destroyed.
-        workerContext->removeAllEventListeners();
+        workerGlobalScope->removeAllEventListeners();
 
         // We wait for the database thread to clean up all its stuff so that we
         // can do more stringent leak checks as we exit.
@@ -235,7 +225,7 @@
 
         // Stick a shutdown command at the end of the queue, so that we deal
         // with all the cleanup tasks the databases post first.
-        workerContext->postTask(WorkerThreadShutdownFinishTask::create());
+        workerGlobalScope->postTask(WorkerThreadShutdownFinishTask::create());
     }
 
     virtual bool isCleanupTask() const { return true; }
@@ -247,10 +237,10 @@
     MutexLocker lock(m_threadCreationMutex);
 
     // Ensure that tasks are being handled by thread event loop. If script execution weren't forbidden, a while(1) loop in JS could keep the thread alive forever.
-    if (m_workerContext) {
-        m_workerContext->script()->scheduleExecutionTermination();
+    if (m_workerGlobalScope) {
+        m_workerGlobalScope->script()->scheduleExecutionTermination();
 
-        DatabaseManager::manager().interruptAllDatabasesForContext(m_workerContext.get());
+        DatabaseManager::manager().interruptAllDatabasesForContext(m_workerGlobalScope.get());
         m_runLoop.postTaskAndTerminate(WorkerThreadShutdownStartTask::create());
         return;
     }
diff --git a/Source/core/workers/WorkerThread.h b/Source/core/workers/WorkerThread.h
index 1e14bc1..92bd58a 100644
--- a/Source/core/workers/WorkerThread.h
+++ b/Source/core/workers/WorkerThread.h
@@ -28,7 +28,6 @@
 #define WorkerThread_h
 
 #include "core/page/ContentSecurityPolicy.h"
-#include "core/page/GroupSettings.h"
 #include "core/workers/WorkerRunLoop.h"
 #include "weborigin/SecurityOrigin.h"
 #include "wtf/Forward.h"
@@ -40,12 +39,12 @@
 
     class KURL;
     class NotificationClient;
-    class WorkerContext;
+    class WorkerGlobalScope;
     class WorkerLoaderProxy;
     class WorkerReportingProxy;
     struct WorkerThreadStartupData;
 
-    enum WorkerThreadStartMode { DontPauseWorkerContextOnStart, PauseWorkerContextOnStart };
+    enum WorkerThreadStartMode { DontPauseWorkerGlobalScopeOnStart, PauseWorkerGlobalScopeOnStart };
 
     class WorkerThread : public RefCounted<WorkerThread> {
     public:
@@ -69,15 +68,15 @@
 #endif
 
     protected:
-        WorkerThread(const KURL&, const String& userAgent, const GroupSettings*,  const String& sourceCode, WorkerLoaderProxy&, WorkerReportingProxy&, WorkerThreadStartMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType, const SecurityOrigin* topOrigin);
+        WorkerThread(const KURL&, const String& userAgent, const String& sourceCode, WorkerLoaderProxy&, WorkerReportingProxy&, WorkerThreadStartMode, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType, const SecurityOrigin* topOrigin);
 
         // Factory method for creating a new worker context for the thread.
-        virtual PassRefPtr<WorkerContext> createWorkerContext(const KURL&, const String& userAgent, PassOwnPtr<GroupSettings>, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType, PassRefPtr<SecurityOrigin> topOrigin) = 0;
+        virtual PassRefPtr<WorkerGlobalScope> createWorkerGlobalScope(const KURL&, const String& userAgent, const String& contentSecurityPolicy, ContentSecurityPolicy::HeaderType, PassRefPtr<SecurityOrigin> topOrigin) = 0;
 
         // Executes the event loop for the worker thread. Derived classes can override to perform actions before/after entering the event loop.
         virtual void runEventLoop();
 
-        WorkerContext* workerContext() { return m_workerContext.get(); }
+        WorkerGlobalScope* workerGlobalScope() { return m_workerGlobalScope.get(); }
 
     private:
         // Static function executed as the core routine on the new thread. Passed a pointer to a WorkerThread object.
@@ -90,7 +89,7 @@
         WorkerLoaderProxy& m_workerLoaderProxy;
         WorkerReportingProxy& m_workerReportingProxy;
 
-        RefPtr<WorkerContext> m_workerContext;
+        RefPtr<WorkerGlobalScope> m_workerGlobalScope;
         Mutex m_threadCreationMutex;
 
         OwnPtr<WorkerThreadStartupData> m_startupData;
diff --git a/Source/core/xml/XMLHttpRequest.cpp b/Source/core/xml/XMLHttpRequest.cpp
index e95e0d9..29d1bbc 100644
--- a/Source/core/xml/XMLHttpRequest.cpp
+++ b/Source/core/xml/XMLHttpRequest.cpp
@@ -218,6 +218,8 @@
         ec = INVALID_STATE_ERR;
         return ScriptString();
     }
+    if (m_error || (m_state != LOADING && m_state != DONE))
+        return ScriptString();
     return m_responseText;
 }
 
@@ -238,7 +240,7 @@
         // If it is text/html, then the responseType of "document" must have been supplied explicitly.
         if ((m_response.isHTTP() && !responseIsXML() && !isHTML)
             || (isHTML && m_responseTypeCode == ResponseTypeDefault)
-            || scriptExecutionContext()->isWorkerContext()) {
+            || scriptExecutionContext()->isWorkerGlobalScope()) {
             m_responseDocument = 0;
         } else {
             if (isHTML)
@@ -265,7 +267,7 @@
         return 0;
     }
     // We always return null before DONE.
-    if (m_state != DONE)
+    if (m_error || m_state != DONE)
         return 0;
 
     if (!m_responseBlob) {
@@ -300,7 +302,7 @@
         return 0;
     }
 
-    if (m_state != DONE)
+    if (m_error || m_state != DONE)
         return 0;
 
     if (!m_responseArrayBuffer.get() && m_binaryResponseBuilder.get() && m_binaryResponseBuilder->size() > 0) {
@@ -330,7 +332,7 @@
         return;
     }
 
-    // Newer functionality is not available to synchronous requests in window contexts, as a spec-mandated 
+    // Newer functionality is not available to synchronous requests in window contexts, as a spec-mandated
     // attempt to discourage synchronous XHR use. responseType is one such piece of functionality.
     // We'll only disable this functionality for HTTP(S) requests since sync requests for local protocols
     // such as file: and data: still make sense to allow.
@@ -571,9 +573,12 @@
         // from the HTML5 specification to serialize the document.
         String body = createMarkup(document);
 
-        // FIXME: this should use value of document.inputEncoding to determine the encoding to use.
+        // FIXME: This should use value of document.inputEncoding to determine the encoding to use.
         WTF::TextEncoding encoding = UTF8Encoding();
-        m_requestEntityBody = FormData::create(encoding.encode(body.characters(), body.length(), WTF::EntitiesForUnencodables));
+        if (body.is8Bit())
+            m_requestEntityBody = FormData::create(body.characters8(), body.length());
+        else
+            m_requestEntityBody = FormData::create(encoding.encode(body, WTF::EntitiesForUnencodables));
         if (m_upload)
             m_requestEntityBody->setAlwaysStream(true);
     }
@@ -595,7 +600,10 @@
             m_requestHeaders.set("Content-Type", contentType);
         }
 
-        m_requestEntityBody = FormData::create(UTF8Encoding().encode(body.characters(), body.length(), WTF::EntitiesForUnencodables));
+        if (body.is8Bit())
+            m_requestEntityBody = FormData::create(body.characters8(), body.length());
+        else
+            m_requestEntityBody = FormData::create(UTF8Encoding().encode(body, WTF::EntitiesForUnencodables));
         if (m_upload)
             m_requestEntityBody->setAlwaysStream(true);
     }
@@ -680,12 +688,6 @@
     createRequest(ec);
 }
 
-void XMLHttpRequest::sendForInspector(ExceptionCode& ec)
-{
-    m_allowCrossOriginRequests = true;
-    send(ec);
-}
-
 void XMLHttpRequest::sendForInspectorXHRReplay(PassRefPtr<FormData> formData, ExceptionCode& ec)
 {
     m_requestEntityBody = formData ? formData->deepCopy() : 0;
@@ -980,7 +982,7 @@
         logConsoleError(scriptExecutionContext(), "Refused to get unsafe header \"" + name + "\"");
         return String();
     }
-    
+
     HTTPHeaderSet accessControlExposeHeaderSet;
     parseAccessControlExposeHeadersAllowList(m_response.httpHeaderField("Access-Control-Expose-Headers"), accessControlExposeHeaderSet);
 
diff --git a/Source/core/xml/XMLHttpRequest.h b/Source/core/xml/XMLHttpRequest.h
index 69b0f07..91011d3 100644
--- a/Source/core/xml/XMLHttpRequest.h
+++ b/Source/core/xml/XMLHttpRequest.h
@@ -111,7 +111,6 @@
     unsigned long timeout() const { return m_timeoutMilliseconds; }
     void setTimeout(unsigned long timeout, ExceptionCode&);
 
-    void sendForInspector(ExceptionCode&);
     void sendForInspectorXHRReplay(PassRefPtr<FormData>, ExceptionCode&);
 
     // Expose HTTP validation methods for other untrusted requests.
diff --git a/Source/core/xml/XMLHttpRequest.idl b/Source/core/xml/XMLHttpRequest.idl
index 8811709..fbe7217 100644
--- a/Source/core/xml/XMLHttpRequest.idl
+++ b/Source/core/xml/XMLHttpRequest.idl
@@ -37,7 +37,7 @@
 };
 
 [
-    GlobalContext=WindowAndWorker,
+    GlobalContext=Window&WorkerGlobalScope,
     ActiveDOMObject,
     Constructor,
     ConstructorCallWith=ScriptExecutionContext,
diff --git a/Source/core/xml/XPathException.cpp b/Source/core/xml/XPathException.cpp
deleted file mode 100644
index bc92848..0000000
--- a/Source/core/xml/XPathException.cpp
+++ /dev/null
@@ -1,60 +0,0 @@
-/*
- * Copyright (C) 2011 Google Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY GOOGLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#include "config.h"
-#include "core/xml/XPathException.h"
-
-namespace WebCore {
-
-static struct XPathExceptionNameDescription {
-    const char* const name;
-    const char* const description;
-} xPathExceptions[] = {
-    { "INVALID_EXPRESSION_ERR", "The expression had a syntax error or otherwise is not a legal expression according to the rules of the specific XPathEvaluator." },
-    { "TYPE_ERR", "The expression could not be converted to return the specified type." }
-};
-
-bool XPathException::initializeDescription(ExceptionCode ec, ExceptionCodeDescription* description)
-{
-    if (ec < XPathExceptionOffset || ec > XPathExceptionMax)
-        return false;
-
-    description->typeName = "DOM XPath";
-    description->code = ec - XPathExceptionOffset;
-    description->type = XPathExceptionType;
-
-    size_t tableSize = WTF_ARRAY_LENGTH(xPathExceptions);
-    size_t tableIndex = ec - INVALID_EXPRESSION_ERR;
-
-    description->name = tableIndex < tableSize ? xPathExceptions[tableIndex].name : 0;
-    description->description = tableIndex < tableSize ? xPathExceptions[tableIndex].description : 0;
-
-    return true;
-}
-
-} // namespace WebCore
diff --git a/Source/core/xml/XPathException.h b/Source/core/xml/XPathException.h
deleted file mode 100644
index 134086e..0000000
--- a/Source/core/xml/XPathException.h
+++ /dev/null
@@ -1,64 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-#ifndef XPathException_h
-#define XPathException_h
-
-#include "bindings/v8/ScriptWrappable.h"
-#include "core/dom/ExceptionBase.h"
-
-namespace WebCore {
-
-class XPathException : public ExceptionBase, public ScriptWrappable {
-public:
-    static PassRefPtr<XPathException> create(const ExceptionCodeDescription& description)
-    {
-        return adoptRef(new XPathException(description));
-    }
-
-    static const int XPathExceptionOffset = 400;
-    static const int XPathExceptionMax = 499;
-
-    enum XPathExceptionCode {
-        INVALID_EXPRESSION_ERR = XPathExceptionOffset + 51,
-        TYPE_ERR
-    };
-
-    static bool initializeDescription(ExceptionCode, ExceptionCodeDescription*);
-
-private:
-    explicit XPathException(const ExceptionCodeDescription& description)
-        : ExceptionBase(description)
-    {
-        ScriptWrappable::init(this);
-    }
-};
-
-} // namespace WebCore
-
-#endif // XPathException_h
diff --git a/Source/core/xml/XPathException.idl b/Source/core/xml/XPathException.idl
deleted file mode 100644
index 2f4ef9f..0000000
--- a/Source/core/xml/XPathException.idl
+++ /dev/null
@@ -1,44 +0,0 @@
-/*
- * Copyright (C) 2007 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer.
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution.
- * 3.  Neither the name of Apple Computer, Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-[
-    DoNotCheckConstants
-] exception XPathException {
-
-    readonly attribute unsigned short   code;
-    readonly attribute DOMString        name;
-    readonly attribute DOMString        message;
-
-    // Override in a Mozilla compatible format
-    [NotEnumerable] DOMString toString();
-
-    // XPathExceptionCode
-    const unsigned short INVALID_EXPRESSION_ERR = 51;
-    const unsigned short TYPE_ERR = 52;
-};
-
diff --git a/Source/core/xml/XPathExpression.cpp b/Source/core/xml/XPathExpression.cpp
index 164f640..3a96c3e 100644
--- a/Source/core/xml/XPathExpression.cpp
+++ b/Source/core/xml/XPathExpression.cpp
@@ -28,7 +28,6 @@
 #include "core/xml/XPathExpression.h"
 
 #include "core/dom/ExceptionCode.h"
-#include "core/xml/XPathException.h"
 #include "core/xml/XPathExpressionNode.h"
 #include "core/xml/XPathNSResolver.h"
 #include "core/xml/XPathParser.h"
@@ -73,9 +72,8 @@
     evaluationContext.node = 0; // Do not hold a reference to the context node, as this may prevent the whole document from being destroyed in time.
 
     if (evaluationContext.hadTypeConversionError) {
-        // It is not specified what to do if type conversion fails while evaluating an expression, and INVALID_EXPRESSION_ERR is not exactly right
-        // when the failure happens in an otherwise valid expression because of a variable. But XPathEvaluator does not support variables, so it's close enough.
-        ec = XPathException::INVALID_EXPRESSION_ERR;
+        // It is not specified what to do if type conversion fails while evaluating an expression.
+        ec = SYNTAX_ERR;
         return 0;
     }
 
diff --git a/Source/core/xml/XPathNodeSet.cpp b/Source/core/xml/XPathNodeSet.cpp
index bfe26d2..7ead9c9 100644
--- a/Source/core/xml/XPathNodeSet.cpp
+++ b/Source/core/xml/XPathNodeSet.cpp
@@ -96,7 +96,7 @@
         // FIXME: namespace nodes are not implemented.
         for (unsigned i = sortedEnd; i < to; ++i) {
             Node* n = parentMatrix[i][0];
-            if (n->isAttributeNode() && static_cast<Attr*>(n)->ownerElement() == commonAncestor)
+            if (n->isAttributeNode() && toAttr(n)->ownerElement() == commonAncestor)
                 parentMatrix[i].swap(parentMatrix[sortedEnd++]);
         }
         if (sortedEnd != from) {
@@ -159,7 +159,7 @@
         Node* n = m_nodes[i].get();
         parentsVector.append(n);
         if (n->isAttributeNode()) {
-            n = static_cast<Attr*>(n)->ownerElement();
+            n = toAttr(n)->ownerElement();
             parentsVector.append(n);
             containsAttributeNodes = true;
         }
@@ -180,7 +180,7 @@
 static Node* findRootNode(Node* node)
 {
     if (node->isAttributeNode())
-        node = static_cast<Attr*>(node)->ownerElement();
+        node = toAttr(node)->ownerElement();
     if (node->inDocument())
         node = node->document();
     else {
diff --git a/Source/core/xml/XPathParser.cpp b/Source/core/xml/XPathParser.cpp
index 5daab74..4ef59b6 100644
--- a/Source/core/xml/XPathParser.cpp
+++ b/Source/core/xml/XPathParser.cpp
@@ -30,7 +30,6 @@
 
 #include "core/dom/ExceptionCode.h"
 #include "core/xml/XPathEvaluator.h"
-#include "core/xml/XPathException.h"
 #include "core/xml/XPathNSResolver.h"
 #include "core/xml/XPathPath.h"
 #include "core/xml/XPathStep.h"
@@ -504,7 +503,7 @@
         if (m_gotNamespaceError)
             ec = NAMESPACE_ERR;
         else
-            ec = XPathException::INVALID_EXPRESSION_ERR;
+            ec = SYNTAX_ERR;
         return 0;
     }
 
diff --git a/Source/core/xml/XPathResult.cpp b/Source/core/xml/XPathResult.cpp
index 6c5e4fd..3f386df 100644
--- a/Source/core/xml/XPathResult.cpp
+++ b/Source/core/xml/XPathResult.cpp
@@ -30,7 +30,6 @@
 #include "core/dom/Document.h"
 #include "core/dom/ExceptionCode.h"
 #include "core/xml/XPathEvaluator.h"
-#include "core/xml/XPathException.h"
 
 namespace WebCore {
 
@@ -89,14 +88,14 @@
         case ANY_UNORDERED_NODE_TYPE:
         case FIRST_ORDERED_NODE_TYPE: // This is correct - singleNodeValue() will take care of ordering.
             if (!m_value.isNodeSet()) {
-                ec = XPathException::TYPE_ERR;
+                ec = TypeError;
                 return;
             }
             m_resultType = type;
             break;
         case ORDERED_NODE_ITERATOR_TYPE:
             if (!m_value.isNodeSet()) {
-                ec = XPathException::TYPE_ERR;
+                ec = TypeError;
                 return;
             }
             m_nodeSet.sort();
@@ -104,7 +103,7 @@
             break;
         case ORDERED_NODE_SNAPSHOT_TYPE:
             if (!m_value.isNodeSet()) {
-                ec = XPathException::TYPE_ERR;
+                ec = TypeError;
                 return;
             }
             m_value.toNodeSet().sort();
@@ -121,7 +120,7 @@
 double XPathResult::numberValue(ExceptionCode& ec) const
 {
     if (resultType() != NUMBER_TYPE) {
-        ec = XPathException::TYPE_ERR;
+        ec = TypeError;
         return 0.0;
     }
     return m_value.toNumber();
@@ -130,7 +129,7 @@
 String XPathResult::stringValue(ExceptionCode& ec) const
 {
     if (resultType() != STRING_TYPE) {
-        ec = XPathException::TYPE_ERR;
+        ec = TypeError;
         return String();
     }
     return m_value.toString();
@@ -139,7 +138,7 @@
 bool XPathResult::booleanValue(ExceptionCode& ec) const
 {
     if (resultType() != BOOLEAN_TYPE) {
-        ec = XPathException::TYPE_ERR;
+        ec = TypeError;
         return false;
     }
     return m_value.toBoolean();
@@ -148,7 +147,7 @@
 Node* XPathResult::singleNodeValue(ExceptionCode& ec) const
 {
     if (resultType() != ANY_UNORDERED_NODE_TYPE && resultType() != FIRST_ORDERED_NODE_TYPE) {
-        ec = XPathException::TYPE_ERR;
+        ec = TypeError;
         return 0;
     }
   
@@ -171,7 +170,7 @@
 unsigned long XPathResult::snapshotLength(ExceptionCode& ec) const
 {
     if (resultType() != UNORDERED_NODE_SNAPSHOT_TYPE && resultType() != ORDERED_NODE_SNAPSHOT_TYPE) {
-        ec = XPathException::TYPE_ERR;
+        ec = TypeError;
         return 0;
     }
 
@@ -181,7 +180,7 @@
 Node* XPathResult::iterateNext(ExceptionCode& ec)
 {
     if (resultType() != UNORDERED_NODE_ITERATOR_TYPE && resultType() != ORDERED_NODE_ITERATOR_TYPE) {
-        ec = XPathException::TYPE_ERR;
+        ec = TypeError;
         return 0;
     }
     
@@ -203,7 +202,7 @@
 Node* XPathResult::snapshotItem(unsigned long index, ExceptionCode& ec)
 {
     if (resultType() != UNORDERED_NODE_SNAPSHOT_TYPE && resultType() != ORDERED_NODE_SNAPSHOT_TYPE) {
-        ec = XPathException::TYPE_ERR;
+        ec = TypeError;
         return 0;
     }
     
diff --git a/Source/core/xml/XPathStep.cpp b/Source/core/xml/XPathStep.cpp
index 56cf1a2..cd6642b 100644
--- a/Source/core/xml/XPathStep.cpp
+++ b/Source/core/xml/XPathStep.cpp
@@ -253,7 +253,7 @@
             return;
         case ParentAxis:
             if (context->isAttributeNode()) {
-                Element* n = static_cast<Attr*>(context)->ownerElement();
+                Element* n = toAttr(context)->ownerElement();
                 if (nodeMatches(n, ParentAxis, m_nodeTest))
                     nodes.append(n);
             } else {
@@ -265,7 +265,7 @@
         case AncestorAxis: {
             Node* n = context;
             if (context->isAttributeNode()) {
-                n = static_cast<Attr*>(context)->ownerElement();
+                n = toAttr(context)->ownerElement();
                 if (nodeMatches(n, AncestorAxis, m_nodeTest))
                     nodes.append(n);
             }
@@ -297,10 +297,11 @@
             return;
         case FollowingAxis:
             if (context->isAttributeNode()) {
-                Node* p = static_cast<Attr*>(context)->ownerElement();
-                while ((p = NodeTraversal::next(p)))
+                Node* p = toAttr(context)->ownerElement();
+                while ((p = NodeTraversal::next(p))) {
                     if (nodeMatches(p, FollowingAxis, m_nodeTest))
                         nodes.append(p);
+                }
             } else {
                 for (Node* p = context; !isRootDomNode(p); p = p->parentNode()) {
                     for (Node* n = p->nextSibling(); n; n = n->nextSibling()) {
@@ -315,7 +316,7 @@
             return;
         case PrecedingAxis: {
             if (context->isAttributeNode())
-                context = static_cast<Attr*>(context)->ownerElement();
+                context = toAttr(context)->ownerElement();
 
             Node* n = context;
             while (ContainerNode* parent = n->parentNode()) {
@@ -375,7 +376,7 @@
                 nodes.append(context);
             Node* n = context;
             if (context->isAttributeNode()) {
-                n = static_cast<Attr*>(context)->ownerElement();
+                n = toAttr(context)->ownerElement();
                 if (nodeMatches(n, AncestorOrSelfAxis, m_nodeTest))
                     nodes.append(n);
             }
diff --git a/Source/core/xml/XSLStyleSheetLibxslt.cpp b/Source/core/xml/XSLStyleSheetLibxslt.cpp
index 0c11fda..19d6e47 100644
--- a/Source/core/xml/XSLStyleSheetLibxslt.cpp
+++ b/Source/core/xml/XSLStyleSheetLibxslt.cpp
@@ -30,7 +30,8 @@
 #include "core/xml/XSLImportRule.h"
 #include "core/xml/XSLTProcessor.h"
 #include "core/xml/parser/XMLDocumentParserScope.h"
-#include <wtf/text/CString.h>
+#include "core/xml/parser/XMLParserInput.h"
+#include "wtf/text/CString.h"
 
 #include <libxml/uri.h>
 #include <libxslt/xsltutils.h>
@@ -118,11 +119,9 @@
     return document->cachedResourceLoader();
 }
 
-bool XSLStyleSheet::parseString(const String& string)
+bool XSLStyleSheet::parseString(const String& source)
 {
     // Parse in a single chunk into an xmlDocPtr
-    const UChar BOM = 0xFEFF;
-    const unsigned char BOMHighByte = *reinterpret_cast<const unsigned char*>(&BOM);
     if (!m_stylesheetDocTaken)
         xmlFreeDoc(m_stylesheetDoc);
     m_stylesheetDocTaken = false;
@@ -133,11 +132,9 @@
         console = frame->page()->console();
 
     XMLDocumentParserScope scope(cachedResourceLoader(), XSLTProcessor::genericErrorFunc, XSLTProcessor::parseErrorFunc, console);
+    XMLParserInput input(source);
 
-    const char* buffer = reinterpret_cast<const char*>(string.characters());
-    int size = string.length() * sizeof(UChar);
-
-    xmlParserCtxtPtr ctxt = xmlCreateMemoryParserCtxt(buffer, size);
+    xmlParserCtxtPtr ctxt = xmlCreateMemoryParserCtxt(input.data(), input.size());
     if (!ctxt)
         return 0;
 
@@ -153,14 +150,12 @@
         xmlDictReference(ctxt->dict);
     }
 
-    m_stylesheetDoc = xmlCtxtReadMemory(ctxt, buffer, size,
-        finalURL().string().utf8().data(),
-        BOMHighByte == 0xFF ? "UTF-16LE" : "UTF-16BE",
+    m_stylesheetDoc = xmlCtxtReadMemory(ctxt, input.data(), input.size(),
+        finalURL().string().utf8().data(), input.encoding(),
         XML_PARSE_NOENT | XML_PARSE_DTDATTR | XML_PARSE_NOWARNING | XML_PARSE_NOCDATA);
+
     xmlFreeParserCtxt(ctxt);
-
     loadChildSheets();
-
     return m_stylesheetDoc;
 }
 
diff --git a/Source/core/xml/XSLTUnicodeSort.cpp b/Source/core/xml/XSLTUnicodeSort.cpp
index 4f40912..2ad7102 100644
--- a/Source/core/xml/XSLTUnicodeSort.cpp
+++ b/Source/core/xml/XSLTUnicodeSort.cpp
@@ -165,7 +165,7 @@
                     } else {
                         String str1 = String::fromUTF8((const char*)results[j]->stringval);
                         String str2 = String::fromUTF8((const char*)results[j + incr]->stringval);
-                        tst = collator.collate(str1.characters(), str1.length(), str2.characters(), str2.length());
+                        tst = collator.collate(str1.bloatedCharacters(), str1.length(), str2.bloatedCharacters(), str2.length());
                     }
                     if (descending)
                         tst = -tst;
@@ -220,7 +220,7 @@
                             } else {
                                 String str1 = String::fromUTF8((const char*)res[j]->stringval);
                                 String str2 = String::fromUTF8((const char*)res[j + incr]->stringval);
-                                tst = collator.collate(str1.characters(), str1.length(), str2.characters(), str2.length());
+                                tst = collator.collate(str1.bloatedCharacters(), str1.length(), str2.bloatedCharacters(), str2.length());
                             }
                             if (desc)
                                 tst = -tst;
diff --git a/Source/core/xml/parser/XMLDocumentParser.cpp b/Source/core/xml/parser/XMLDocumentParser.cpp
index d56f283..bebcde2 100644
--- a/Source/core/xml/parser/XMLDocumentParser.cpp
+++ b/Source/core/xml/parser/XMLDocumentParser.cpp
@@ -63,7 +63,9 @@
 #include "core/xml/XMLErrors.h"
 #include "core/xml/XMLTreeViewer.h"
 #include "core/xml/parser/XMLDocumentParserScope.h"
+#include "core/xml/parser/XMLParserInput.h"
 #include "weborigin/SecurityOrigin.h"
+#include "wtf/TemporaryChange.h"
 
 using namespace std;
 
@@ -533,17 +535,39 @@
     element->parserSetAttributes(attributeVector);
 }
 
-static void switchToUTF16(xmlParserCtxtPtr ctxt)
+static void switchEncoding(xmlParserCtxtPtr ctxt, bool is8Bit)
 {
     // Hack around libxml2's lack of encoding overide support by manually
     // resetting the encoding to UTF-16 before every chunk.  Otherwise libxml
     // will detect <?xml version="1.0" encoding="<encoding name>"?> blocks
     // and switch encodings, causing the parse to fail.
+    if (is8Bit) {
+        xmlSwitchEncoding(ctxt, XML_CHAR_ENCODING_8859_1);
+        return;
+    }
+
     const UChar BOM = 0xFEFF;
     const unsigned char BOMHighByte = *reinterpret_cast<const unsigned char*>(&BOM);
     xmlSwitchEncoding(ctxt, BOMHighByte == 0xFF ? XML_CHAR_ENCODING_UTF16LE : XML_CHAR_ENCODING_UTF16BE);
 }
 
+static void parseChunk(xmlParserCtxtPtr ctxt, const String& chunk)
+{
+    bool is8Bit = chunk.is8Bit();
+    switchEncoding(ctxt, is8Bit);
+    if (is8Bit)
+        xmlParseChunk(ctxt, reinterpret_cast<const char*>(chunk.characters8()), sizeof(LChar) * chunk.length(), 0);
+    else
+        xmlParseChunk(ctxt, reinterpret_cast<const char*>(chunk.characters16()), sizeof(UChar) * chunk.length(), 0);
+}
+
+static void finishParsing(xmlParserCtxtPtr ctxt)
+{
+    xmlParseChunk(ctxt, 0, 0, 1);
+}
+
+#define xmlParseChunk #error "Use parseChunk instead to select the correct encoding."
+
 static bool shouldAllowExternalLoad(const KURL& url)
 {
     String urlString = url.string();
@@ -657,12 +681,9 @@
     xmlParserCtxtPtr parser = xmlCreatePushParserCtxt(handlers, 0, 0, 0, 0);
     parser->_private = userData;
     parser->replaceEntities = true;
-    switchToUTF16(parser);
-
     return adoptRef(new XMLParserContext(parser));
 }
 
-
 // Chunk should be encoded in UTF-8
 PassRefPtr<XMLParserContext> XMLParserContext::createMemoryParser(xmlSAXHandlerPtr handlers, void* userData, const CString& chunk)
 {
@@ -712,6 +733,7 @@
     , m_view(frameView)
     , m_context(0)
     , m_currentNode(document)
+    , m_isCurrentlyParsing8BitChunk(false)
     , m_sawError(false)
     , m_sawCSS(false)
     , m_sawXSLTransform(false)
@@ -734,6 +756,7 @@
     , m_view(0)
     , m_context(0)
     , m_currentNode(fragment)
+    , m_isCurrentlyParsing8BitChunk(false)
     , m_sawError(false)
     , m_sawCSS(false)
     , m_sawXSLTransform(false)
@@ -810,15 +833,15 @@
 
     // libXML throws an error if you try to switch the encoding for an empty string.
     if (parseString.length()) {
-        // JavaScript may cause the parser to detach during xmlParseChunk
+        // JavaScript may cause the parser to detach during parseChunk
         // keep this alive until this function is done.
         RefPtr<XMLDocumentParser> protect(this);
 
-        switchToUTF16(context->context());
         XMLDocumentParserScope scope(document()->cachedResourceLoader());
-        xmlParseChunk(context->context(), reinterpret_cast<const char*>(parseString.characters()), sizeof(UChar) * parseString.length(), 0);
+        TemporaryChange<bool> encodingScope(m_isCurrentlyParsing8BitChunk, parseString.is8Bit());
+        parseChunk(context->context(), parseString);
 
-        // JavaScript (which may be run under the xmlParseChunk callstack) may
+        // JavaScript (which may be run under the parseChunk callstack) may
         // cause the parser to be stopped or detached.
         if (isStopped())
             return;
@@ -1316,8 +1339,9 @@
 static void startDocumentHandler(void* closure)
 {
     xmlParserCtxt* ctxt = static_cast<xmlParserCtxt*>(closure);
-    switchToUTF16(ctxt);
-    getParser(closure)->startDocument(toString(ctxt->version), toString(ctxt->encoding), ctxt->standalone);
+    XMLDocumentParser* parser = getParser(closure);
+    switchEncoding(ctxt, parser->isCurrentlyParsing8BitChunk());
+    parser->startDocument(toString(ctxt->version), toString(ctxt->encoding), ctxt->standalone);
     xmlSAX2StartDocument(closure);
 }
 
@@ -1400,7 +1424,7 @@
             // Tell libxml we're done.
             {
                 XMLDocumentParserScope scope(document()->cachedResourceLoader());
-                xmlParseChunk(context(), 0, 0, 1);
+                finishParsing(context());
             }
 
             m_context = 0;
@@ -1433,20 +1457,12 @@
 {
     if (source.isEmpty())
         return 0;
-
     // Parse in a single chunk into an xmlDocPtr
     // FIXME: Hook up error handlers so that a failure to parse the main document results in
     // good error messages.
-    const UChar BOM = 0xFEFF;
-    const unsigned char BOMHighByte = *reinterpret_cast<const unsigned char*>(&BOM);
-
     XMLDocumentParserScope scope(cachedResourceLoader, errorFunc, 0);
-    xmlDocPtr sourceDoc = xmlReadMemory(reinterpret_cast<const char*>(source.characters()),
-                                        source.length() * sizeof(UChar),
-                                        url.latin1().data(),
-                                        BOMHighByte == 0xFF ? "UTF-16LE" : "UTF-16BE",
-                                        XSLT_PARSE_OPTIONS);
-    return sourceDoc;
+    XMLParserInput input(source);
+    return xmlReadMemory(input.data(), input.size(), url.latin1().data(), input.encoding(), XSLT_PARSE_OPTIONS);
 }
 
 OrdinalNumber XMLDocumentParser::lineNumber() const
@@ -1578,7 +1594,8 @@
     sax.initialized = XML_SAX2_MAGIC;
     RefPtr<XMLParserContext> parser = XMLParserContext::createStringParser(&sax, &state);
     String parseString = "<?xml version=\"1.0\"?><attrs " + string + " />";
-    xmlParseChunk(parser->context(), reinterpret_cast<const char*>(parseString.characters()), parseString.length() * sizeof(UChar), 1);
+    parseChunk(parser->context(), parseString);
+    finishParsing(parser->context());
     attrsOK = state.gotAttributes;
     return state.attributes;
 }
diff --git a/Source/core/xml/parser/XMLDocumentParser.h b/Source/core/xml/parser/XMLDocumentParser.h
index 9bc693c..b0be668 100644
--- a/Source/core/xml/parser/XMLDocumentParser.h
+++ b/Source/core/xml/parser/XMLDocumentParser.h
@@ -25,13 +25,13 @@
 #ifndef XMLDocumentParser_h
 #define XMLDocumentParser_h
 
-#include <libxml/tree.h>
-#include "core/dom/FragmentScriptingPermission.h"
+#include "core/dom/ParserContentPolicy.h"
 #include "core/dom/ScriptableDocumentParser.h"
 #include "core/loader/cache/CachedResourceClient.h"
 #include "core/loader/cache/CachedResourceHandle.h"
 #include "core/platform/text/SegmentedString.h"
 #include "core/xml/XMLErrors.h"
+#include <libxml/tree.h>
 #include <wtf/HashMap.h>
 #include <wtf/OwnPtr.h>
 #include <wtf/text/CString.h>
@@ -83,6 +83,8 @@
         void setIsXHTMLDocument(bool isXHTML) { m_isXHTMLDocument = isXHTML; }
         bool isXHTMLDocument() const { return m_isXHTMLDocument; }
 
+        bool isCurrentlyParsing8BitChunk() { return m_isCurrentlyParsing8BitChunk; }
+
         static bool parseDocumentFragment(const String&, DocumentFragment*, Element* parent = 0, ParserContentPolicy = AllowScriptingContent);
 
         // Used by the XMLHttpRequest to check if the responseXML was well formed.
@@ -165,6 +167,7 @@
 
         RefPtr<Text> m_leafTextNode;
 
+        bool m_isCurrentlyParsing8BitChunk;
         bool m_sawError;
         bool m_sawCSS;
         bool m_sawXSLTransform;
diff --git a/Source/core/xml/parser/XMLParserInput.h b/Source/core/xml/parser/XMLParserInput.h
new file mode 100644
index 0000000..7404012
--- /dev/null
+++ b/Source/core/xml/parser/XMLParserInput.h
@@ -0,0 +1,76 @@
+/*
+ * Copyright (C) 2013 Google Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are
+ * met:
+ *
+ *     * Redistributions of source code must retain the above copyright
+ * notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above
+ * copyright notice, this list of conditions and the following disclaimer
+ * in the documentation and/or other materials provided with the
+ * distribution.
+ *     * Neither the name of Google Inc. nor the names of its
+ * contributors may be used to endorse or promote products derived from
+ * this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
+ * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
+ * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
+ * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
+ * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+ * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
+ * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
+ * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
+ * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#ifndef XMLParserInput_h
+#define XMLParserInput_h
+
+#include "wtf/text/WTFString.h"
+
+namespace WebCore {
+
+class XMLParserInput {
+public:
+    explicit XMLParserInput(const String& source)
+        : m_source(source)
+        , m_data(0)
+        , m_size(0)
+        , m_encoding(0)
+    {
+        if (m_source.isEmpty())
+            return;
+
+        const UChar BOM = 0xFEFF;
+        const unsigned char BOMHighByte = *reinterpret_cast<const unsigned char*>(&BOM);
+
+        if (m_source.is8Bit()) {
+            m_encoding = "iso-8859-1";
+            m_data = reinterpret_cast<const char*>(m_source.characters8());
+            m_size = m_source.length() * sizeof(LChar);
+        } else {
+            m_encoding = BOMHighByte == 0xFF ? "UTF-16LE" : "UTF-16BE";
+            m_data = reinterpret_cast<const char*>(m_source.characters16());
+            m_size = m_source.length() * sizeof(UChar);
+        }
+    }
+
+    const char* encoding() const { return m_encoding; }
+    const char* data() const { return m_data; }
+    int size() const { return m_size; }
+
+private:
+    String m_source;
+    const char* m_encoding;
+    const char* m_data;
+    int m_size;
+};
+
+}
+
+#endif