Merge mozilla-central to fx-team
authorCarsten "Tomcat" Book <cbook@mozilla.com>
Tue, 06 Sep 2016 15:43:49 +0200
changeset 312845 e403c34977380158c098158767c990849316a9fd
parent 312844 9748e79666b98653302f93b7f4d9691c35d1f7aa (current diff)
parent 312809 bec2b7e3c0eb2adf0370f94802eca96e41f5879b (diff)
child 312846 97633d930c8f10ca5b8c9a7986bc390900f5970a
push id30662
push userkwierso@gmail.com
push dateWed, 07 Sep 2016 00:34:56 +0000
treeherdermozilla-central@91c2b9d5c135 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
milestone51.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge mozilla-central to fx-team
browser/components/originattributes/test/browser/browser_dummy.js
dom/base/test/test_bug704320_http_http.html
dom/base/test/test_bug704320_http_https.html
dom/base/test/test_bug704320_https_http.html
dom/base/test/test_bug704320_https_https.html
security/sandbox/chromium/base/atomicops_internals_arm_gcc.h
security/sandbox/chromium/base/atomicops_internals_x86_gcc.h
security/sandbox/chromium/base/basictypes.h
security/sandbox/chromium/base/float_util.h
security/sandbox/chromium/base/port.h
security/sandbox/chromium/base/safe_strerror_posix.cc
security/sandbox/chromium/base/safe_strerror_posix.h
security/sandbox/chromium/sandbox/linux/seccomp-bpf/basicblock.cc
security/sandbox/chromium/sandbox/linux/seccomp-bpf/basicblock.h
security/sandbox/chromium/sandbox/linux/seccomp-bpf/codegen.cc
security/sandbox/chromium/sandbox/linux/seccomp-bpf/codegen.h
security/sandbox/chromium/sandbox/linux/seccomp-bpf/codegen_unittest.cc
security/sandbox/chromium/sandbox/linux/seccomp-bpf/errorcode.cc
security/sandbox/chromium/sandbox/linux/seccomp-bpf/errorcode.h
security/sandbox/chromium/sandbox/linux/seccomp-bpf/errorcode_unittest.cc
security/sandbox/chromium/sandbox/linux/seccomp-bpf/instruction.h
security/sandbox/chromium/sandbox/linux/seccomp-bpf/linux_seccomp.h
security/sandbox/chromium/sandbox/linux/seccomp-bpf/syscall_iterator.cc
security/sandbox/chromium/sandbox/linux/seccomp-bpf/syscall_iterator.h
security/sandbox/chromium/sandbox/linux/seccomp-bpf/syscall_iterator_unittest.cc
security/sandbox/chromium/sandbox/linux/seccomp-bpf/verifier.cc
security/sandbox/chromium/sandbox/linux/seccomp-bpf/verifier.h
security/sandbox/chromium/sandbox/linux/services/android_arm_ucontext.h
security/sandbox/chromium/sandbox/linux/services/android_futex.h
security/sandbox/chromium/sandbox/linux/services/android_i386_ucontext.h
security/sandbox/chromium/sandbox/linux/services/android_ucontext.h
security/sandbox/chromium/sandbox/linux/services/android_x86_64_ucontext.h
security/sandbox/chromium/sandbox/linux/services/arm_linux_syscalls.h
security/sandbox/chromium/sandbox/linux/services/linux_syscalls.h
security/sandbox/chromium/sandbox/linux/services/x86_32_linux_syscalls.h
security/sandbox/chromium/sandbox/linux/services/x86_64_linux_syscalls.h
security/sandbox/chromium/sandbox/win/src/handle_table.cc
security/sandbox/chromium/sandbox/win/src/handle_table.h
security/sandbox/chromium/sandbox/win/src/shared_handles.cc
security/sandbox/chromium/sandbox/win/src/shared_handles.h
--- a/CLOBBER
+++ b/CLOBBER
@@ -17,9 +17,9 @@
 #
 # Modifying this file will now automatically clobber the buildbot machines \o/
 #
 
 # Are you updating CLOBBER because you think it's needed for your WebIDL
 # changes to stick? As of bug 928195, this shouldn't be necessary! Please
 # don't change CLOBBER for WebIDL changes any more.
 
-Bug 1289951 maybe needed a clobber to fix xpcshell tests?
+Bug 1287426 - Clobber required because of Linux Chromium sandbox file moves.
--- a/browser/app/profile/firefox.js
+++ b/browser/app/profile/firefox.js
@@ -521,16 +521,18 @@ pref("privacy.cpd.openWindows",         
 // 6 - Last 24 hours
 pref("privacy.sanitize.timeSpan", 1);
 pref("privacy.sanitize.sanitizeOnShutdown", false);
 
 pref("privacy.sanitize.migrateFx3Prefs",    false);
 
 pref("privacy.panicButton.enabled",         true);
 
+pref("privacy.firstparty.isolate",          false);
+
 pref("network.proxy.share_proxy_settings",  false); // use the same proxy settings for all protocols
 
 // simple gestures support
 pref("browser.gesture.swipe.left", "Browser:BackOrBackDuplicate");
 pref("browser.gesture.swipe.right", "Browser:ForwardOrForwardDuplicate");
 pref("browser.gesture.swipe.up", "cmd_scrollTop");
 pref("browser.gesture.swipe.down", "cmd_scrollBottom");
 #ifdef XP_MACOSX
--- a/browser/components/originattributes/test/browser/browser.ini
+++ b/browser/components/originattributes/test/browser/browser.ini
@@ -1,10 +1,24 @@
 [DEFAULT]
 skip-if = buildapp == "mulet"
 tags = usercontextid firstpartyisolation originattributes
 support-files =
+  dummy.html
   file_firstPartyBasic.html
   head.js
+  test.js
+  test.js^headers^
+  test.html
+  test2.html
+  test2.js
+  test2.js^headers^
+  test_firstParty.html
+  test_firstParty_cookie.html
+  test_firstParty_html_redirect.html
+  test_firstParty_http_redirect.html
+  test_firstParty_http_redirect.html^headers^
+  test_firstParty_iframe_http_redirect.html
+  test_firstParty_postMessage.html
+  window.html
 
-[browser_dummy.js]
-skip-if = true
+[browser_firstPartyIsolation.js]
 [browser_localStorageIsolation.js]
deleted file mode 100644
--- a/browser/components/originattributes/test/browser/browser_dummy.js
+++ /dev/null
@@ -1,10 +0,0 @@
-/*
- * This is a dummy test case which makes this could be built.
- * Should be removed after actual tests landed.
- */
-
-"use strict";
-
-add_task(function* () {
-  ok(true, "Make this test pass anyway.");
-});
new file mode 100644
--- /dev/null
+++ b/browser/components/originattributes/test/browser/browser_firstPartyIsolation.js
@@ -0,0 +1,174 @@
+const BASE_URL = "http://mochi.test:8888/browser/browser/components/originattributes/test/browser/";
+const BASE_DOMAIN = "mochi.test";
+
+add_task(function* setup() {
+  Services.prefs.setBoolPref("privacy.firstparty.isolate", true);
+  registerCleanupFunction(function () {
+    Services.prefs.clearUserPref("privacy.firstparty.isolate");
+  });
+});
+
+/**
+ * Test for the top-level document and child iframes should have the
+ * firstPartyDomain attribute.
+ */
+add_task(function* principal_test() {
+  let tab = gBrowser.addTab(BASE_URL + "test_firstParty.html");
+  yield BrowserTestUtils.browserLoaded(tab.linkedBrowser, true, function (url) {
+    return url == BASE_URL + "test_firstParty.html";
+  });
+
+  yield ContentTask.spawn(tab.linkedBrowser, { firstPartyDomain: BASE_DOMAIN }, function* (attrs) {
+    info("document principal: " + content.document.nodePrincipal.origin);
+    Assert.equal(docShell.getOriginAttributes().firstPartyDomain, "",
+                 "top-level docShell shouldn't have firstPartyDomain attribute.");
+    Assert.equal(content.document.nodePrincipal.originAttributes.firstPartyDomain,
+                 attrs.firstPartyDomain, "The document should have firstPartyDomain");
+
+    for (let i = 1; i < 4; i++) {
+      let iframe = content.document.getElementById("iframe" + i);
+      info("iframe principal: " + iframe.contentDocument.nodePrincipal.origin);
+      Assert.equal(iframe.frameLoader.docShell.getOriginAttributes().firstPartyDomain,
+                   attrs.firstPartyDomain, "iframe's docshell should have firstPartyDomain");
+      Assert.equal(iframe.contentDocument.nodePrincipal.originAttributes.firstPartyDomain,
+                   attrs.firstPartyDomain, "iframe should have firstPartyDomain");
+    }
+  });
+
+  gBrowser.removeTab(tab);
+});
+
+/**
+ * Test for the cookie jars of the top-level document and child iframe should be
+ * isolated by firstPartyDomain.
+ */
+add_task(function* cookie_test() {
+  let tab = gBrowser.addTab(BASE_URL + "test_firstParty_cookie.html");
+  yield BrowserTestUtils.browserLoaded(tab.linkedBrowser, true);
+
+  let iter = Services.cookies.enumerator;
+  let count = 0;
+  while (iter.hasMoreElements()) {
+    count++;
+    let cookie = iter.getNext().QueryInterface(Ci.nsICookie2);
+    Assert.equal(cookie.value, "foo", "Cookie value should be foo");
+    Assert.equal(cookie.originAttributes.firstPartyDomain, BASE_DOMAIN, "Cookie's origin attributes should be " + BASE_DOMAIN);
+  }
+
+  // one cookie is from requesting test.js from top-level doc, and the other from
+  // requesting test2.js from iframe test2.html.
+  Assert.equal(count, 2, "Should have two cookies");
+
+  gBrowser.removeTab(tab);
+});
+
+/**
+ * Test for after redirect, the top-level document should update the firstPartyDomain
+ * attribute. However if the redirect is happening on the iframe, the attribute
+ * should remain the same.
+ */
+add_task(function* redirect_test() {
+  let tab = gBrowser.addTab(BASE_URL + "test_firstParty_http_redirect.html");
+  yield BrowserTestUtils.browserLoaded(tab.linkedBrowser);
+  yield ContentTask.spawn(tab.linkedBrowser, { firstPartyDomain: "example.com" }, function* (attrs) {
+    info("document principal: " + content.document.nodePrincipal.origin);
+    info("document uri: " + content.document.documentURI);
+
+    Assert.equal(content.document.documentURI, "http://example.com/browser/browser/components/originattributes/test/browser/dummy.html",
+                 "The page should have been redirected to http://example.com/browser/browser/components/originattributes/test/browser/dummy.html");
+    Assert.equal(content.document.nodePrincipal.originAttributes.firstPartyDomain,
+                 attrs.firstPartyDomain, "The document should have firstPartyDomain");
+  });
+
+  // Since this is a HTML redirect, we wait until the final page is loaded.
+  let tab2 = gBrowser.addTab(BASE_URL + "test_firstParty_html_redirect.html");
+  yield BrowserTestUtils.browserLoaded(tab2.linkedBrowser, false, function(url) {
+    return url == "http://example.com/";
+  });
+
+  yield ContentTask.spawn(tab2.linkedBrowser, { firstPartyDomain: "example.com" }, function* (attrs) {
+    info("2nd tab document principal: " + content.document.nodePrincipal.origin);
+    info("2nd tab document uri: " + content.document.documentURI);
+    Assert.equal(content.document.documentURI, "http://example.com/",
+                 "The page should have been redirected to http://example.com");
+    Assert.equal(content.document.nodePrincipal.originAttributes.firstPartyDomain,
+                 attrs.firstPartyDomain, "The document should have firstPartyDomain");
+  });
+
+  let tab3 = gBrowser.addTab(BASE_URL + "test_firstParty_iframe_http_redirect.html");
+  yield BrowserTestUtils.browserLoaded(tab3.linkedBrowser, true, function(url) {
+    return url == (BASE_URL + "test_firstParty_iframe_http_redirect.html");
+  });
+
+  // This redirect happens on the iframe, so unlike the two redirect tests above,
+  // the firstPartyDomain should still stick to the current top-level document,
+  // which is mochi.test.
+  yield ContentTask.spawn(tab3.linkedBrowser, { firstPartyDomain: "mochi.test" }, function* (attrs) {
+    let iframe = content.document.getElementById("iframe1");
+    info("iframe document principal: " + iframe.contentDocument.nodePrincipal.origin);
+    info("iframe document uri: " + iframe.contentDocument.documentURI);
+
+    Assert.equal(iframe.contentDocument.documentURI, "http://example.com/browser/browser/components/originattributes/test/browser/dummy.html",
+                 "The page should have been redirected to http://example.com/browser/browser/components/originattributes/test/browser/dummy.html");
+    Assert.equal(iframe.contentDocument.nodePrincipal.originAttributes.firstPartyDomain,
+                 attrs.firstPartyDomain, "The iframe should have firstPartyDomain: " + attrs.firstPartyDomain);
+  });
+
+  gBrowser.removeTab(tab);
+  gBrowser.removeTab(tab2);
+  gBrowser.removeTab(tab3);
+});
+
+/**
+ * Test for postMessage between document and iframe.
+ */
+add_task(function* postMessage_test() {
+  let tab = gBrowser.addTab(BASE_URL + "test_firstParty_postMessage.html");
+
+  // The top-level page will post a message to its child iframe, and wait for
+  // another message from the iframe, once it receives the message, it will
+  // create another iframe, dummy.html.
+  // So we wait until dummy.html is loaded
+  yield BrowserTestUtils.browserLoaded(tab.linkedBrowser, true, function (url) {
+    return url == BASE_URL + "dummy.html";
+  });
+
+  yield ContentTask.spawn(tab.linkedBrowser, {}, function* () {
+    info("document principal: " + content.document.nodePrincipal.origin);
+    let value = content.document.getElementById("message").textContent;
+    Assert.equal(value, "OK");
+  });
+
+  gBrowser.removeTab(tab);
+});
+
+/**
+ * When the web page calls window.open, the new window should have the same
+ * firstPartyDomain attribute.
+ */
+add_task(function* openWindow_test() {
+  Services.prefs.setIntPref("browser.link.open_newwindow", 2);
+  registerCleanupFunction(function () {
+    Services.prefs.clearUserPref("browser.link.open_newwindow");
+  });
+
+  let tab = gBrowser.addTab(BASE_URL + "window.html");
+  let win = yield BrowserTestUtils.waitForNewWindow();
+
+  yield ContentTask.spawn(win.gBrowser.selectedBrowser, { firstPartyDomain: "mochi.test" }, function* (attrs) {
+    Assert.equal(docShell.getOriginAttributes().firstPartyDomain, attrs.firstPartyDomain,
+                 "window.open() should have firstPartyDomain attribute");
+    Assert.equal(content.document.nodePrincipal.originAttributes.firstPartyDomain,
+                 attrs.firstPartyDomain, "The document should have firstPartyDomain");
+
+    let iframe = content.document.getElementById("iframe1");
+    Assert.equal(iframe.frameLoader.docShell.getOriginAttributes().firstPartyDomain,
+                 attrs.firstPartyDomain, "iframe's docshell should have firstPartyDomain");
+    Assert.equal(iframe.contentDocument.nodePrincipal.originAttributes.firstPartyDomain,
+                 attrs.firstPartyDomain, "iframe should have firstPartyDomain");
+  });
+
+  gBrowser.removeTab(tab);
+  yield BrowserTestUtils.closeWindow(win);
+});
+
new file mode 100644
--- /dev/null
+++ b/browser/components/originattributes/test/browser/dummy.html
@@ -0,0 +1,9 @@
+<html>
+<head>
+<title>Dummy test page</title>
+<meta http-equiv="Content-Type" content="text/html;charset=utf-8"></meta>
+</head>
+<body>
+<p>Dummy test page</p>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/browser/components/originattributes/test/browser/test.html
@@ -0,0 +1,25 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <meta charset="utf-8">
+  <title>Test for Bug 1260931</title>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script>
+  window.onmessage = function (evt) {
+    if (evt.data != "HI") {
+      return;
+    }
+
+    window.parent.postMessage("OK", "http://mochi.test:8888");
+  };
+
+  setTimeout(function() {
+    window.parent.postMessage("KO", "http://mochi.test:8888");
+  }, 1000);
+
+  </script>
+</head>
+<body>
+  Hello World.
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/browser/components/originattributes/test/browser/test.js
@@ -0,0 +1,1 @@
+var i = 1;
new file mode 100644
--- /dev/null
+++ b/browser/components/originattributes/test/browser/test.js^headers^
@@ -0,0 +1,1 @@
+Set-Cookie: test=foo
new file mode 100644
--- /dev/null
+++ b/browser/components/originattributes/test/browser/test2.html
@@ -0,0 +1,12 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <meta charset="utf-8">
+  <title>Test for Bug 1260931</title>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script src="test2.js"></script>
+</head>
+<body>
+  Hello World.
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/browser/components/originattributes/test/browser/test2.js
@@ -0,0 +1,1 @@
+var i = 1;
new file mode 100644
--- /dev/null
+++ b/browser/components/originattributes/test/browser/test2.js^headers^
@@ -0,0 +1,1 @@
+Set-Cookie: test2=foo
new file mode 100644
--- /dev/null
+++ b/browser/components/originattributes/test/browser/test_firstParty.html
@@ -0,0 +1,15 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <meta charset="utf-8"/>
+  <title>Test for Bug 1260931</title>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+  <div>
+    <iframe id="iframe1" src="http://example.com"></iframe>
+    <iframe id="iframe2" sandbox="" src="http://example.com"></iframe>
+    <iframe id="iframe3" sandbox="allow-same-origin" src="http://example.com"></iframe>
+  </div>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/browser/components/originattributes/test/browser/test_firstParty_cookie.html
@@ -0,0 +1,13 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <meta charset="utf-8">
+  <title>Test for Bug 1260931</title>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+  <script src="test.js"></script>
+</head>
+<body>
+  Hello World.
+  <iframe id="iframe1" src="test2.html"></iframe>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/browser/components/originattributes/test/browser/test_firstParty_html_redirect.html
@@ -0,0 +1,9 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <meta charset="utf8" http-equiv="refresh" content="0; url=http://example.com/"/>
+  <title>Test for Bug 1260931</title>
+</head>
+<body>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/browser/components/originattributes/test/browser/test_firstParty_http_redirect.html
@@ -0,0 +1,9 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <meta charset="utf-8"/>
+  <title>Test for Bug 1260931</title>
+</head>
+<body>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/browser/components/originattributes/test/browser/test_firstParty_http_redirect.html^headers^
@@ -0,0 +1,2 @@
+HTTP 302 Found
+Location: http://example.com/browser/browser/components/originattributes/test/browser/dummy.html
new file mode 100644
--- /dev/null
+++ b/browser/components/originattributes/test/browser/test_firstParty_iframe_http_redirect.html
@@ -0,0 +1,13 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <meta charset="utf-8"/>
+  <title>Test for Bug 1260931</title>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<body>
+  <div>
+    <iframe id="iframe1" src="test_firstParty_http_redirect.html"></iframe>
+  </div>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/browser/components/originattributes/test/browser/test_firstParty_postMessage.html
@@ -0,0 +1,28 @@
+<!DOCTYPE HTML>
+<html>
+<head>
+  <meta charset="utf-8"/>
+  <title>Test for Bug 1260931</title>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+</head>
+<script>
+function onload() {
+  let iframe1 = document.getElementById("iframe1");
+  iframe1.contentWindow.postMessage("HI", "http://mochi.test:8888");
+}
+
+window.onmessage = function (evt) {
+  document.getElementById("message").textContent = evt.data;
+
+  let iframe2 = document.createElement("iframe");
+  iframe2.src = "dummy.html";
+  document.body.appendChild(iframe2);
+};
+</script>
+<body onload="onload()">
+  <div>
+    <iframe id="iframe1" src="test.html"></iframe>
+    <span id="message"></span>
+  </div>
+</body>
+</html>
new file mode 100644
--- /dev/null
+++ b/browser/components/originattributes/test/browser/window.html
@@ -0,0 +1,13 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
+<html>
+  <head>
+    <meta charset="utf8">
+    <title>Page creating a popup</title>
+  </head>
+  <body>
+    <script type="text/javascript">
+       var w = window.open();
+       w.document.body.innerHTML = "<iframe id='iframe1' src='data:text/plain,test2'></iframe>";
+    </script>
+  </body>
+</html>
--- a/build/clang-plugin/clang-plugin.cpp
+++ b/build/clang-plugin/clang-plugin.cpp
@@ -264,16 +264,21 @@ bool isIgnoredPathForImplicitConversion(
   SmallString<1024> FileName = SM.getFilename(Loc);
   llvm::sys::fs::make_absolute(FileName);
   llvm::sys::path::reverse_iterator Begin = llvm::sys::path::rbegin(FileName),
                                     End = llvm::sys::path::rend(FileName);
   for (; Begin != End; ++Begin) {
     if (Begin->compare_lower(StringRef("graphite2")) == 0) {
       return true;
     }
+    if (Begin->compare_lower(StringRef("chromium")) == 0) {
+      // Ignore security/sandbox/chromium but not ipc/chromium.
+      ++Begin;
+      return Begin != End && Begin->compare_lower(StringRef("sandbox")) == 0;
+    }
   }
   return false;
 }
 
 bool isInterestingDeclForImplicitConversion(const Decl *Declaration) {
   return !isInIgnoredNamespaceForImplicitConversion(Declaration) &&
          !isIgnoredPathForImplicitConversion(Declaration);
 }
--- a/caps/BasePrincipal.cpp
+++ b/caps/BasePrincipal.cpp
@@ -7,16 +7,17 @@
 #include "mozilla/BasePrincipal.h"
 
 #include "nsDocShell.h"
 #ifdef MOZ_CRASHREPORTER
 #include "nsExceptionHandler.h"
 #endif
 #include "nsIAddonPolicyService.h"
 #include "nsIContentSecurityPolicy.h"
+#include "nsIEffectiveTLDService.h"
 #include "nsIObjectInputStream.h"
 #include "nsIObjectOutputStream.h"
 
 #include "nsPrincipal.h"
 #include "nsNetUtil.h"
 #include "nsIURIWithPrincipal.h"
 #include "nsNullPrincipal.h"
 #include "nsScriptSecurityManager.h"
@@ -42,29 +43,31 @@ PrincipalOriginAttributes::InheritFromDo
   mUserContextId = aAttrs.mUserContextId;
 
   // TODO:
   // Bug 1225349 - PrincipalOriginAttributes should inherit mSignedPkg
   // accordingly by URI
   mSignedPkg = aAttrs.mSignedPkg;
 
   mPrivateBrowsingId = aAttrs.mPrivateBrowsingId;
+  mFirstPartyDomain = aAttrs.mFirstPartyDomain;
 }
 
 void
 PrincipalOriginAttributes::InheritFromNecko(const NeckoOriginAttributes& aAttrs)
 {
   mAppId = aAttrs.mAppId;
   mInIsolatedMozBrowser = aAttrs.mInIsolatedMozBrowser;
 
   // addonId is computed from the principal URI and never propagated
   mUserContextId = aAttrs.mUserContextId;
   mSignedPkg = aAttrs.mSignedPkg;
 
   mPrivateBrowsingId = aAttrs.mPrivateBrowsingId;
+  mFirstPartyDomain = aAttrs.mFirstPartyDomain;
 }
 
 void
 DocShellOriginAttributes::InheritFromDocToChildDocShell(const PrincipalOriginAttributes& aAttrs)
 {
   mAppId = aAttrs.mAppId;
   mInIsolatedMozBrowser = aAttrs.mInIsolatedMozBrowser;
 
@@ -72,48 +75,70 @@ DocShellOriginAttributes::InheritFromDoc
   mUserContextId = aAttrs.mUserContextId;
 
   // TODO:
   // Bug 1225353 - DocShell/NeckoOriginAttributes should inherit
   // mSignedPkg accordingly by mSignedPkgInBrowser
   mSignedPkg = aAttrs.mSignedPkg;
 
   mPrivateBrowsingId = aAttrs.mPrivateBrowsingId;
+  mFirstPartyDomain = aAttrs.mFirstPartyDomain;
 }
 
 void
 NeckoOriginAttributes::InheritFromDocToNecko(const PrincipalOriginAttributes& aAttrs)
 {
   mAppId = aAttrs.mAppId;
   mInIsolatedMozBrowser = aAttrs.mInIsolatedMozBrowser;
 
   // addonId is computed from the principal URI and never propagated
   mUserContextId = aAttrs.mUserContextId;
 
   // TODO:
   // Bug 1225353 - DocShell/NeckoOriginAttributes should inherit
   // mSignedPkg accordingly by mSignedPkgInBrowser
 
   mPrivateBrowsingId = aAttrs.mPrivateBrowsingId;
+  mFirstPartyDomain = aAttrs.mFirstPartyDomain;
 }
 
 void
-NeckoOriginAttributes::InheritFromDocShellToNecko(const DocShellOriginAttributes& aAttrs)
+NeckoOriginAttributes::InheritFromDocShellToNecko(const DocShellOriginAttributes& aAttrs,
+                                                  const bool aIsTopLevelDocument,
+                                                  nsIURI* aURI)
 {
   mAppId = aAttrs.mAppId;
   mInIsolatedMozBrowser = aAttrs.mInIsolatedMozBrowser;
 
   // addonId is computed from the principal URI and never propagated
   mUserContextId = aAttrs.mUserContextId;
 
   // TODO:
   // Bug 1225353 - DocShell/NeckoOriginAttributes should inherit
   // mSignedPkg accordingly by mSignedPkgInBrowser
 
   mPrivateBrowsingId = aAttrs.mPrivateBrowsingId;
+
+  bool isFirstPartyEnabled = IsFirstPartyEnabled();
+
+  // When the pref is on, we also compute the firstPartyDomain attribute
+  // if this is for top-level document.
+  if (isFirstPartyEnabled && aIsTopLevelDocument) {
+    nsCOMPtr<nsIEffectiveTLDService> tldService = do_GetService(NS_EFFECTIVETLDSERVICE_CONTRACTID);
+    MOZ_ASSERT(tldService);
+    if (!tldService) {
+      return;
+    }
+
+    nsAutoCString baseDomain;
+    tldService->GetBaseDomain(aURI, 0, baseDomain);
+    mFirstPartyDomain = NS_ConvertUTF8toUTF16(baseDomain);
+  } else {
+    mFirstPartyDomain = aAttrs.mFirstPartyDomain;
+  }
 }
 
 void
 OriginAttributes::CreateSuffix(nsACString& aStr) const
 {
   UniquePtr<URLParams> params(new URLParams());
   nsAutoString value;
 
@@ -156,16 +181,21 @@ OriginAttributes::CreateSuffix(nsACStrin
   }
 
   if (mPrivateBrowsingId) {
     value.Truncate();
     value.AppendInt(mPrivateBrowsingId);
     params->Set(NS_LITERAL_STRING("privateBrowsingId"), value);
   }
 
+  if (!mFirstPartyDomain.IsEmpty()) {
+    MOZ_RELEASE_ASSERT(mFirstPartyDomain.FindCharInSet(dom::quota::QuotaManager::kReplaceChars) == kNotFound);
+    params->Set(NS_LITERAL_STRING("firstPartyDomain"), mFirstPartyDomain);
+  }
+
   aStr.Truncate();
 
   params->Serialize(value);
   if (!value.IsEmpty()) {
     aStr.AppendLiteral("^");
     aStr.Append(NS_ConvertUTF16toUTF8(value));
   }
 
@@ -242,16 +272,22 @@ public:
       int64_t val = aValue.ToInteger64(&rv);
       NS_ENSURE_SUCCESS(rv, false);
       NS_ENSURE_TRUE(val >= 0 && val <= UINT32_MAX, false);
       mOriginAttributes->mPrivateBrowsingId = static_cast<uint32_t>(val);
 
       return true;
     }
 
+    if (aName.EqualsLiteral("firstPartyDomain")) {
+      MOZ_RELEASE_ASSERT(mOriginAttributes->mFirstPartyDomain.IsEmpty());
+      mOriginAttributes->mFirstPartyDomain.Assign(aValue);
+      return true;
+    }
+
     // No other attributes are supported.
     return false;
   }
 
 private:
   OriginAttributes* mOriginAttributes;
 };
 
@@ -302,16 +338,31 @@ void
 OriginAttributes::SetFromGenericAttributes(const GenericOriginAttributes& aAttrs)
 {
   mAppId = aAttrs.mAppId;
   mInIsolatedMozBrowser = aAttrs.mInIsolatedMozBrowser;
   mAddonId = aAttrs.mAddonId;
   mUserContextId = aAttrs.mUserContextId;
   mSignedPkg = aAttrs.mSignedPkg;
   mPrivateBrowsingId = aAttrs.mPrivateBrowsingId;
+  mFirstPartyDomain = aAttrs.mFirstPartyDomain;
+}
+
+bool
+OriginAttributes::IsFirstPartyEnabled()
+{
+  // Cache the privacy.firstparty.isolate pref.
+  static bool sFirstPartyIsolation = false;
+  static bool sCachedFirstPartyPref = false;
+  if (!sCachedFirstPartyPref) {
+    sCachedFirstPartyPref = true;
+    Preferences::AddBoolVarCache(&sFirstPartyIsolation, "privacy.firstparty.isolate");
+  }
+
+  return sFirstPartyIsolation;
 }
 
 BasePrincipal::BasePrincipal()
 {}
 
 BasePrincipal::~BasePrincipal()
 {}
 
--- a/caps/BasePrincipal.h
+++ b/caps/BasePrincipal.h
@@ -32,17 +32,18 @@ class OriginAttributes : public dom::Ori
 public:
   bool operator==(const OriginAttributes& aOther) const
   {
     return mAppId == aOther.mAppId &&
            mInIsolatedMozBrowser == aOther.mInIsolatedMozBrowser &&
            mAddonId == aOther.mAddonId &&
            mUserContextId == aOther.mUserContextId &&
            mSignedPkg == aOther.mSignedPkg &&
-           mPrivateBrowsingId == aOther.mPrivateBrowsingId;
+           mPrivateBrowsingId == aOther.mPrivateBrowsingId &&
+           mFirstPartyDomain == aOther.mFirstPartyDomain;
   }
   bool operator!=(const OriginAttributes& aOther) const
   {
     return !(*this == aOther);
   }
 
   // Serializes/Deserializes non-default values into the suffix format, i.e.
   // |!key1=value1&key2=value2|. If there are no non-default attributes, this
@@ -60,16 +61,19 @@ public:
   void SyncAttributesWithPrivateBrowsing(bool aInPrivateBrowsing);
 
   void SetFromGenericAttributes(const GenericOriginAttributes& aAttrs);
 
 protected:
   OriginAttributes() {}
   explicit OriginAttributes(const OriginAttributesDictionary& aOther)
     : OriginAttributesDictionary(aOther) {}
+
+  // check if "privacy.firstparty.isolate" is enabled.
+  bool IsFirstPartyEnabled();
 };
 
 class PrincipalOriginAttributes;
 class DocShellOriginAttributes;
 class NeckoOriginAttributes;
 
 // Various classes in Gecko contain OriginAttributes members, and those
 // OriginAttributes get propagated to other classes according to certain rules.
@@ -131,17 +135,21 @@ public:
     mAppId = aAppId;
     mInIsolatedMozBrowser = aInIsolatedMozBrowser;
   }
 
   // Inheriting OriginAttributes from document to necko when a network request
   // is made.
   void InheritFromDocToNecko(const PrincipalOriginAttributes& aAttrs);
 
-  void InheritFromDocShellToNecko(const DocShellOriginAttributes& aAttrs);
+  // Inheriting OriginAttributes from a docshell when loading a top-level
+  // document.
+  void InheritFromDocShellToNecko(const DocShellOriginAttributes& aAttrs,
+                                  const bool aIsTopLevelDocument = false,
+                                  nsIURI* aURI = nullptr);
 };
 
 // For operating on OriginAttributes not associated with any data structure.
 class GenericOriginAttributes : public OriginAttributes
 {
 public:
   GenericOriginAttributes() {}
   explicit GenericOriginAttributes(const OriginAttributesDictionary& aOther)
@@ -184,16 +192,20 @@ public:
     if (mSignedPkg.WasPassed() && mSignedPkg.Value() != aAttrs.mSignedPkg) {
       return false;
     }
 
     if (mPrivateBrowsingId.WasPassed() && mPrivateBrowsingId.Value() != aAttrs.mPrivateBrowsingId) {
       return false;
     }
 
+    if (mFirstPartyDomain.WasPassed() && mFirstPartyDomain.Value() != aAttrs.mFirstPartyDomain) {
+      return false;
+    }
+
     return true;
   }
 
   bool Overlaps(const OriginAttributesPattern& aOther) const
   {
     if (mAppId.WasPassed() && aOther.mAppId.WasPassed() &&
         mAppId.Value() != aOther.mAppId.Value()) {
       return false;
@@ -220,16 +232,21 @@ public:
       return false;
     }
 
     if (mPrivateBrowsingId.WasPassed() && aOther.mPrivateBrowsingId.WasPassed() &&
         mPrivateBrowsingId.Value() != aOther.mPrivateBrowsingId.Value()) {
       return false;
     }
 
+    if (mFirstPartyDomain.WasPassed() && aOther.mFirstPartyDomain.WasPassed() &&
+        mFirstPartyDomain.Value() != aOther.mFirstPartyDomain.Value()) {
+      return false;
+    }
+
     return true;
   }
 };
 
 /*
  * Base class from which all nsIPrincipal implementations inherit. Use this for
  * default implementations and other commonalities between principal
  * implementations.
--- a/caps/nsScriptSecurityManager.cpp
+++ b/caps/nsScriptSecurityManager.cpp
@@ -431,47 +431,30 @@ nsScriptSecurityManager::GetChannelURIPr
     NS_PRECONDITION(aChannel, "Must have channel!");
 
     // Get the principal from the URI.  Make sure this does the same thing
     // as nsDocument::Reset and XULDocument::StartDocumentLoad.
     nsCOMPtr<nsIURI> uri;
     nsresult rv = NS_GetFinalChannelURI(aChannel, getter_AddRefs(uri));
     NS_ENSURE_SUCCESS(rv, rv);
 
-    nsCOMPtr<nsILoadContext> loadContext;
-    NS_QueryNotificationCallbacks(aChannel, loadContext);
-
     nsCOMPtr<nsILoadInfo> loadInfo;
     aChannel->GetLoadInfo(getter_AddRefs(loadInfo));
-    nsContentPolicyType contentPolicyType = nsIContentPolicy::TYPE_INVALID;
-    if (loadInfo) {
-      contentPolicyType = loadInfo->GetExternalContentPolicyType();
-    }
 
+    // Inherit the origin attributes from loadInfo.
+    // If this is a top-level document load, the origin attributes of the
+    // loadInfo will be set from nsDocShell::DoURILoad.
+    // For subresource loading, the origin attributes of the loadInfo is from
+    // its loadingPrincipal.
     PrincipalOriginAttributes attrs;
-    if (nsIContentPolicy::TYPE_DOCUMENT == contentPolicyType ||
-        nsIContentPolicy::TYPE_SUBDOCUMENT == contentPolicyType) {
-      // If it's document or sub-document, inherit originAttributes from
-      // the document.
-      if (loadContext) {
-        DocShellOriginAttributes docShellAttrs;
-        loadContext->GetOriginAttributes(docShellAttrs);
-        attrs.InheritFromDocShellToDoc(docShellAttrs, uri);
-      }
-    } else {
-      // Inherit origin attributes from loading principal if any.
-      nsCOMPtr<nsIPrincipal> loadingPrincipal;
-      if (loadInfo) {
-        loadInfo->GetLoadingPrincipal(getter_AddRefs(loadingPrincipal));
-      }
-      if (loadingPrincipal) {
-        attrs = BasePrincipal::Cast(loadingPrincipal)->OriginAttributesRef();
-      }
+
+    // For addons loadInfo might be null.
+    if (loadInfo) {
+      attrs.InheritFromNecko(loadInfo->GetOriginAttributes());
     }
-
     rv = MaybeSetAddonIdFromURI(attrs, uri);
     NS_ENSURE_SUCCESS(rv, rv);
     nsCOMPtr<nsIPrincipal> prin = BasePrincipal::CreateCodebasePrincipal(uri, attrs);
     prin.forget(aPrincipal);
     return *aPrincipal ? NS_OK : NS_ERROR_FAILURE;
 }
 
 NS_IMETHODIMP
--- a/caps/tests/unit/test_origin.js
+++ b/caps/tests/unit/test_origin.js
@@ -37,29 +37,33 @@ function checkOriginAttributes(prin, att
 
 // utility function useful for debugging
 function printAttrs(name, attrs) {
   do_print(name + " {\n" +
            "\tappId: " + attrs.appId + ",\n" +
            "\tuserContextId: " + attrs.userContextId + ",\n" +
            "\tinIsolatedMozBrowser: " + attrs.inIsolatedMozBrowser + ",\n" +
            "\taddonId: '" + attrs.addonId + "',\n" +
-           "\tsignedPkg: '" + attrs.signedPkg + "'\n}");
+           "\tsignedPkg: '" + attrs.signedPkg + "',\n" +
+           "\tprivateBrowsingId: '" + attrs.privateBrowsingId + "',\n" +
+           "\tfirstPartyDomain: '" + attrs.firstPartyDomain + "'\n}");
 }
 
 
 function checkValues(attrs, values) {
   values = values || {};
   //printAttrs("attrs", attrs);
   //printAttrs("values", values);
   do_check_eq(attrs.appId, values.appId || 0);
   do_check_eq(attrs.userContextId, values.userContextId || 0);
   do_check_eq(attrs.inIsolatedMozBrowser, values.inIsolatedMozBrowser || false);
   do_check_eq(attrs.addonId, values.addonId || '');
   do_check_eq(attrs.signedPkg, values.signedPkg || '');
+  do_check_eq(attrs.privateBrowsingId, values.privateBrowsingId || '');
+  do_check_eq(attrs.firstPartyDomain, values.firstPartyDomain || '');
 }
 
 function run_test() {
   // Attributeless origins.
   do_check_eq(ssm.getSystemPrincipal().origin, '[System Principal]');
   checkOriginAttributes(ssm.getSystemPrincipal());
   var exampleOrg = ssm.createCodebasePrincipal(makeURI('http://example.org'), {});
   do_check_eq(exampleOrg.origin, 'http://example.org');
@@ -117,16 +121,21 @@ function run_test() {
   checkOriginAttributes(exampleCom_appBrowser, {appId: 42, inIsolatedMozBrowser: true}, '^appId=42&inBrowser=1');
   do_check_eq(exampleCom_appBrowser.origin, 'https://www.example.com:123^appId=42&inBrowser=1');
 
   // Addon.
   var exampleOrg_addon = ssm.createCodebasePrincipal(makeURI('http://example.org'), {addonId: 'dummy'});
   checkOriginAttributes(exampleOrg_addon, { addonId: "dummy" }, '^addonId=dummy');
   do_check_eq(exampleOrg_addon.origin, 'http://example.org^addonId=dummy');
 
+  // First party Uri
+  var exampleOrg_firstPartyDomain = ssm.createCodebasePrincipal(makeURI('http://example.org'), {firstPartyDomain: 'example.org'});
+  checkOriginAttributes(exampleOrg_firstPartyDomain, { firstPartyDomain: "example.org" }, '^firstPartyDomain=example.org');
+  do_check_eq(exampleOrg_firstPartyDomain.origin, 'http://example.org^firstPartyDomain=example.org');
+
   // Make sure we don't crash when serializing principals with UNKNOWN_APP_ID.
   try {
     let binaryStream = Cc["@mozilla.org/binaryoutputstream;1"].
                        createInstance(Ci.nsIObjectOutputStream);
     let pipe = Cc["@mozilla.org/pipe;1"].createInstance(Ci.nsIPipe);
     pipe.init(false, false, 0, 0xffffffff, null);
     binaryStream.setOutputStream(pipe.outputStream);
     binaryStream.writeCompoundObject(simplePrin, Ci.nsISupports, true);
@@ -172,16 +181,17 @@ function run_test() {
   checkCrossOrigin(exampleOrg_app, exampleOrg);
   checkCrossOrigin(exampleOrg_app, nullPrin_app);
   checkCrossOrigin(exampleOrg_browser, exampleOrg_app);
   checkCrossOrigin(exampleOrg_browser, nullPrin_browser);
   checkCrossOrigin(exampleOrg_appBrowser, exampleOrg_app);
   checkCrossOrigin(exampleOrg_appBrowser, nullPrin_appBrowser);
   checkCrossOrigin(exampleOrg_appBrowser, exampleCom_appBrowser);
   checkCrossOrigin(exampleOrg_addon, exampleOrg);
+  checkCrossOrigin(exampleOrg_firstPartyDomain, exampleOrg);
   checkCrossOrigin(exampleOrg_userContext, exampleOrg);
   checkCrossOrigin(exampleOrg_userContextAddon, exampleOrg);
   checkCrossOrigin(exampleOrg_userContext, exampleOrg_userContextAddon);
   checkCrossOrigin(exampleOrg_userContext, exampleOrg_userContextApp);
   checkCrossOrigin(exampleOrg_signedPkg, exampleOrg);
   checkCrossOrigin(exampleOrg_signedPkg, exampleOrg_signedPkg_browser);
   checkCrossOrigin(exampleOrg_signedPkg, exampleOrg_signedPkg_another);
 
@@ -198,39 +208,40 @@ function run_test() {
   checkKind(ssm.getSystemPrincipal(), 'systemPrincipal');
 
   //
   // Test Origin Attribute Manipulation
   //
 
   // check that we can create an empty origin attributes dict with default
   // members and values.
-  emptyAttrs = ChromeUtils.fillNonDefaultOriginAttributes({});
+  var emptyAttrs = ChromeUtils.fillNonDefaultOriginAttributes({});
   checkValues(emptyAttrs);
 
   var uri = "http://example.org";
   var tests = [
     [ "", {} ],
     [ "^appId=5", {appId: 5} ],
     [ "^userContextId=3", {userContextId: 3} ],
     [ "^addonId=fooBar", {addonId: "fooBar"} ],
     [ "^inBrowser=1", {inIsolatedMozBrowser: true} ],
+    [ "^firstPartyDomain=example.org", {firstPartyDomain: "example.org"} ],
     [ "^signedPkg=bazQux", {signedPkg: "bazQux"} ],
     [ "^appId=3&inBrowser=1&userContextId=6",
       {appId: 3, userContextId: 6, inIsolatedMozBrowser: true} ] ];
 
   // check that we can create an origin attributes from an origin properly
-  tests.forEach(function(t) {
+  tests.forEach(t => {
     let attrs = ChromeUtils.createOriginAttributesFromOrigin(uri + t[0]);
     checkValues(attrs, t[1]);
     do_check_eq(ChromeUtils.originAttributesToSuffix(attrs), t[0]);
   });
 
   // check that we can create an origin attributes from a dict properly
-  tests.forEach(function(t) {
+  tests.forEach(t => {
     let attrs = ChromeUtils.fillNonDefaultOriginAttributes(t[1]);
     checkValues(attrs, t[1]);
     do_check_eq(ChromeUtils.originAttributesToSuffix(attrs), t[0]);
   });
 
   // each row in the set_tests array has these values:
   // [0] - the suffix used to create an origin attribute from
   // [1] - the expected result of creating an origin attribute from [0]
@@ -239,17 +250,17 @@ function run_test() {
   // [4] - the expected result of creating a suffix from [3]
   var set_tests = [
     [ "", {}, {appId: 5}, {appId: 5}, "^appId=5" ],
     [ "^appId=5", {appId: 5}, {appId: 3}, {appId: 3}, "^appId=3" ],
     [ "^appId=5", {appId: 5}, {userContextId: 3}, {appId: 5, userContextId: 3}, "^appId=5&userContextId=3" ],
     [ "^appId=5", {appId: 5}, {appId: 3, userContextId: 7}, {appId: 3, userContextId: 7}, "^appId=3&userContextId=7" ] ];
 
   // check that we can set origin attributes values properly
-  set_tests.forEach(function(t) {
+  set_tests.forEach(t => {
     let orig = ChromeUtils.createOriginAttributesFromOrigin(uri + t[0]);
     checkValues(orig, t[1]);
     let mod = orig;
     for (var key in t[2]) {
       mod[key] = t[2][key];
     }
     checkValues(mod, t[3]);
     do_check_eq(ChromeUtils.originAttributesToSuffix(mod), t[4]);
@@ -262,17 +273,39 @@ function run_test() {
   // [3] - the expected result of creating a suffix from [2]
   var dflt_tests = [
     [ "", {}, {}, "" ],
     [ "^userContextId=3", {userContextId: 3}, {}, "" ],
     [ "^appId=5", {appId: 5}, {appId: 5}, "^appId=5" ],
     [ "^appId=5&userContextId=3", {appId: 5, userContextId: 3}, {appId: 5}, "^appId=5" ] ];
 
   // check that we can set the userContextId to default properly
-  dflt_tests.forEach(function(t) {
+  dflt_tests.forEach(t => {
     let orig = ChromeUtils.createOriginAttributesFromOrigin(uri + t[0]);
     checkValues(orig, t[1]);
     let mod = orig;
     mod['userContextId'] = 0;
     checkValues(mod, t[2]);
     do_check_eq(ChromeUtils.originAttributesToSuffix(mod), t[3]);
   });
+
+  // each row in the dflt2_tests array has these values:
+  // [0] - the suffix used to create an origin attribute from
+  // [1] - the expected result of creating an origin attributes from [0]
+  // [2] - the expected result after setting firstPartyUri to the default
+  // [3] - the expected result of creating a suffix from [2]
+  var dflt2_tests = [
+    [ "", {}, {}, "" ],
+    [ "^firstPartyDomain=foo.com", {firstPartyDomain: "foo.com"}, {}, "" ],
+    [ "^appId=5", {appId: 5}, {appId: 5}, "^appId=5" ],
+    [ "^appId=5&firstPartyDomain=foo.com", {appId: 5, firstPartyDomain: "foo.com"}, {appId: 5}, "^appId=5" ] ];
+
+  // check that we can set the userContextId to default properly
+  dflt2_tests.forEach(t => {
+    let orig = ChromeUtils.createOriginAttributesFromOrigin(uri + t[0]);
+    checkValues(orig, t[1]);
+    let mod = orig;
+    mod['firstPartyDomain'] = "";
+    checkValues(mod, t[2]);
+    do_check_eq(ChromeUtils.originAttributesToSuffix(mod), t[3]);
+  });
+
 }
--- a/docshell/base/nsDocShell.cpp
+++ b/docshell/base/nsDocShell.cpp
@@ -10807,17 +10807,20 @@ nsDocShell::DoURILoad(nsIURI* aURI,
                    securityFlags) :
       new LoadInfo(loadingPrincipal, triggeringPrincipal, loadingNode,
                    securityFlags, aContentPolicyType);
 
   // We have to do this in case our OriginAttributes are different from the
   // OriginAttributes of the parent document. Or in case there isn't a
   // parent document.
   NeckoOriginAttributes neckoAttrs;
-  neckoAttrs.InheritFromDocShellToNecko(GetOriginAttributes());
+  bool isTopLevelDoc = aContentPolicyType == nsIContentPolicy::TYPE_DOCUMENT &&
+                       mItemType == typeContent &&
+                       !GetIsMozBrowserOrApp();
+  neckoAttrs.InheritFromDocShellToNecko(GetOriginAttributes(), isTopLevelDoc, aURI);
   rv = loadInfo->SetOriginAttributes(neckoAttrs);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     return rv;
   }
 
   if (!isSrcdoc) {
     rv = NS_NewChannelInternal(getter_AddRefs(channel),
                                aURI,
--- a/dom/base/nsFrameLoader.cpp
+++ b/dom/base/nsFrameLoader.cpp
@@ -2093,16 +2093,48 @@ nsFrameLoader::MaybeCreateDocShell()
     webNav->SetSessionHistory(sessionHistory);
   }
 
   DocShellOriginAttributes attrs;
   if (docShell->ItemType() == mDocShell->ItemType()) {
     attrs = nsDocShell::Cast(docShell)->GetOriginAttributes();
   }
 
+  // Inherit origin attributes from parent document if
+  // 1. It's in a content docshell.
+  // 2. its nodePrincipal is not a SystemPrincipal.
+  // 3. It's not a mozbrowser nor mozapp frame.
+  //
+  // For example, firstPartyDomain is computed from top-level document, it
+  // doesn't exist in the top-level docshell.
+  if (parentType == nsIDocShellTreeItem::typeContent &&
+      !nsContentUtils::IsSystemPrincipal(doc->NodePrincipal()) &&
+      !OwnerIsMozBrowserOrAppFrame()) {
+    PrincipalOriginAttributes poa = BasePrincipal::Cast(doc->NodePrincipal())->OriginAttributesRef();
+
+    // Assert on the firstPartyDomain from top-level docshell should be empty
+    if (mIsTopLevelContent) {
+      MOZ_ASSERT(attrs.mFirstPartyDomain.IsEmpty(),
+                 "top-level docshell shouldn't have firstPartyDomain attribute.");
+    }
+
+    // So far we want to make sure InheritFromDocToChildDocShell doesn't override
+    // any other origin attribute than firstPartyDomain.
+    MOZ_ASSERT(attrs.mAppId == poa.mAppId,
+              "docshell and document should have the same appId attribute.");
+    MOZ_ASSERT(attrs.mUserContextId == poa.mUserContextId,
+              "docshell and document should have the same userContextId attribute.");
+    MOZ_ASSERT(attrs.mInIsolatedMozBrowser == poa.mInIsolatedMozBrowser,
+              "docshell and document should have the same inIsolatedMozBrowser attribute.");
+    MOZ_ASSERT(attrs.mPrivateBrowsingId == poa.mPrivateBrowsingId,
+              "docshell and document should have the same privateBrowsingId attribute.");
+
+    attrs.InheritFromDocToChildDocShell(poa);
+  }
+
   if (OwnerIsAppFrame()) {
     // You can't be both an app and a browser frame.
     MOZ_ASSERT(!OwnerIsMozBrowserFrame());
 
     nsCOMPtr<mozIApplication> ownApp = GetOwnApp();
     MOZ_ASSERT(ownApp);
     uint32_t ownAppId = nsIScriptSecurityManager::NO_APP_ID;
     if (ownApp) {
--- a/dom/base/test/mochitest.ini
+++ b/dom/base/test/mochitest.ini
@@ -538,21 +538,17 @@ skip-if = buildapp == 'b2g'
 [test_bug693615.html]
 [test_bug693875.html]
 [test_bug694754.xhtml]
 [test_bug696301-1.html]
 [test_bug696301-2.html]
 [test_bug698381.html]
 [test_bug698384.html]
 [test_bug704063.html]
-[test_bug704320_http_http.html]
-[test_bug704320_http_https.html]
-[test_bug704320_https_http.html]
-skip-if = buildapp == 'b2g'  # b2g (https://example.com not working bug 1162353)
-[test_bug704320_https_https.html]
+[test_bug704320.html]
 skip-if = buildapp == 'b2g'  # b2g (https://example.com not working bug 1162353)
 [test_bug704320_policyset.html]
 [test_bug704320_policyset2.html]
 [test_bug704320_preload.html]
 [test_bug707142.html]
 [test_bug708620.html]
 [test_bug711047.html]
 [test_bug711180.html]
new file mode 100644
--- /dev/null
+++ b/dom/base/test/test_bug704320.html
@@ -0,0 +1,71 @@
+<!DOCTYPE HTML>
+<html>
+<!--
+https://bugzilla.mozilla.org/show_bug.cgi?id=704320
+-->
+<head>
+  <meta charset="utf-8">
+  <title>Test for Bug 704320</title>
+  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
+  <script type="application/javascript" src="referrerHelper.js"></script>
+  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
+
+<script type="application/javascript;version=1.7">
+
+//generates URLs to test
+var generateURLArray = (function(from, to){
+  const baseURL = '://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=';
+  const schemeTo = '&scheme-to=';
+
+  return [
+    from + baseURL + from + schemeTo + to + '&policy=no-referrer-when-downgrade',
+    from + baseURL + from + schemeTo + to + '&policy=no-referrer',
+    from + baseURL + from + schemeTo + to + '&policy=unsafe-url',
+    from + baseURL + from + schemeTo + to + '&policy=origin',
+    from + baseURL + from + schemeTo + to + '&policy=origin-when-cross-origin',
+  ];
+});
+
+var testIframeUrls = generateURLArray('http', 'http');
+testIframeUrls = testIframeUrls.concat(generateURLArray('https', 'https'));
+testIframeUrls = testIframeUrls.concat(generateURLArray('http', 'https'));
+testIframeUrls = testIframeUrls.concat(generateURLArray('https', 'http'));
+
+SimpleTest.waitForExplicitFinish();
+var advance = function() { tests.next(); };
+
+/**
+ * This is the main test routine -- serialized by use of a generator.
+ * It performs all tests in sequence using in the same iframe.
+ */
+var tests = (function() {
+  var iframe = document.getElementById("testframe");
+  iframe.onload = function() {
+     advance();
+  }
+
+  // load the test frame from testIframeUrls[url]
+  // it will call back into this function via postMessage when it finishes loading.
+  // and continue beyond the yield.
+  for(url in testIframeUrls) {
+    yield iframe.src = testIframeUrls[url];
+    // run test and check result for loaded test URL
+    yield checkExpectedGlobalResults();
+  }
+
+  // complete.  Be sure to yield so we don't call this twice.
+  yield SimpleTest.finish();
+})();
+
+</script>
+</head>
+
+<body onload="tests.next();">
+<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=704320">Mozilla Bug 704320 - HTTP/HTTPS to HTTPS/HTTP</a>
+<p id="display"></p>
+<pre id="content">
+</pre>
+  <iframe id="testframe"></iframe>
+
+</body>
+</html>
\ No newline at end of file
deleted file mode 100644
--- a/dom/base/test/test_bug704320_http_http.html
+++ /dev/null
@@ -1,62 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=704320
--->
-<head>
-  <meta charset="utf-8">
-  <title>Test for Bug 704320 - HTTP to HTTP</title>
-  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="referrerHelper.js"></script>
-  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-
-<script type="application/javascript;version=1.7">
-
-var testIframeUrls = [
-  // HTTP to HTTP
-  'http://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=http&scheme-to=http&policy=no-referrer-when-downgrade',
-  'http://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=http&scheme-to=http&policy=no-referrer',
-  'http://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=http&scheme-to=http&policy=unsafe-url',
-  'http://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=http&scheme-to=http&policy=origin',
-  'http://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=http&scheme-to=http&policy=origin-when-cross-origin',
-];
-
-SimpleTest.waitForExplicitFinish();
-var advance = function() { tests.next(); };
-
-/**
- * This is the main test routine -- serialized by use of a generator.
- * It performs all tests in sequence using in the same iframe.
- */
-var tests = (function() {
-  var iframe = document.getElementById("testframe");
-  iframe.onload = function() {
-     advance();
-  }
-
-  // load the test frame from testIframeUrls[url]
-  // it will call back into this function via postMessage when it finishes loading.
-  // and continue beyond the yield.
-  for(url in testIframeUrls) {
-    yield iframe.src = testIframeUrls[url];
-    // run test and check result for loaded test URL
-    yield checkExpectedGlobalResults();
-  }
-
-  // complete.  Be sure to yield so we don't call this twice.
-  yield SimpleTest.finish();
-})();
-
-</script>
-</head>
-
-<body onload="tests.next();">
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=704320">Mozilla Bug 704320 - HTTP to HTTP</a>
-<p id="display"></p>
-<pre id="content">
-</pre>
-  <iframe id="testframe"></iframe>
-
-</body>
-</html>
-
deleted file mode 100644
--- a/dom/base/test/test_bug704320_http_https.html
+++ /dev/null
@@ -1,62 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=704320
--->
-<head>
-  <meta charset="utf-8">
-  <title>Test for Bug 704320 - HTTP to HTTPS</title>
-  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="referrerHelper.js"></script>
-  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-
-<script type="application/javascript;version=1.7">
-
-var testIframeUrls = [
-  // HTTP to HTTPS
-  'http://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=http&scheme-to=https&policy=no-referrer-when-downgrade',
-  'http://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=http&scheme-to=https&policy=no-referrer',
-  'http://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=http&scheme-to=https&policy=unsafe-url',
-  'http://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=http&scheme-to=https&policy=origin',
-  'http://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=http&scheme-to=https&policy=origin-when-cross-origin',
-];
-
-SimpleTest.waitForExplicitFinish();
-var advance = function() { tests.next(); };
-
-/**
- * This is the main test routine -- serialized by use of a generator.
- * It performs all tests in sequence using in the same iframe.
- */
-var tests = (function() {
-  var iframe = document.getElementById("testframe");
-  iframe.onload = function() {
-     advance();
-  }
-
-  // load the test frame from testIframeUrls[url]
-  // it will call back into this function via postMessage when it finishes loading.
-  // and continue beyond the yield.
-  for(url in testIframeUrls) {
-    yield iframe.src = testIframeUrls[url];
-    // run test and check result for loaded test URL
-    yield checkExpectedGlobalResults();
-  }
-
-  // complete.  Be sure to yield so we don't call this twice.
-  yield SimpleTest.finish();
-})();
-
-</script>
-</head>
-
-<body onload="tests.next();">
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=704320">Mozilla Bug 704320 - HTTP to HTTPS</a>
-<p id="display"></p>
-<pre id="content">
-</pre>
-  <iframe id="testframe"></iframe>
-
-</body>
-</html>
-
deleted file mode 100644
--- a/dom/base/test/test_bug704320_https_http.html
+++ /dev/null
@@ -1,62 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=704320
--->
-<head>
-  <meta charset="utf-8">
-  <title>Test for Bug 704320 - HTTPS to HTTP</title>
-  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="referrerHelper.js"></script>
-  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-
-<script type="application/javascript;version=1.7">
-
-var testIframeUrls = [
-  // HTTPS to HTTP
-  'https://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=https&scheme-to=http&policy=no-referrer-when-downgrade',
-  'https://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=https&scheme-to=http&policy=no-referrer',
-  'https://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=https&scheme-to=http&policy=unsafe-url',
-  'https://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=https&scheme-to=http&policy=origin',
-  'https://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=https&scheme-to=http&policy=origin-when-cross-origin',
-];
-
-SimpleTest.waitForExplicitFinish();
-var advance = function() { tests.next(); };
-
-/**
- * This is the main test routine -- serialized by use of a generator.
- * It performs all tests in sequence using in the same iframe.
- */
-var tests = (function() {
-  var iframe = document.getElementById("testframe");
-  iframe.onload = function() {
-     advance();
-  }
-
-  // load the test frame from testIframeUrls[url]
-  // it will call back into this function via postMessage when it finishes loading.
-  // and continue beyond the yield.
-  for(url in testIframeUrls) {
-    yield iframe.src = testIframeUrls[url];
-    // run test and check result for loaded test URL
-    yield checkExpectedGlobalResults();
-  }
-
-  // complete.  Be sure to yield so we don't call this twice.
-  yield SimpleTest.finish();
-})();
-
-</script>
-</head>
-
-<body onload="tests.next();">
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=704320">Mozilla Bug 704320 - HTTPS to HTTP</a>
-<p id="display"></p>
-<pre id="content">
-</pre>
-  <iframe id="testframe"></iframe>
-
-</body>
-</html>
-
deleted file mode 100644
--- a/dom/base/test/test_bug704320_https_https.html
+++ /dev/null
@@ -1,62 +0,0 @@
-<!DOCTYPE HTML>
-<html>
-<!--
-https://bugzilla.mozilla.org/show_bug.cgi?id=704320
--->
-<head>
-  <meta charset="utf-8">
-  <title>Test for Bug 704320 - HTTPS to HTTPS</title>
-  <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
-  <script type="application/javascript" src="referrerHelper.js"></script>
-  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
-
-<script type="application/javascript;version=1.7">
-
-var testIframeUrls = [
-  // HTTPS to HTTPS
-  'https://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=https&scheme-to=https&policy=no-referrer-when-downgrade',
-  'https://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=https&scheme-to=https&policy=no-referrer',
-  'https://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=https&scheme-to=https&policy=unsafe-url',
-  'https://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=https&scheme-to=https&policy=origin',
-  'https://example.com/tests/dom/base/test/bug704320.sjs?action=create-1st-level-iframe&scheme-from=https&scheme-to=https&policy=origin-when-cross-origin'
-];
-
-SimpleTest.waitForExplicitFinish();
-var advance = function() { tests.next(); };
-
-/**
- * This is the main test routine -- serialized by use of a generator.
- * It performs all tests in sequence using in the same iframe.
- */
-var tests = (function() {
-  var iframe = document.getElementById("testframe");
-  iframe.onload = function() {
-     advance();
-  }
-
-  // load the test frame from testIframeUrls[url]
-  // it will call back into this function via postMessage when it finishes loading.
-  // and continue beyond the yield.
-  for(url in testIframeUrls) {
-    yield iframe.src = testIframeUrls[url];
-    // run test and check result for loaded test URL
-    yield checkExpectedGlobalResults();
-  }
-
-  // complete.  Be sure to yield so we don't call this twice.
-  yield SimpleTest.finish();
-})();
-
-</script>
-</head>
-
-<body onload="tests.next();">
-<a target="_blank" href="https://bugzilla.mozilla.org/show_bug.cgi?id=704320">Mozilla Bug 704320 - HTTPS to HTTPS</a>
-<p id="display"></p>
-<pre id="content">
-</pre>
-  <iframe id="testframe"></iframe>
-
-</body>
-</html>
-
--- a/dom/indexedDB/ActorsParent.cpp
+++ b/dom/indexedDB/ActorsParent.cpp
@@ -6217,17 +6217,17 @@ private:
   RefPtr<Factory> mFactory;
   RefPtr<FullDatabaseMetadata> mMetadata;
   RefPtr<FileManager> mFileManager;
   RefPtr<DirectoryLock> mDirectoryLock;
   nsTHashtable<nsPtrHashKey<TransactionBase>> mTransactions;
   nsTHashtable<nsPtrHashKey<MutableFile>> mMutableFiles;
   RefPtr<DatabaseConnection> mConnection;
   const PrincipalInfo mPrincipalInfo;
-  const OptionalContentId mOptionalContentParentId;
+  const Maybe<ContentParentId> mOptionalContentParentId;
   const nsCString mGroup;
   const nsCString mOrigin;
   const nsCString mId;
   const nsString mFilePath;
   uint32_t mActiveMutableFileCount;
   const uint32_t mTelemetryId;
   const PersistenceType mPersistenceType;
   const bool mFileHandleDisabled;
@@ -6237,17 +6237,17 @@ private:
   bool mActorWasAlive;
   bool mActorDestroyed;
   bool mMetadataCleanedUp;
 
 public:
   // Created by OpenDatabaseOp.
   Database(Factory* aFactory,
            const PrincipalInfo& aPrincipalInfo,
-           const OptionalContentId& aOptionalContentParentId,
+           const Maybe<ContentParentId>& aOptionalContentParentId,
            const nsACString& aGroup,
            const nsACString& aOrigin,
            uint32_t aTelemetryId,
            FullDatabaseMetadata* aMetadata,
            FileManager* aFileManager,
            already_AddRefed<DirectoryLock> aDirectoryLock,
            bool aFileHandleDisabled,
            bool aChromeWriteAccessAllowed);
@@ -6276,21 +6276,19 @@ public:
   GetPrincipalInfo() const
   {
     return mPrincipalInfo;
   }
 
   bool
   IsOwnedByProcess(ContentParentId aContentParentId) const
   {
-    MOZ_ASSERT(mOptionalContentParentId.type() != OptionalContentId::T__None);
-
     return
-      mOptionalContentParentId.type() == OptionalContentId::TContentParentId &&
-      mOptionalContentParentId.get_ContentParentId() == aContentParentId;
+      mOptionalContentParentId &&
+      mOptionalContentParentId.value() == aContentParentId;
   }
 
   const nsCString&
   Group() const
   {
     return mGroup;
   }
 
@@ -7446,17 +7444,17 @@ struct FactoryOp::MaybeBlockedDatabaseIn
 class OpenDatabaseOp final
   : public FactoryOp
 {
   friend class Database;
   friend class VersionChangeTransaction;
 
   class VersionChangeOp;
 
-  OptionalContentId mOptionalContentParentId;
+  Maybe<ContentParentId> mOptionalContentParentId;
 
   RefPtr<FullDatabaseMetadata> mMetadata;
 
   uint64_t mRequestedVersion;
   RefPtr<FileManager> mFileManager;
 
   RefPtr<Database> mDatabase;
   RefPtr<VersionChangeTransaction> mVersionChangeTransaction;
@@ -7471,20 +7469,17 @@ class OpenDatabaseOp final
 public:
   OpenDatabaseOp(Factory* aFactory,
                  already_AddRefed<ContentParent> aContentParent,
                  const CommonFactoryRequestParams& aParams);
 
   bool
   IsOtherProcessActor() const
   {
-    MOZ_ASSERT(mOptionalContentParentId.type() != OptionalContentId::T__None);
-
-    return mOptionalContentParentId.type() ==
-             OptionalContentId::TContentParentId;
+    return mOptionalContentParentId.isSome();
   }
 
 private:
   ~OpenDatabaseOp()
   {
     MOZ_ASSERT(!mVersionChangeOp);
   }
 
@@ -13531,17 +13526,17 @@ WaitForTransactionsHelper::Run()
 }
 
 /*******************************************************************************
  * Database
  ******************************************************************************/
 
 Database::Database(Factory* aFactory,
                    const PrincipalInfo& aPrincipalInfo,
-                   const OptionalContentId& aOptionalContentParentId,
+                   const Maybe<ContentParentId>& aOptionalContentParentId,
                    const nsACString& aGroup,
                    const nsACString& aOrigin,
                    uint32_t aTelemetryId,
                    FullDatabaseMetadata* aMetadata,
                    FileManager* aFileManager,
                    already_AddRefed<DirectoryLock> aDirectoryLock,
                    bool aFileHandleDisabled,
                    bool aChromeWriteAccessAllowed)
@@ -20756,19 +20751,17 @@ OpenDatabaseOp::OpenDatabaseOp(Factory* 
   , mMetadata(new FullDatabaseMetadata(aParams.metadata()))
   , mRequestedVersion(aParams.metadata().version())
   , mVersionChangeOp(nullptr)
   , mTelemetryId(0)
 {
   if (mContentParent) {
     // This is a little scary but it looks safe to call this off the main thread
     // for now.
-    mOptionalContentParentId = mContentParent->ChildID();
-  } else {
-    mOptionalContentParentId = void_t();
+    mOptionalContentParentId = Some(mContentParent->ChildID());
   }
 }
 
 void
 OpenDatabaseOp::ActorDestroy(ActorDestroyReason aWhy)
 {
   AssertIsOnOwningThread();
 
--- a/dom/ipc/ContentParent.cpp
+++ b/dom/ipc/ContentParent.cpp
@@ -3638,17 +3638,17 @@ ContentParent::DeallocPPresentationParen
   RefPtr<PresentationParent> actor =
   dont_AddRef(static_cast<PresentationParent*>(aActor));
   return true;
 }
 
 bool
 ContentParent::RecvPPresentationConstructor(PPresentationParent* aActor)
 {
-  return static_cast<PresentationParent*>(aActor)->Init();
+  return static_cast<PresentationParent*>(aActor)->Init(mChildID);
 }
 
 PFlyWebPublishedServerParent*
 ContentParent::AllocPFlyWebPublishedServerParent(const nsString& name,
                                                  const FlyWebPublishOptions& params)
 {
   RefPtr<FlyWebPublishedServerParent> actor =
     new FlyWebPublishedServerParent(name, params);
--- a/dom/ipc/PContent.ipdl
+++ b/dom/ipc/PContent.ipdl
@@ -319,22 +319,16 @@ union MaybeFileDesc {
     void_t;
 };
 
 union FileDescOrError {
     FileDescriptor;
     nsresult;
 };
 
-union OptionalContentId
-{
-  ContentParentId;
-  void_t;
-};
-
 struct DomainPolicyClone
 {
     bool        active;
     URIParams[] blacklist;
     URIParams[] whitelist;
     URIParams[] superBlacklist;
     URIParams[] superWhitelist;
 };
--- a/dom/ipc/TabChild.cpp
+++ b/dom/ipc/TabChild.cpp
@@ -504,17 +504,17 @@ TabChild::Create(nsIContentChild* aManag
         RefPtr<TabChild> child = sPreallocatedTab.get();
         sPreallocatedTab = nullptr;
 
         MOZ_ASSERT(!child->mTriedBrowserInit);
 
         child->mManager = aManager;
         child->SetTabId(aTabId);
         child->SetTabContext(aContext);
-        child->NotifyTabContextUpdated();
+        child->NotifyTabContextUpdated(true);
         return child.forget();
     }
 
     RefPtr<TabChild> iframe = new TabChild(aManager, aTabId,
                                              aContext, aChromeFlags);
     return NS_SUCCEEDED(iframe->Init()) ? iframe.forget() : nullptr;
 }
 
@@ -722,16 +722,17 @@ TabChild::Init()
 {
   nsCOMPtr<nsIWebBrowser> webBrowser = do_CreateInstance(NS_WEBBROWSER_CONTRACTID);
   if (!webBrowser) {
     NS_ERROR("Couldn't create a nsWebBrowser?");
     return NS_ERROR_FAILURE;
   }
 
   webBrowser->SetContainerWindow(this);
+  webBrowser->SetOriginAttributes(OriginAttributesRef());
   mWebNav = do_QueryInterface(webBrowser);
   NS_ASSERTION(mWebNav, "nsWebBrowser doesn't implement nsIWebNavigation?");
 
   nsCOMPtr<nsIDocShellTreeItem> docShellItem(do_QueryInterface(WebNavigation()));
   docShellItem->SetItemType(nsIDocShellTreeItem::typeContentWrapper);
 
   nsCOMPtr<nsIBaseWindow> baseWindow = do_QueryInterface(WebNavigation());
   if (!baseWindow) {
@@ -750,17 +751,17 @@ TabChild::Init()
     LayoutDeviceIntRect(0, 0, 0, 0),
     nullptr                  // HandleWidgetEvent
   );
 
   baseWindow->InitWindow(0, mPuppetWidget, 0, 0, 0, 0);
   baseWindow->Create();
 
   // Set the tab context attributes then pass to docShell
-  NotifyTabContextUpdated();
+  NotifyTabContextUpdated(false);
 
   // IPC uses a WebBrowser object for which DNS prefetching is turned off
   // by default. But here we really want it, so enable it explicitly
   nsCOMPtr<nsIWebBrowserSetup> webBrowserSetup =
     do_QueryInterface(baseWindow);
   if (webBrowserSetup) {
     webBrowserSetup->SetProperty(nsIWebBrowserSetup::SETUP_ALLOW_DNS_PREFETCH,
                                  true);
@@ -820,27 +821,30 @@ TabChild::Init()
         }
       });
   mAPZEventState = new APZEventState(mPuppetWidget, Move(callback));
 
   return NS_OK;
 }
 
 void
-TabChild::NotifyTabContextUpdated()
+TabChild::NotifyTabContextUpdated(bool aIsPreallocated)
 {
   nsCOMPtr<nsIDocShell> docShell = do_GetInterface(WebNavigation());
   MOZ_ASSERT(docShell);
 
   if (!docShell) {
     return;
   }
 
   UpdateFrameType();
-  nsDocShell::Cast(docShell)->SetOriginAttributes(OriginAttributesRef());
+
+  if (aIsPreallocated)  {
+    nsDocShell::Cast(docShell)->SetOriginAttributes(OriginAttributesRef());
+  }
 
   // Set SANDBOXED_AUXILIARY_NAVIGATION flag if this is a receiver page.
   if (!PresentationURL().IsEmpty()) {
     docShell->SetSandboxFlags(SANDBOXED_AUXILIARY_NAVIGATION);
   }
 }
 
 void
--- a/dom/ipc/TabChild.h
+++ b/dom/ipc/TabChild.h
@@ -682,22 +682,23 @@ protected:
 #ifdef MOZ_WIDGET_GONK
   void MaybeRequestPreinitCamera();
 #endif
 
 private:
   void HandleDoubleTap(const CSSPoint& aPoint, const Modifiers& aModifiers,
                        const ScrollableLayerGuid& aGuid);
 
-  // Notify others that our TabContext has been updated.  (At the moment, this
-  // sets the appropriate origin attributes on our docshell.)
+  // Notify others that our TabContext has been updated.
   //
   // You should call this after calling TabContext::SetTabContext().  We also
   // call this during Init().
-  void NotifyTabContextUpdated();
+  //
+  // @param aIsPreallocated  true if this is called for Preallocated Tab.
+  void NotifyTabContextUpdated(bool aIsPreallocated);
 
   // Update the frameType on our docshell.
   void UpdateFrameType();
 
   void ActorDestroy(ActorDestroyReason why) override;
 
   enum FrameScriptLoading { DONT_LOAD_SCRIPTS, DEFAULT_LOAD_SCRIPTS };
 
--- a/dom/media/MediaDecoderStateMachine.cpp
+++ b/dom/media/MediaDecoderStateMachine.cpp
@@ -867,18 +867,18 @@ nsresult MediaDecoderStateMachine::Init(
     OwnerThread(), __func__, this,
     &MediaDecoderStateMachine::OnCDMProxyReady,
     &MediaDecoderStateMachine::OnCDMProxyNotReady));
 #endif
 
   nsresult rv = mReader->Init();
   NS_ENSURE_SUCCESS(rv, rv);
 
-  OwnerThread()->Dispatch(NewRunnableMethod<State>(
-    this, &MediaDecoderStateMachine::EnterState, mState.Ref()));
+  OwnerThread()->Dispatch(
+    NewRunnableMethod(this, &MediaDecoderStateMachine::EnterState));
 
   return NS_OK;
 }
 
 void
 MediaDecoderStateMachine::SetMediaDecoderReaderWrapperCallback()
 {
   MOZ_ASSERT(OnTaskQueue());
@@ -1058,39 +1058,39 @@ MediaDecoderStateMachine::SetState(State
 {
   MOZ_ASSERT(OnTaskQueue());
   if (mState == aState) {
     return;
   }
 
   DECODER_LOG("MDSM state: %s -> %s", ToStateStr(), ToStateStr(aState));
 
-  ExitState(mState);
+  ExitState();
   mState = aState;
-  EnterState(mState);
+  EnterState();
 }
 
 void
-MediaDecoderStateMachine::ExitState(State aState)
+MediaDecoderStateMachine::ExitState()
 {
   MOZ_ASSERT(OnTaskQueue());
-  switch (aState) {
+  switch (mState) {
     case DECODER_STATE_COMPLETED:
       mSentPlaybackEndedEvent = false;
       break;
     default:
       break;
   }
 }
 
 void
-MediaDecoderStateMachine::EnterState(State aState)
+MediaDecoderStateMachine::EnterState()
 {
   MOZ_ASSERT(OnTaskQueue());
-  switch (aState) {
+  switch (mState) {
     case DECODER_STATE_DECODING_METADATA:
       ReadMetadata();
       break;
     case DECODER_STATE_DORMANT:
       DiscardSeekTaskIfExist();
       if (IsPlaying()) {
         StopPlayback();
       }
@@ -2270,135 +2270,140 @@ MediaDecoderStateMachine::FinishShutdown
 void
 MediaDecoderStateMachine::RunStateMachine()
 {
   MOZ_ASSERT(OnTaskQueue());
 
   mDelayedScheduler.Reset(); // Must happen on state machine task queue.
   mDispatchedStateMachine = false;
 
-  MediaResource* resource = mResource;
-  NS_ENSURE_TRUE_VOID(resource);
-
   switch (mState) {
-    case DECODER_STATE_SHUTDOWN:
-    case DECODER_STATE_DORMANT:
-    case DECODER_STATE_WAIT_FOR_CDM:
-    case DECODER_STATE_DECODING_METADATA:
-    case DECODER_STATE_DECODING_FIRSTFRAME:
+    case DECODER_STATE_DECODING:
+      StepDecoding();
+      return;
+    case DECODER_STATE_BUFFERING:
+      StepBuffering();
+      return;
+    case DECODER_STATE_COMPLETED:
+      StepCompleted();
+      return;
+    default:
       return;
-
-    case DECODER_STATE_DECODING: {
-      if (mPlayState != MediaDecoder::PLAY_STATE_PLAYING && IsPlaying())
-      {
-        // We're playing, but the element/decoder is in paused state. Stop
-        // playing!
-        StopPlayback();
-      }
-
-      // Start playback if necessary so that the clock can be properly queried.
-      MaybeStartPlayback();
-
-      UpdatePlaybackPositionPeriodically();
-      NS_ASSERTION(!IsPlaying() ||
-                   IsStateMachineScheduled(),
-                   "Must have timer scheduled");
-      MaybeStartBuffering();
+  }
+}
+
+void
+MediaDecoderStateMachine::StepDecoding()
+{
+  MOZ_ASSERT(OnTaskQueue());
+
+  if (mPlayState != MediaDecoder::PLAY_STATE_PLAYING && IsPlaying()) {
+    // We're playing, but the element/decoder is in paused state. Stop
+    // playing!
+    StopPlayback();
+  }
+
+  // Start playback if necessary so that the clock can be properly queried.
+  MaybeStartPlayback();
+
+  UpdatePlaybackPositionPeriodically();
+
+  NS_ASSERTION(!IsPlaying() ||
+               IsStateMachineScheduled(),
+               "Must have timer scheduled");
+
+  MaybeStartBuffering();
+}
+
+void
+MediaDecoderStateMachine::StepBuffering()
+{
+  MOZ_ASSERT(OnTaskQueue());
+
+  TimeStamp now = TimeStamp::Now();
+  NS_ASSERTION(!mBufferingStart.IsNull(), "Must know buffering start time.");
+
+  // With buffering heuristics we will remain in the buffering state if
+  // we've not decoded enough data to begin playback, or if we've not
+  // downloaded a reasonable amount of data inside our buffering time.
+  if (mReader->UseBufferingHeuristics()) {
+    TimeDuration elapsed = now - mBufferingStart;
+    bool isLiveStream = mResource->IsLiveStream();
+    if ((isLiveStream || !CanPlayThrough()) &&
+        elapsed < TimeDuration::FromSeconds(mBufferingWait * mPlaybackRate) &&
+        (mQuickBuffering ? HasLowDecodedData(mQuickBufferingLowDataThresholdUsecs)
+                         : HasLowUndecodedData(mBufferingWait * USECS_PER_S)) &&
+        mResource->IsExpectingMoreData()) {
+      DECODER_LOG("Buffering: wait %ds, timeout in %.3lfs %s",
+                  mBufferingWait, mBufferingWait - elapsed.ToSeconds(),
+                  (mQuickBuffering ? "(quick exit)" : ""));
+      ScheduleStateMachineIn(USECS_PER_S);
       return;
     }
-
-    case DECODER_STATE_BUFFERING: {
-      TimeStamp now = TimeStamp::Now();
-      NS_ASSERTION(!mBufferingStart.IsNull(), "Must know buffering start time.");
-
-      // With buffering heuristics we will remain in the buffering state if
-      // we've not decoded enough data to begin playback, or if we've not
-      // downloaded a reasonable amount of data inside our buffering time.
-      if (mReader->UseBufferingHeuristics()) {
-        TimeDuration elapsed = now - mBufferingStart;
-        bool isLiveStream = resource->IsLiveStream();
-        if ((isLiveStream || !CanPlayThrough()) &&
-              elapsed < TimeDuration::FromSeconds(mBufferingWait * mPlaybackRate) &&
-              (mQuickBuffering ? HasLowDecodedData(mQuickBufferingLowDataThresholdUsecs)
-                               : HasLowUndecodedData(mBufferingWait * USECS_PER_S)) &&
-              mResource->IsExpectingMoreData())
-        {
-          DECODER_LOG("Buffering: wait %ds, timeout in %.3lfs %s",
-                      mBufferingWait, mBufferingWait - elapsed.ToSeconds(),
-                      (mQuickBuffering ? "(quick exit)" : ""));
-          ScheduleStateMachineIn(USECS_PER_S);
-          return;
-        }
-      } else if (OutOfDecodedAudio() || OutOfDecodedVideo()) {
-        MOZ_ASSERT(mReader->IsWaitForDataSupported(),
-                   "Don't yet have a strategy for non-heuristic + non-WaitForData");
-        DispatchDecodeTasksIfNeeded();
-        MOZ_ASSERT_IF(!mMinimizePreroll && OutOfDecodedAudio(), mReader->IsRequestingAudioData() || mReader->IsWaitingAudioData());
-        MOZ_ASSERT_IF(!mMinimizePreroll && OutOfDecodedVideo(), mReader->IsRequestingVideoData() || mReader->IsWaitingVideoData());
-        DECODER_LOG("In buffering mode, waiting to be notified: outOfAudio: %d, "
-                    "mAudioStatus: %s, outOfVideo: %d, mVideoStatus: %s",
-                    OutOfDecodedAudio(), AudioRequestStatus(),
-                    OutOfDecodedVideo(), VideoRequestStatus());
-        return;
-      }
-
-      DECODER_LOG("Changed state from BUFFERING to DECODING");
-      DECODER_LOG("Buffered for %.3lfs", (now - mBufferingStart).ToSeconds());
-      SetState(DECODER_STATE_DECODING);
-
-      NS_ASSERTION(IsStateMachineScheduled(), "Must have timer scheduled");
-      return;
-    }
-
-    case DECODER_STATE_SEEKING: {
-      return;
-    }
-
-    case DECODER_STATE_COMPLETED: {
-      if (mPlayState != MediaDecoder::PLAY_STATE_PLAYING && IsPlaying()) {
-        StopPlayback();
-      }
-      // Play the remaining media. We want to run AdvanceFrame() at least
-      // once to ensure the current playback position is advanced to the
-      // end of the media, and so that we update the readyState.
-      if ((HasVideo() && !mVideoCompleted) ||
-          (HasAudio() && !mAudioCompleted)) {
-        // Start playback if necessary to play the remaining media.
-        MaybeStartPlayback();
-        UpdatePlaybackPositionPeriodically();
-        NS_ASSERTION(!IsPlaying() ||
-                     IsStateMachineScheduled(),
-                     "Must have timer scheduled");
-        return;
-      }
-
-      // StopPlayback in order to reset the IsPlaying() state so audio
-      // is restarted correctly.
-      StopPlayback();
-
-      if (mPlayState == MediaDecoder::PLAY_STATE_PLAYING &&
-          !mSentPlaybackEndedEvent)
-      {
-        int64_t clockTime = std::max(AudioEndTime(), VideoEndTime());
-        clockTime = std::max(int64_t(0), std::max(clockTime, Duration().ToMicroseconds()));
-        UpdatePlaybackPosition(clockTime);
-
-        // Ensure readyState is updated before firing the 'ended' event.
-        UpdateNextFrameStatus();
-
-        mOnPlaybackEvent.Notify(MediaEventType::PlaybackEnded);
-
-        mSentPlaybackEndedEvent = true;
-
-        // MediaSink::GetEndTime() must be called before stopping playback.
-        StopMediaSink();
-      }
-
-      return;
-    }
+  } else if (OutOfDecodedAudio() || OutOfDecodedVideo()) {
+    MOZ_ASSERT(mReader->IsWaitForDataSupported(),
+               "Don't yet have a strategy for non-heuristic + non-WaitForData");
+    DispatchDecodeTasksIfNeeded();
+    MOZ_ASSERT_IF(!mMinimizePreroll && OutOfDecodedAudio(), mReader->IsRequestingAudioData() || mReader->IsWaitingAudioData());
+    MOZ_ASSERT_IF(!mMinimizePreroll && OutOfDecodedVideo(), mReader->IsRequestingVideoData() || mReader->IsWaitingVideoData());
+    DECODER_LOG("In buffering mode, waiting to be notified: outOfAudio: %d, "
+                "mAudioStatus: %s, outOfVideo: %d, mVideoStatus: %s",
+                OutOfDecodedAudio(), AudioRequestStatus(),
+                OutOfDecodedVideo(), VideoRequestStatus());
+    return;
+  }
+
+  DECODER_LOG("Changed state from BUFFERING to DECODING");
+  DECODER_LOG("Buffered for %.3lfs", (now - mBufferingStart).ToSeconds());
+  SetState(DECODER_STATE_DECODING);
+  NS_ASSERTION(IsStateMachineScheduled(), "Must have timer scheduled");
+}
+
+void
+MediaDecoderStateMachine::StepCompleted()
+{
+  MOZ_ASSERT(OnTaskQueue());
+
+  if (mPlayState != MediaDecoder::PLAY_STATE_PLAYING && IsPlaying()) {
+    StopPlayback();
+  }
+
+  // Play the remaining media. We want to run AdvanceFrame() at least
+  // once to ensure the current playback position is advanced to the
+  // end of the media, and so that we update the readyState.
+  if ((HasVideo() && !mVideoCompleted) ||
+      (HasAudio() && !mAudioCompleted)) {
+    // Start playback if necessary to play the remaining media.
+    MaybeStartPlayback();
+    UpdatePlaybackPositionPeriodically();
+    NS_ASSERTION(!IsPlaying() ||
+                 IsStateMachineScheduled(),
+                 "Must have timer scheduled");
+    return;
+  }
+
+  // StopPlayback in order to reset the IsPlaying() state so audio
+  // is restarted correctly.
+  StopPlayback();
+
+  if (mPlayState == MediaDecoder::PLAY_STATE_PLAYING &&
+      !mSentPlaybackEndedEvent) {
+    int64_t clockTime = std::max(AudioEndTime(), VideoEndTime());
+    clockTime = std::max(int64_t(0), std::max(clockTime, Duration().ToMicroseconds()));
+    UpdatePlaybackPosition(clockTime);
+
+    // Ensure readyState is updated before firing the 'ended' event.
+    UpdateNextFrameStatus();
+
+    mOnPlaybackEvent.Notify(MediaEventType::PlaybackEnded);
+
+    mSentPlaybackEndedEvent = true;
+
+    // MediaSink::GetEndTime() must be called before stopping playback.
+    StopMediaSink();
   }
 }
 
 void
 MediaDecoderStateMachine::Reset(TrackSet aTracks)
 {
   MOZ_ASSERT(OnTaskQueue());
   DECODER_LOG("MediaDecoderStateMachine::Reset");
--- a/dom/media/MediaDecoderStateMachine.h
+++ b/dom/media/MediaDecoderStateMachine.h
@@ -351,18 +351,18 @@ private:
   // and aborting all pending operations on the decode task queue.
   void Reset(TrackSet aTracks = TrackSet(TrackInfo::kAudioTrack,
                                          TrackInfo::kVideoTrack));
 
 protected:
   virtual ~MediaDecoderStateMachine();
 
   void SetState(State aState);
-  void ExitState(State aState);
-  void EnterState(State aState);
+  void ExitState();
+  void EnterState();
 
   void BufferedRangeUpdated();
 
   void ReaderSuspendedChanged();
 
   // Inserts MediaData* samples into their respective MediaQueues.
   // aSample must not be null.
 
@@ -551,16 +551,22 @@ protected:
   // Completes the seek operation, moves onto the next appropriate state.
   void SeekCompleted();
 
   // Queries our state to see whether the decode has finished for all streams.
   bool CheckIfDecodeComplete();
 
   // Performs one "cycle" of the state machine.
   void RunStateMachine();
+  // Perform one cycle of the DECODING state.
+  void StepDecoding();
+  // Perform one cycle of the BUFFERING state.
+  void StepBuffering();
+  // Perform one cycle of the COMPLETED state.
+  void StepCompleted();
 
   bool IsStateMachineScheduled() const;
 
   // These return true if the respective stream's decode has not yet reached
   // the end of stream.
   bool IsAudioDecoding();
   bool IsVideoDecoding();
 
--- a/dom/presentation/PresentationDeviceManager.cpp
+++ b/dom/presentation/PresentationDeviceManager.cpp
@@ -183,17 +183,17 @@ PresentationDeviceManager::GetAvailableD
   for (uint32_t i = 0; i < mDevices.Length(); ++i) {
     if (presentationUrls.IsEmpty()) {
       devices->AppendElement(mDevices[i], false);
       continue;
     }
 
     for (uint32_t j = 0; j < presentationUrls.Length(); ++j) {
       bool isSupported;
-      if (NS_SUCCEEDED(mDevices[i]->IsRequestedUrlSupported(presentationUrls[i],
+      if (NS_SUCCEEDED(mDevices[i]->IsRequestedUrlSupported(presentationUrls[j],
                                                             &isSupported)) &&
           isSupported) {
         devices->AppendElement(mDevices[i], false);
         break;
       }
     }
   }
 
--- a/dom/presentation/PresentationRequest.cpp
+++ b/dom/presentation/PresentationRequest.cpp
@@ -194,19 +194,25 @@ PresentationRequest::StartWithDevice(con
 
   nsCOMPtr<nsIPresentationService> service =
     do_GetService(PRESENTATION_SERVICE_CONTRACTID);
   if(NS_WARN_IF(!service)) {
     promise->MaybeReject(NS_ERROR_DOM_OPERATION_ERR);
     return promise.forget();
   }
 
+  // Get xul:browser element in parent process or nsWindowRoot object in child
+  // process. If it's in child process, the corresponding xul:browser element
+  // will be obtained at PresentationRequestParent::DoRequest in its parent
+  // process.
+  nsCOMPtr<nsIDOMEventTarget> handler =
+    do_QueryInterface(GetOwner()->GetChromeEventHandler());
   nsCOMPtr<nsIPresentationServiceCallback> callback =
     new PresentationRequesterCallback(this, id, promise);
-  rv = service->StartSession(mUrls, id, origin, aDeviceId, GetOwner()->WindowID(), callback);
+  rv = service->StartSession(mUrls, id, origin, aDeviceId, GetOwner()->WindowID(), handler, callback);
   if (NS_WARN_IF(NS_FAILED(rv))) {
     promise->MaybeReject(NS_ERROR_DOM_OPERATION_ERR);
   }
 
   return promise.forget();
 }
 
 already_AddRefed<Promise>
--- a/dom/presentation/PresentationService.cpp
+++ b/dom/presentation/PresentationService.cpp
@@ -106,47 +106,51 @@ class PresentationDeviceRequest final : 
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIPRESENTATIONDEVICEREQUEST
 
   PresentationDeviceRequest(const nsTArray<nsString>& aUrls,
                             const nsAString& aId,
                             const nsAString& aOrigin,
                             uint64_t aWindowId,
+                            nsIDOMEventTarget* aEventTarget,
                             nsIPresentationServiceCallback* aCallback);
 
 private:
   virtual ~PresentationDeviceRequest() = default;
   nsresult CreateSessionInfo(nsIPresentationDevice* aDevice,
                              const nsAString& aSelectedRequestUrl);
 
   nsTArray<nsString> mRequestUrls;
   nsString mId;
   nsString mOrigin;
   uint64_t mWindowId;
+  nsWeakPtr mChromeEventHandler;
   nsCOMPtr<nsIPresentationServiceCallback> mCallback;
 };
 
 LazyLogModule gPresentationLog("Presentation");
 
 } // namespace dom
 } // namespace mozilla
 
 NS_IMPL_ISUPPORTS(PresentationDeviceRequest, nsIPresentationDeviceRequest)
 
 PresentationDeviceRequest::PresentationDeviceRequest(
                                       const nsTArray<nsString>& aUrls,
                                       const nsAString& aId,
                                       const nsAString& aOrigin,
                                       uint64_t aWindowId,
+                                      nsIDOMEventTarget* aEventTarget,
                                       nsIPresentationServiceCallback* aCallback)
   : mRequestUrls(aUrls)
   , mId(aId)
   , mOrigin(aOrigin)
   , mWindowId(aWindowId)
+  , mChromeEventHandler(do_GetWeakReference(aEventTarget))
   , mCallback(aCallback)
 {
   MOZ_ASSERT(!mRequestUrls.IsEmpty());
   MOZ_ASSERT(!mId.IsEmpty());
   MOZ_ASSERT(!mOrigin.IsEmpty());
   MOZ_ASSERT(mCallback);
 }
 
@@ -159,16 +163,24 @@ PresentationDeviceRequest::GetOrigin(nsA
 
 NS_IMETHODIMP
 PresentationDeviceRequest::GetRequestURLs(nsIArray** aUrls)
 {
   return ConvertURLArrayHelper(mRequestUrls, aUrls);
 }
 
 NS_IMETHODIMP
+PresentationDeviceRequest::GetChromeEventHandler(nsIDOMEventTarget** aChromeEventHandler)
+{
+  nsCOMPtr<nsIDOMEventTarget> handler(do_QueryReferent(mChromeEventHandler));
+  handler.forget(aChromeEventHandler);
+  return NS_OK;
+}
+
+NS_IMETHODIMP
 PresentationDeviceRequest::Select(nsIPresentationDevice* aDevice)
 {
   MOZ_ASSERT(NS_IsMainThread());
   if (NS_WARN_IF(!aDevice)) {
     MOZ_ASSERT(false, "|aDevice| should noe be null.");
     mCallback->NotifyError(NS_ERROR_DOM_OPERATION_ERR);
     return NS_ERROR_INVALID_ARG;
   }
@@ -629,30 +641,32 @@ PresentationService::IsAppInstalled(nsIU
 }
 
 NS_IMETHODIMP
 PresentationService::StartSession(const nsTArray<nsString>& aUrls,
                                   const nsAString& aSessionId,
                                   const nsAString& aOrigin,
                                   const nsAString& aDeviceId,
                                   uint64_t aWindowId,
+                                  nsIDOMEventTarget* aEventTarget,
                                   nsIPresentationServiceCallback* aCallback)
 {
   PRES_DEBUG("%s:id[%s]\n", __func__, NS_ConvertUTF16toUTF8(aSessionId).get());
 
   MOZ_ASSERT(NS_IsMainThread());
   MOZ_ASSERT(aCallback);
   MOZ_ASSERT(!aSessionId.IsEmpty());
   MOZ_ASSERT(!aUrls.IsEmpty());
 
   nsCOMPtr<nsIPresentationDeviceRequest> request =
     new PresentationDeviceRequest(aUrls,
                                   aSessionId,
                                   aOrigin,
                                   aWindowId,
+                                  aEventTarget,
                                   aCallback);
 
   if (aDeviceId.IsVoid()) {
     // Pop up a prompt and ask user to select a device.
     nsCOMPtr<nsIPresentationDevicePrompt> prompt =
       do_GetService(PRESENTATION_DEVICE_PROMPT_CONTRACTID);
     if (NS_WARN_IF(!prompt)) {
       return aCallback->NotifyError(NS_ERROR_DOM_OPERATION_ERR);
--- a/dom/presentation/interfaces/nsIPresentationDevicePrompt.idl
+++ b/dom/presentation/interfaces/nsIPresentationDevicePrompt.idl
@@ -1,15 +1,16 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsISupports.idl"
 
 interface nsIArray;
+interface nsIDOMEventTarget;
 interface nsIPresentationDevice;
 
 %{C++
 #define PRESENTATION_DEVICE_PROMPT_CONTRACTID "@mozilla.org/presentation-device/prompt;1"
 %}
 
 /*
  * The information and callbacks for device selection
@@ -18,16 +19,19 @@ interface nsIPresentationDevice;
 interface nsIPresentationDeviceRequest : nsISupports
 {
   // The origin which initiate the request.
   readonly attribute DOMString origin;
 
   // The array of candidate URLs.
   readonly attribute nsIArray requestURLs;
 
+  // The XUL browser element that the request was originated in.
+  readonly attribute nsIDOMEventTarget chromeEventHandler;
+
   /*
    * Callback after selecting a device
    * @param device The selected device.
    */
   void select(in nsIPresentationDevice device);
 
   /*
    * Callback after selection failed or canceled by user.
--- a/dom/presentation/interfaces/nsIPresentationService.idl
+++ b/dom/presentation/interfaces/nsIPresentationService.idl
@@ -1,14 +1,15 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "nsISupports.idl"
 
+interface nsIDOMEventTarget;
 interface nsIInputStream;
 interface nsIPresentationAvailabilityListener;
 interface nsIPresentationRespondingListener;
 interface nsIPresentationSessionListener;
 
 %{C++
 #define PRESENTATION_SERVICE_CID \
   { 0x1d9bb10c, 0xc0ab, 0x4fe8, \
@@ -54,31 +55,35 @@ interface nsIPresentationService : nsISu
   /*
    * Start a new presentation session and display a prompt box which asks users
    * to select a device.
    *
    * @param urls: The candidate Urls of presenting page. Only one url would be used.
    * @param sessionId: An ID to identify presentation session.
    * @param origin: The url of requesting page.
    * @param deviceId: The specified device of handling this request, null string
-                      for prompt device selection dialog.
+   *                  for prompt device selection dialog.
    * @param windowId: The inner window ID associated with the presentation
    *                  session. (0 implies no window ID since no actual window
    *                  uses 0 as its ID. Generally it's the case the window is
    *                  located in different process from this service)
+   * @param eventTarget: The chrome event handler, in particular XUL browser
+   *                     element in parent process, that the request was
+   *                     originated in.
    * @param callback: Invoke the callback when the operation is completed.
    *                  NotifySuccess() is called with |id| if a session is
    *                  established successfully with the selected device.
    *                  Otherwise, NotifyError() is called with a error message.
    */
   [noscript] void startSession(in URLArrayRef urls,
                                in DOMString sessionId,
                                in DOMString origin,
                                in DOMString deviceId,
                                in unsigned long long windowId,
+                               in nsIDOMEventTarget eventTarget,
                                in nsIPresentationServiceCallback callback);
 
   /*
    * Send the message to the session.
    *
    * @param sessionId: An ID to identify presentation session.
    * @param role: Identify the function called by controller or receiver.
    * @param data: the message being sent out.
--- a/dom/presentation/ipc/PPresentation.ipdl
+++ b/dom/presentation/ipc/PPresentation.ipdl
@@ -5,26 +5,29 @@
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 include protocol PContent;
 include protocol PPresentationRequest;
 include protocol PPresentationBuilder;
 
 include InputStreamParams;
 
+using mozilla::dom::TabId from "mozilla/dom/ipc/IdType.h";
+
 namespace mozilla {
 namespace dom {
 
 struct StartSessionRequest
 {
   nsString[] urls;
   nsString sessionId;
   nsString origin;
   nsString deviceId;
   uint64_t windowId;
+  TabId tabId;
 };
 
 struct SendSessionMessageRequest
 {
   nsString sessionId;
   uint8_t role;
   nsString data;
 };
--- a/dom/presentation/ipc/PresentationIPCService.cpp
+++ b/dom/presentation/ipc/PresentationIPCService.cpp
@@ -1,16 +1,17 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set sw=2 ts=8 et ft=cpp : */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "mozilla/dom/ContentChild.h"
 #include "mozilla/dom/PPresentation.h"
+#include "mozilla/dom/TabParent.h"
 #include "mozilla/ipc/InputStreamUtils.h"
 #include "mozilla/ipc/URIUtils.h"
 #include "nsGlobalWindow.h"
 #include "nsIPresentationListener.h"
 #include "PresentationCallbacks.h"
 #include "PresentationChild.h"
 #include "PresentationContentSessionInfo.h"
 #include "PresentationIPCService.h"
@@ -52,29 +53,35 @@ PresentationIPCService::~PresentationIPC
 }
 
 NS_IMETHODIMP
 PresentationIPCService::StartSession(const nsTArray<nsString>& aUrls,
                                      const nsAString& aSessionId,
                                      const nsAString& aOrigin,
                                      const nsAString& aDeviceId,
                                      uint64_t aWindowId,
+                                     nsIDOMEventTarget* aEventTarget,
                                      nsIPresentationServiceCallback* aCallback)
 {
   if (aWindowId != 0) {
     AddRespondingSessionId(aWindowId,
                            aSessionId,
                            nsIPresentationService::ROLE_CONTROLLER);
   }
 
+  nsPIDOMWindowInner* window =
+    nsGlobalWindow::GetInnerWindowWithId(aWindowId)->AsInner();
+  TabId tabId = TabParent::GetTabIdFrom(window->GetDocShell());
+
   return SendRequest(aCallback, StartSessionRequest(aUrls,
                                                     nsString(aSessionId),
                                                     nsString(aOrigin),
                                                     nsString(aDeviceId),
-                                                    aWindowId));
+                                                    aWindowId,
+                                                    tabId));
 }
 
 NS_IMETHODIMP
 PresentationIPCService::SendSessionMessage(const nsAString& aSessionId,
                                            uint8_t aRole,
                                            const nsAString& aData)
 {
   MOZ_ASSERT(!aSessionId.IsEmpty());
--- a/dom/presentation/ipc/PresentationParent.cpp
+++ b/dom/presentation/ipc/PresentationParent.cpp
@@ -1,15 +1,16 @@
 /* -*- Mode: c++; c-basic-offset: 2; indent-tabs-mode: nil; tab-width: 40 -*- */
 /* vim: set ts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #include "DCPresentationChannelDescription.h"
+#include "mozilla/dom/ContentProcessManager.h"
 #include "mozilla/ipc/InputStreamUtils.h"
 #include "mozilla/Unused.h"
 #include "nsIPresentationDeviceManager.h"
 #include "nsServiceManagerUtils.h"
 #include "PresentationBuilderParent.h"
 #include "PresentationParent.h"
 #include "PresentationService.h"
 #include "PresentationSessionInfo.h"
@@ -31,20 +32,21 @@ PresentationParent::PresentationParent()
 }
 
 /* virtual */ PresentationParent::~PresentationParent()
 {
   MOZ_COUNT_DTOR(PresentationParent);
 }
 
 bool
-PresentationParent::Init()
+PresentationParent::Init(ContentParentId aContentParentId)
 {
   MOZ_ASSERT(!mService);
   mService = do_GetService(PRESENTATION_SERVICE_CONTRACTID);
+  mChildId = aContentParentId;
   return NS_WARN_IF(!mService) ? false : true;
 }
 
 void
 PresentationParent::ActorDestroy(ActorDestroyReason aWhy)
 {
   mActorDestroyed = true;
 
@@ -103,17 +105,17 @@ PresentationParent::RecvPPresentationReq
   return NS_WARN_IF(NS_FAILED(rv)) ? false : true;
 }
 
 PPresentationRequestParent*
 PresentationParent::AllocPPresentationRequestParent(
   const PresentationIPCRequest& aRequest)
 {
   MOZ_ASSERT(mService);
-  RefPtr<PresentationRequestParent> actor = new PresentationRequestParent(mService);
+  RefPtr<PresentationRequestParent> actor = new PresentationRequestParent(mService, mChildId);
   return actor.forget().take();
 }
 
 bool
 PresentationParent::DeallocPPresentationRequestParent(
   PPresentationRequestParent* aActor)
 {
   RefPtr<PresentationRequestParent> actor =
@@ -305,18 +307,20 @@ PresentationParent::RecvNotifyTransportC
 }
 
 /*
  * Implementation of PresentationRequestParent
  */
 
 NS_IMPL_ISUPPORTS(PresentationRequestParent, nsIPresentationServiceCallback)
 
-PresentationRequestParent::PresentationRequestParent(nsIPresentationService* aService)
+PresentationRequestParent::PresentationRequestParent(nsIPresentationService* aService,
+                                                     ContentParentId aContentParentId)
   : mService(aService)
+  , mChildId(aContentParentId)
 {
   MOZ_COUNT_CTOR(PresentationRequestParent);
 }
 
 PresentationRequestParent::~PresentationRequestParent()
 {
   MOZ_COUNT_DTOR(PresentationRequestParent);
 }
@@ -329,19 +333,28 @@ PresentationRequestParent::ActorDestroy(
 }
 
 nsresult
 PresentationRequestParent::DoRequest(const StartSessionRequest& aRequest)
 {
   MOZ_ASSERT(mService);
   mNeedRegisterBuilder = true;
   mSessionId = aRequest.sessionId();
+
+  nsCOMPtr<nsIDOMEventTarget> eventTarget;
+  ContentProcessManager* cpm = ContentProcessManager::GetSingleton();
+  RefPtr<TabParent> tp =
+    cpm->GetTopLevelTabParentByProcessAndTabId(mChildId, aRequest.tabId());
+  if (tp) {
+    eventTarget = do_QueryInterface(tp->GetOwnerElement());
+  }
+  
   return mService->StartSession(aRequest.urls(), aRequest.sessionId(),
                                 aRequest.origin(), aRequest.deviceId(),
-                                aRequest.windowId(), this);
+                                aRequest.windowId(), eventTarget, this);
 }
 
 nsresult
 PresentationRequestParent::DoRequest(const SendSessionMessageRequest& aRequest)
 {
   MOZ_ASSERT(mService);
 
   // Validate the accessibility (primarily for receiver side) so that a
--- a/dom/presentation/ipc/PresentationParent.h
+++ b/dom/presentation/ipc/PresentationParent.h
@@ -2,16 +2,17 @@
 /* vim: set ts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
  * You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef mozilla_dom_PresentationParent_h__
 #define mozilla_dom_PresentationParent_h__
 
+#include "mozilla/dom/ipc/IdType.h"
 #include "mozilla/dom/PPresentationBuilderParent.h"
 #include "mozilla/dom/PPresentationParent.h"
 #include "mozilla/dom/PPresentationRequestParent.h"
 #include "nsIPresentationListener.h"
 #include "nsIPresentationService.h"
 #include "nsIPresentationSessionTransportBuilder.h"
 
 namespace mozilla {
@@ -25,17 +26,17 @@ class PresentationParent final : public 
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIPRESENTATIONAVAILABILITYLISTENER
   NS_DECL_NSIPRESENTATIONSESSIONLISTENER
   NS_DECL_NSIPRESENTATIONRESPONDINGLISTENER
 
   PresentationParent();
 
-  bool Init();
+  bool Init(ContentParentId aContentParentId);
 
   bool RegisterTransportBuilder(const nsString& aSessionId, const uint8_t& aRole);
 
   virtual void ActorDestroy(ActorDestroyReason aWhy) override;
 
   virtual bool
   RecvPPresentationRequestConstructor(PPresentationRequestParent* aActor,
                                       const PresentationIPCRequest& aRequest) override;
@@ -81,28 +82,30 @@ public:
 private:
   virtual ~PresentationParent();
 
   bool mActorDestroyed = false;
   nsCOMPtr<nsIPresentationService> mService;
   nsTArray<nsString> mSessionIdsAtController;
   nsTArray<nsString> mSessionIdsAtReceiver;
   nsTArray<uint64_t> mWindowIds;
+  ContentParentId mChildId;
 };
 
 class PresentationRequestParent final : public PPresentationRequestParent
                                       , public nsIPresentationServiceCallback
 {
   friend class PresentationParent;
 
 public:
   NS_DECL_ISUPPORTS
   NS_DECL_NSIPRESENTATIONSERVICECALLBACK
 
-  explicit PresentationRequestParent(nsIPresentationService* aService);
+  explicit PresentationRequestParent(nsIPresentationService* aService,
+                                     ContentParentId aContentParentId);
 
   virtual void ActorDestroy(ActorDestroyReason aWhy) override;
 
 private:
   virtual ~PresentationRequestParent();
 
   nsresult SendResponse(nsresult aResult);
 
@@ -117,14 +120,15 @@ private:
   nsresult DoRequest(const ReconnectSessionRequest& aRequest);
 
   nsresult DoRequest(const BuildTransportRequest& aRequest);
 
   bool mActorDestroyed = false;
   bool mNeedRegisterBuilder = false;
   nsString mSessionId;
   nsCOMPtr<nsIPresentationService> mService;
+  ContentParentId mChildId;
 };
 
 } // namespace dom
 } // namespace mozilla
 
 #endif // mozilla_dom_PresentationParent_h__
--- a/dom/webidl/ChromeUtils.webidl
+++ b/dom/webidl/ChromeUtils.webidl
@@ -76,17 +76,19 @@ interface ChromeUtils : ThreadSafeChrome
  */
 dictionary OriginAttributesDictionary {
   unsigned long appId = 0;
   unsigned long userContextId = 0;
   boolean inIsolatedMozBrowser = false;
   DOMString addonId = "";
   DOMString signedPkg = "";
   unsigned long privateBrowsingId = 0;
+  DOMString firstPartyDomain = "";
 };
 dictionary OriginAttributesPatternDictionary {
   unsigned long appId;
   unsigned long userContextId;
   boolean inIsolatedMozBrowser;
   DOMString addonId;
   DOMString signedPkg;
   unsigned long privateBrowsingId;
+  DOMString firstPartyDomain;
 };
--- a/dom/workers/WorkerRunnable.cpp
+++ b/dom/workers/WorkerRunnable.cpp
@@ -711,34 +711,38 @@ WorkerProxyToMainThreadRunnable::PostDis
     ReleaseRunnable(WorkerPrivate* aWorkerPrivate,
                     WorkerProxyToMainThreadRunnable* aRunnable)
       : MainThreadWorkerControlRunnable(aWorkerPrivate)
       , mRunnable(aRunnable)
     {
       MOZ_ASSERT(aRunnable);
     }
 
-    // We must call RunBackOnWorkerThread() also if the runnable is cancelled.
+    // We must call RunBackOnWorkerThread() also if the runnable is canceled.
     nsresult
     Cancel() override
     {
       WorkerRun(nullptr, mWorkerPrivate);
-      return NS_OK;
+      return MainThreadWorkerControlRunnable::Cancel();
     }
 
     virtual bool
     WorkerRun(JSContext* aCx, workers::WorkerPrivate* aWorkerPrivate) override
     {
       MOZ_ASSERT(aWorkerPrivate);
       aWorkerPrivate->AssertIsOnWorkerThread();
 
-      mRunnable->RunBackOnWorkerThread();
+      if (mRunnable) {
+        mRunnable->RunBackOnWorkerThread();
 
-      // Let's release the worker thread.
-      mRunnable->ReleaseWorker();
+        // Let's release the worker thread.
+        mRunnable->ReleaseWorker();
+        mRunnable = nullptr;
+      }
+
       return true;
     }
 
   private:
     ~ReleaseRunnable()
     {}
   };
 
--- a/embedding/browser/moz.build
+++ b/embedding/browser/moz.build
@@ -43,15 +43,16 @@ UNIFIED_SOURCES += [
     'nsDocShellTreeOwner.cpp',
     'nsEmbedStream.cpp',
     'nsWebBrowser.cpp',
     'nsWebBrowserContentPolicy.cpp',
 ]
 
 FINAL_LIBRARY = 'xul'
 LOCAL_INCLUDES += [
+    '/docshell/base',
     '/dom/base',
     '/dom/svg',
     '/layout/style',
 ]
 
 if CONFIG['GNU_CXX']:
     CXXFLAGS += ['-Wno-error=shadow']
--- a/embedding/browser/nsIWebBrowser.idl
+++ b/embedding/browser/nsIWebBrowser.idl
@@ -8,16 +8,24 @@
 
 interface nsIInterfaceRequestor;
 interface nsIWebBrowserChrome;
 interface nsIURIContentListener;
 interface nsIDOMWindow;
 interface mozIDOMWindowProxy;
 interface nsIWeakReference;
 
+%{C++
+namespace mozilla {
+class DocShellOriginAttributes;
+}
+%}
+
+[ref] native const_OriginAttributesRef(const mozilla::DocShellOriginAttributes);
+
 /**
  * The nsIWebBrowser interface is implemented by web browser objects.
  * Embedders use this interface during initialisation to associate
  * the new web browser instance with the embedders chrome and
  * to register any listeners. The interface may also be used at runtime
  * to obtain the content DOM window and from that the rest of the DOM.
  */
 [scriptable, uuid(4052b6da-4faa-4646-b3a1-7e16a01c2dc2)]
@@ -139,9 +147,17 @@ interface nsIWebBrowser : nsISupports
      * enough that we want to avoid certain optimizations like discarding
      * decoded image data and throttling the refresh driver. In Firefox,
      * this corresponds to the visible tab.
      *
      * Defaults to true. For optimal performance, set it to false when
      * appropriate.
      */
     attribute boolean isActive;
+
+    /**
+     * Set Origin Attributes on the nsIWebBrowser.
+     * The Origin Attributes will be passed to the docshell once it has been
+     * created
+     */
+    [noscript, notxpcom, nostdcall, binaryname(SetOriginAttributes)]
+    void binarySetOriginAttributes(in const_OriginAttributesRef aOriginAttrs);
 };
--- a/embedding/browser/nsWebBrowser.cpp
+++ b/embedding/browser/nsWebBrowser.cpp
@@ -34,16 +34,17 @@
 #include "nsIURI.h"
 #include "nsIWebBrowserPersist.h"
 #include "nsCWebBrowserPersist.h"
 #include "nsIServiceManager.h"
 #include "nsFocusManager.h"
 #include "Layers.h"
 #include "gfxContext.h"
 #include "nsILoadContext.h"
+#include "nsDocShell.h"
 
 // for painting the background window
 #include "mozilla/LookAndFeel.h"
 
 // Printing Includes
 #ifdef NS_PRINTING
 #include "nsIWebBrowserPrint.h"
 #include "nsIContentViewer.h"
@@ -383,16 +384,22 @@ nsWebBrowser::SetIsActive(bool aIsActive
 
   // If we have a docshell, pass on the request
   if (mDocShell) {
     return mDocShell->SetIsActive(aIsActive);
   }
   return NS_OK;
 }
 
+void
+nsWebBrowser::SetOriginAttributes(const DocShellOriginAttributes& aAttrs)
+{
+  mOriginAttributes = aAttrs;
+}
+
 //*****************************************************************************
 // nsWebBrowser::nsIDocShellTreeItem
 //*****************************************************************************
 
 NS_IMETHODIMP
 nsWebBrowser::GetName(nsAString& aName)
 {
   if (mDocShell) {
@@ -1188,16 +1195,17 @@ nsWebBrowser::Create()
     rv = mInternalWidget->Create(nullptr, mParentNativeWindow, bounds,
                                  &widgetInit);
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   nsCOMPtr<nsIDocShell> docShell(
     do_CreateInstance("@mozilla.org/docshell;1", &rv));
   NS_ENSURE_SUCCESS(rv, rv);
+  nsDocShell::Cast(docShell)->SetOriginAttributes(mOriginAttributes);
   rv = SetDocShell(docShell);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // get the system default window background colour
   LookAndFeel::GetColor(LookAndFeel::eColorID_WindowBackground,
                         &mBackgroundColor);
 
   // the docshell has been set so we now have our listener registrars.
--- a/embedding/browser/nsWebBrowser.h
+++ b/embedding/browser/nsWebBrowser.h
@@ -33,16 +33,17 @@
 #include "nsIWebBrowserPersist.h"
 #include "nsIWebBrowserFocus.h"
 #include "nsIWebBrowserStream.h"
 #include "nsIWindowWatcher.h"
 #include "nsIPrintSettings.h"
 #include "nsEmbedStream.h"
 #include "nsIWidgetListener.h"
 
+#include "mozilla/BasePrincipal.h"
 #include "nsTArray.h"
 #include "nsWeakPtr.h"
 
 class nsWebBrowserInitInfo
 {
 public:
   // nsIBaseWindow Stuff
   int32_t x;
@@ -127,16 +128,17 @@ protected:
 protected:
   RefPtr<nsDocShellTreeOwner> mDocShellTreeOwner;
   nsCOMPtr<nsIDocShell> mDocShell;
   nsCOMPtr<nsIInterfaceRequestor> mDocShellAsReq;
   nsCOMPtr<nsIBaseWindow> mDocShellAsWin;
   nsCOMPtr<nsIWebNavigation> mDocShellAsNav;
   nsCOMPtr<nsIScrollable> mDocShellAsScrollable;
   nsCOMPtr<nsITextScroll> mDocShellAsTextScroll;
+  mozilla::DocShellOriginAttributes mOriginAttributes;
 
   nsCOMPtr<nsIWidget> mInternalWidget;
   nsCOMPtr<nsIWindowWatcher> mWWatch;
   nsAutoPtr<nsWebBrowserInitInfo> mInitInfo;
   uint32_t mContentType;
   bool mActivating;
   bool mShouldEnableHistory;
   bool mIsActive;
--- a/gfx/layers/MacIOSurfaceHelpers.cpp
+++ b/gfx/layers/MacIOSurfaceHelpers.cpp
@@ -1,13 +1,14 @@
 /* -*- Mode: C++; tab-width: 20; indent-tabs-mode: nil; c-basic-offset: 2 -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
+#include "libyuv.h"
 #include "MacIOSurfaceHelpers.h"
 #include "mozilla/gfx/MacIOSurface.h"
 #include "YCbCrUtils.h"
 
 namespace mozilla {
 
 using namespace gfx;
 
@@ -79,68 +80,23 @@ CreateSourceSurfaceFromLockedMacIOSurfac
     data.mCbChannel = cbPlane.get();
     data.mCrChannel = crPlane.get();
     data.mCbCrStride = cbCrWidth;
     data.mCbCrSize = IntSize::Truncate(cbCrWidth, cbCrHeight);
     data.mPicSize = data.mYSize;
 
     ConvertYCbCrToRGB(data, SurfaceFormat::B8G8R8X8, IntSize::Truncate(ioWidth, ioHeight), mappedSurface.mData, mappedSurface.mStride);
   } else if (ioFormat == SurfaceFormat::YUV422) {
-    /* Convert to YV16 */
-    size_t cbCrWidth = (ioWidth+1)>>1;
-    size_t cbCrHeight = ioHeight;
-    // Ensure our stride is a multiple of 32 to allow for memory aligned rows.
-    size_t cbCrStride = ALIGNED_32(cbCrWidth);
-    size_t strideDelta = cbCrStride - cbCrWidth;
-    MOZ_ASSERT(strideDelta <= 31);
-
-    auto yPlane = MakeUnique<uint8_t[]>(cbCrStride * 2 * ioHeight + 31);
-    auto cbPlane = MakeUnique<uint8_t[]>(cbCrStride * cbCrHeight + 31);
-    auto crPlane = MakeUnique<uint8_t[]>(cbCrStride * cbCrHeight + 31);
-
-    uint8_t* src = (uint8_t*)aSurface->GetBaseAddress();
-    uint8_t* yDest = ALIGNEDPTR_32(yPlane.get());
-    uint8_t* cbDest = ALIGNEDPTR_32(cbPlane.get());
-    uint8_t* crDest = ALIGNEDPTR_32(crPlane.get());
-
-    for (size_t i = 0; i < ioHeight; i++) {
-      uint8_t* rowSrc = src + bytesPerRow * i;
-      for (size_t j = 0; j < cbCrWidth; j++) {
-        *cbDest = *rowSrc;
-        cbDest++;
-        rowSrc++;
-        *yDest = *rowSrc;
-        yDest++;
-        rowSrc++;
-        *crDest = *rowSrc;
-        crDest++;
-        rowSrc++;
-        *yDest = *rowSrc;
-        yDest++;
-        rowSrc++;
-      }
-      if (strideDelta) {
-        cbDest += strideDelta;
-        crDest += strideDelta;
-        yDest  += strideDelta << 1;
-      }
-    }
-
-    /* Convert to RGB */
-    PlanarYCbCrData data;
-    data.mYChannel = ALIGNEDPTR_32(yPlane.get());
-    data.mYStride = cbCrStride * 2;
-    data.mYSize = IntSize::Truncate(ioWidth, ioHeight);
-    data.mCbChannel = ALIGNEDPTR_32(cbPlane.get());
-    data.mCrChannel = ALIGNEDPTR_32(crPlane.get());
-    data.mCbCrStride = cbCrStride;
-    data.mCbCrSize = IntSize::Truncate(cbCrWidth, cbCrHeight);
-    data.mPicSize = data.mYSize;
-
-    ConvertYCbCrToRGB(data, SurfaceFormat::B8G8R8X8, IntSize::Truncate(ioWidth, ioHeight), mappedSurface.mData, mappedSurface.mStride);
+    IntSize size = IntSize::Truncate(ioWidth, ioHeight);
+    libyuv::ConvertToARGB((uint8_t*)aSurface->GetBaseAddress(), 0 /* not used */,
+                          mappedSurface.mData, mappedSurface.mStride,
+                          0, 0,
+                          size.width, size.height,
+                          size.width, size.height,
+                          libyuv::kRotate0, libyuv::FOURCC_UYVY);
   } else {
     unsigned char* ioData = (unsigned char*)aSurface->GetBaseAddress();
 
     for (size_t i = 0; i < ioHeight; ++i) {
       memcpy(mappedSurface.mData + i * mappedSurface.mStride,
              ioData + i * bytesPerRow,
              ioWidth * 4);
     }
--- a/gfx/layers/composite/TextureHost.h
+++ b/gfx/layers/composite/TextureHost.h
@@ -389,21 +389,30 @@ public:
     ISurfaceAllocator* aDeallocator,
     LayersBackend aBackend,
     TextureFlags aFlags);
 
   /**
    * Lock the texture host for compositing.
    */
   virtual bool Lock() { return true; }
+  /**
+   * Unlock the texture host after compositing. Lock() and Unlock() should be
+   * called in pair.
+   */
+  virtual void Unlock() {}
 
   /**
-   * Unlock the texture host after compositing.
+   * Lock the texture host for compositing without using compositor.
    */
-  virtual void Unlock() {}
+  virtual bool LockWithoutCompositor() { return true; }
+  /**
+   * Similar to Unlock(), but it should be called with LockWithoutCompositor().
+   */
+  virtual void UnlockWithoutCompositor() {}
 
   /**
    * Note that the texture host format can be different from its corresponding
    * texture source's. For example a ShmemTextureHost can have the ycbcr
    * format and produce 3 "alpha" textures sources.
    */
   virtual gfx::SurfaceFormat GetFormat() const = 0;
   /**
@@ -806,16 +815,39 @@ public:
 
   bool Failed() { return mTexture && !mLocked; }
 
 private:
   RefPtr<TextureHost> mTexture;
   bool mLocked;
 };
 
+class MOZ_STACK_CLASS AutoLockTextureHostWithoutCompositor
+{
+public:
+  explicit AutoLockTextureHostWithoutCompositor(TextureHost* aTexture)
+    : mTexture(aTexture)
+  {
+    mLocked = mTexture ? mTexture->LockWithoutCompositor() : false;
+  }
+
+  ~AutoLockTextureHostWithoutCompositor()
+  {
+    if (mTexture && mLocked) {
+      mTexture->UnlockWithoutCompositor();
+    }
+  }
+
+  bool Failed() { return mTexture && !mLocked; }
+
+private:
+  RefPtr<TextureHost> mTexture;
+  bool mLocked;
+};
+
 /**
  * This can be used as an offscreen rendering target by the compositor, and
  * subsequently can be used as a source by the compositor.
  */
 class CompositingRenderTarget: public TextureSource
 {
 public:
 
--- a/gfx/layers/d3d11/TextureD3D11.cpp
+++ b/gfx/layers/d3d11/TextureD3D11.cpp
@@ -728,21 +728,50 @@ Compositor*
 DXGITextureHostD3D11::GetCompositor()
 {
   return mCompositor;
 }
 
 bool
 DXGITextureHostD3D11::Lock()
 {
-  /**
-   * Note: This function may be called when mCompositor is null
-   *       such as during WebVR frame submission.
-   **/
+  if (!mCompositor) {
+    // Make an early return here if we call SetCompositor() with an incompatible
+    // compositor. This check tries to prevent the problem where we use that
+    // incompatible compositor to compose this texture.
+    return false;
+  }
+
+  return LockInternal();
+}
 
+bool
+DXGITextureHostD3D11::LockWithoutCompositor()
+{
+  // Unlike the normal Lock() function, this function may be called when
+  // mCompositor is nullptr such as during WebVR frame submission. So, there is
+  // no 'mCompositor' checking here.
+  return LockInternal();
+}
+
+void
+DXGITextureHostD3D11::Unlock()
+{
+  UnlockInternal();
+}
+
+void
+DXGITextureHostD3D11::UnlockWithoutCompositor()
+{
+  UnlockInternal();
+}
+
+bool
+DXGITextureHostD3D11::LockInternal()
+{
   if (!GetDevice()) {
     NS_WARNING("trying to lock a TextureHost without a D3D device");
     return false;
   }
 
   if (!mTextureSource) {
     if (!mTexture && !OpenSharedHandle()) {
       gfxWindowsPlatform::GetPlatform()->ForceDeviceReset(ForcedDeviceResetReason::OPENSHAREDHANDLE);
@@ -753,17 +782,17 @@ DXGITextureHostD3D11::Lock()
   }
 
   mIsLocked = LockD3DTexture(mTextureSource->GetD3D11Texture());
 
   return mIsLocked;
 }
 
 void
-DXGITextureHostD3D11::Unlock()
+DXGITextureHostD3D11::UnlockInternal()
 {
   UnlockD3DTexture(mTextureSource->GetD3D11Texture());
 }
 
 bool
 DXGITextureHostD3D11::BindTextureSource(CompositableTextureSourceRef& aTexture)
 {
   MOZ_ASSERT(mIsLocked);
--- a/gfx/layers/d3d11/TextureD3D11.h
+++ b/gfx/layers/d3d11/TextureD3D11.h
@@ -291,27 +291,32 @@ public:
 
   virtual void SetCompositor(Compositor* aCompositor) override;
 
   virtual Compositor* GetCompositor() override;
 
   virtual gfx::SurfaceFormat GetFormat() const override { return mFormat; }
 
   virtual bool Lock() override;
+  virtual void Unlock() override;
 
-  virtual void Unlock() override;
+  virtual bool LockWithoutCompositor() override;
+  virtual void UnlockWithoutCompositor() override;
 
   virtual gfx::IntSize GetSize() const override { return mSize; }
 
   virtual already_AddRefed<gfx::DataSourceSurface> GetAsSurface() override
   {
     return nullptr;
   }
 
 protected:
+  bool LockInternal();
+  void UnlockInternal();
+
   RefPtr<ID3D11Device> GetDevice();
 
   bool OpenSharedHandle();
 
   RefPtr<ID3D11Texture2D> mTexture;
   RefPtr<DataTextureSourceD3D11> mTextureSource;
   RefPtr<CompositorD3D11> mCompositor;
   gfx::IntSize mSize;
--- a/gfx/thebes/gfxAndroidPlatform.cpp
+++ b/gfx/thebes/gfxAndroidPlatform.cpp
@@ -168,16 +168,17 @@ IsJapaneseLocale()
 
 void
 gfxAndroidPlatform::GetCommonFallbackFonts(uint32_t aCh, uint32_t aNextCh,
                                            Script aRunScript,
                                            nsTArray<const char*>& aFontList)
 {
     static const char kDroidSansJapanese[] = "Droid Sans Japanese";
     static const char kMotoyaLMaru[] = "MotoyaLMaru";
+    static const char kNotoSansCJKJP[] = "Noto Sans CJK JP";
     static const char kNotoColorEmoji[] = "Noto Color Emoji";
 #ifdef MOZ_WIDGET_GONK
     static const char kFirefoxEmoji[] = "Firefox Emoji";
 #endif
 
     if (aNextCh == 0xfe0fu) {
         // if char is followed by VS16, try for a color emoji glyph
 #ifdef MOZ_WIDGET_GONK
@@ -224,22 +225,24 @@ gfxAndroidPlatform::GetCommonFallbackFon
             aFontList.AppendElement("Droid Sans Georgian");
             break;
         case 0x12: case 0x13:
             aFontList.AppendElement("Droid Sans Ethiopic");
             break;
         case 0xf9: case 0xfa:
             if (IsJapaneseLocale()) {
                 aFontList.AppendElement(kMotoyaLMaru);
+                aFontList.AppendElement(kNotoSansCJKJP);
                 aFontList.AppendElement(kDroidSansJapanese);
             }
             break;
         default:
             if (block >= 0x2e && block <= 0x9f && IsJapaneseLocale()) {
                 aFontList.AppendElement(kMotoyaLMaru);
+                aFontList.AppendElement(kNotoSansCJKJP);
                 aFontList.AppendElement(kDroidSansJapanese);
             }
             break;
         }
     }
     // and try Droid Sans Fallback as a last resort
     aFontList.AppendElement("Droid Sans Fallback");
 }
--- a/gfx/vr/VRDisplayHost.cpp
+++ b/gfx/vr/VRDisplayHost.cpp
@@ -78,17 +78,19 @@ VRDisplayHost::SubmitFrame(VRLayerParent
   // It is possible to get a cache miss on mLastSensorState if latency is
   // longer than kMaxLatencyFrames.  An optimization would be to find a frame
   // that is closer than the one selected with the modulus.
   // If we hit this; however, latency is already so high that the site is
   // un-viewable and a more accurate pose prediction is not likely to
   // compensate.
 
   TextureHost* th = TextureHost::AsTextureHost(aTexture);
-  AutoLockTextureHost autoLock(th);
+  // WebVR doesn't use the compositor to compose the frame, so use
+  // AutoLockTextureHostWithoutCompositor here.
+  AutoLockTextureHostWithoutCompositor autoLock(th);
   if (autoLock.Failed()) {
     NS_WARNING("Failed to lock the VR layer texture");
     return;
   }
 
   CompositableTextureSourceRef source;
   if (!th->BindTextureSource(source)) {
     NS_WARNING("The TextureHost was successfully locked but can't provide a TextureSource");
--- a/image/SVGDocumentWrapper.cpp
+++ b/image/SVGDocumentWrapper.cpp
@@ -345,16 +345,30 @@ SVGDocumentWrapper::SetupViewer(nsIReque
                                         NS_LITERAL_CSTRING(IMAGE_SVG_XML),
                                         nullptr, nullptr,
                                         getter_AddRefs(listener),
                                         getter_AddRefs(viewer));
   NS_ENSURE_SUCCESS(rv, rv);
 
   NS_ENSURE_TRUE(viewer, NS_ERROR_UNEXPECTED);
 
+  // Create a navigation time object and pass it to the SVG document through
+  // the viewer.
+  // The timeline(DocumentTimeline, used in CSS animation) of this SVG
+  // document needs this navigation timing object for time computation, such
+  // as to calculate current time stamp based on the start time of navigation
+  // time object.
+  //
+  // For a root document, DocShell would do these sort of things
+  // automatically. Since there is no DocShell for this wrapped SVG document,
+  // we must set it up manually.
+  RefPtr<nsDOMNavigationTiming> timing = new nsDOMNavigationTiming();
+  timing->NotifyNavigationStart();
+  viewer->SetNavigationTiming(timing);
+
   nsCOMPtr<nsIParser> parser = do_QueryInterface(listener);
   NS_ENSURE_TRUE(parser, NS_ERROR_UNEXPECTED);
 
   // XML-only, because this is for SVG content
   nsIContentSink* sink = parser->GetContentSink();
   nsCOMPtr<nsIXMLContentSink> xmlSink = do_QueryInterface(sink);
   NS_ENSURE_TRUE(sink, NS_ERROR_UNEXPECTED);
 
--- a/image/VectorImage.cpp
+++ b/image/VectorImage.cpp
@@ -520,16 +520,22 @@ VectorImage::GetWidth(int32_t* aWidth)
 //******************************************************************************
 NS_IMETHODIMP_(void)
 VectorImage::RequestRefresh(const TimeStamp& aTime)
 {
   if (HadRecentRefresh(aTime)) {
     return;
   }
 
+  PendingAnimationTracker* tracker =
+    mSVGDocumentWrapper->GetDocument()->GetPendingAnimationTracker();
+  if (tracker && ShouldAnimate()) {
+    tracker->TriggerPendingAnimationsOnNextTick(aTime);
+  }
+
   EvaluateAnimation();
 
   mSVGDocumentWrapper->TickRefreshDriver();
 
   if (mHasPendingInvalidation) {
     SendInvalidationNotifications();
     mHasPendingInvalidation = false;
   }
new file mode 100644
--- /dev/null
+++ b/image/test/mochitest/lime-css-anim-100x100.svg
@@ -0,0 +1,19 @@
+<svg xmlns="http://www.w3.org/2000/svg" version="1.1"
+     width="100" height="100">
+  <defs>
+    <style>
+      #myRect {
+        animation-duration: 0.1s;
+        animation-name: fade;
+        animation-fill-mode: forwards;
+      }
+
+      @keyframes fade {
+          0% { fill-opacity: 0 }
+          100% { fill-opacity: 1 }
+      }
+    </style>
+  </defs>
+  <rect width="100%" height="100%" fill="red"/>
+  <rect id="myRect" width="100%" height="100%" fill="lime" fill-opacity="0"/>
+</svg>
--- a/image/test/mochitest/mochitest.ini
+++ b/image/test/mochitest/mochitest.ini
@@ -57,16 +57,17 @@ support-files =
   iframe.html
   imgutils.js
   invalid.jpg
   keep.gif
   keep.png
   lime100x100.svg
   lime-anim-100x100.svg
   lime-anim-100x100-2.svg
+  lime-css-anim-100x100.svg
   opaque.bmp
   purple.gif
   red.gif
   red.png
   ref-iframe.html
   restore-previous.gif
   restore-previous.png
   rillybad.jpg
--- a/image/test/mochitest/test_animSVGImage.html
+++ b/image/test/mochitest/test_animSVGImage.html
@@ -28,17 +28,21 @@ SimpleTest.waitForExplicitFinish();
 const FAILURE_TIMEOUT = 120000; // Fail early after 120 seconds (2 minutes)
 
 const gImg = document.getElementsByTagName("img")[0];
 
 var gMyDecoderObserver; // value will be set in main()
 var gReferenceSnapshot; // value will be set in takeReferenceSnapshot()
 var gPollCounter = 0;
 var gIsTestFinished = false;
-
+var gSVGImages = [
+  "lime-anim-100x100.svg",    // SMIL animation
+  "lime-css-anim-100x100.svg" // CSS animation
+]
+var gSVGCurrentImage = 0;
 
 function takeReferenceSnapshot() {
   // Take a snapshot of the initial (essentially blank) page
   let blankSnapshot = snapshotWindow(window, false);
 
   // Show reference div, & take a snapshot
   let referenceDiv = document.getElementById("referenceDiv");
   referenceDiv.style.display = "block";
@@ -48,25 +52,37 @@ function takeReferenceSnapshot() {
 
   // Re-hide reference div, and take another snapshot to be sure it's gone
   referenceDiv.style.display = "none";
   let blankSnapshot2 = snapshotWindow(window, false);
   ok(compareSnapshots(blankSnapshot, blankSnapshot2, true)[0],
      "reference div should disappear when it becomes display:none");
 }
 
+function loadNextImageAndPoll()
+{
+  setTimeout(myPoll, 1);
+  // kick off image-loading! myPoll handles the rest.
+  gImg.setAttribute("src", gSVGImages[gSVGCurrentImage]);
+}
+
 function myPoll() {
   gPollCounter++;
   ok(true, "myPoll called");
   let currentSnapshot = snapshotWindow(window, false);
   if (compareSnapshots(currentSnapshot, gReferenceSnapshot, true)[0]) {
     // SUCCESS!
     ok(true, "Animated image looks correct, " +
              "at call #" + gPollCounter + " to myPoll");
-    cleanUpAndFinish();
+
+    if (++gSVGCurrentImage > gSVGImages.length) {
+      cleanUpAndFinish();
+    } else {
+      loadNextImageAndPoll();
+    }
   }
   else
     setTimeout(myPoll, 1);
 }
 
 function failTest() {
   ok(false, "timing out after " + FAILURE_TIMEOUT + "ms.  " +
             "Animated image still doesn't look correct, " +
@@ -86,20 +102,17 @@ function cleanUpAndFinish() {
 
 function main() {
   takeReferenceSnapshot();
 
   // We want to test the cold loading behavior, so clear cache in case an
   // earlier test got our image in there already.
   clearAllImageCaches();
 
-  setTimeout(myPoll, 1);
-
-  // kick off image-loading! myPoll handles the rest.
-  gImg.setAttribute("src", "lime-anim-100x100.svg");
+  loadNextImageAndPoll();
 
   // In case something goes wrong, fail earlier than mochitest timeout,
   // and with more information.
   setTimeout(failTest, FAILURE_TIMEOUT);
 }
 
 window.onload = main;
 
--- a/ipc/glue/WindowsMessageLoop.h
+++ b/ipc/glue/WindowsMessageLoop.h
@@ -5,17 +5,16 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 #ifndef IPC_GLUE_WINDOWSMESSAGELOOP_H
 #define IPC_GLUE_WINDOWSMESSAGELOOP_H
 
 // This file is only meant to compile on windows
 #include <windows.h>
 
-#include "base/basictypes.h"
 #include "nsISupportsImpl.h"
 
 namespace mozilla {
 namespace ipc {
 namespace windows {
 
 void InitUIThread();
 
--- a/js/src/devtools/automation/cgc-jittest-timeouts.txt
+++ b/js/src/devtools/automation/cgc-jittest-timeouts.txt
@@ -1,13 +1,14 @@
 SIMD/nursery-overflow.js
 asm.js/testParallelCompile.js
 auto-regress/bug653395.js
 auto-regress/bug654392.js
 auto-regress/bug675251.js
+auto-regress/bug729797.js
 baseline/bug847446.js
 baseline/bug852175.js
 basic/bug632964-regexp.js
 basic/bug656261.js
 basic/bug677957-2.js
 basic/bug753283.js
 basic/bug867946.js
 basic/testAtomize.js
--- a/js/src/devtools/automation/cgc-jstests-slow.txt
+++ b/js/src/devtools/automation/cgc-jstests-slow.txt
@@ -46,15 +46,16 @@ ecma_6/String/normalize-generateddata-pa
 ecma_6/String/normalize-generateddata-part1-not-listed.js
 ecma_6/String/normalize-generateddata-part1.js
 ecma_6/String/normalize-generateddata-part2.js
 ecma_6/String/normalize-generateddata-part3.js
 js1_5/GC/regress-203278-2.js
 js1_5/GC/regress-203278-3.js
 js1_5/GC/regress-278725.js
 js1_5/Regress/regress-312588.js
+js1_5/Regress/regress-321971.js
 js1_5/Regress/regress-360969-01.js
 js1_5/Regress/regress-360969-02.js
 js1_5/Regress/regress-360969-03.js
 js1_5/Regress/regress-360969-04.js
 js1_5/Regress/regress-360969-05.js
 js1_5/Regress/regress-360969-06.js
 js1_8_5/extensions/clone-complex-object.js
--- a/layout/base/nsDisplayList.cpp
+++ b/layout/base/nsDisplayList.cpp
@@ -1777,17 +1777,17 @@ already_AddRefed<LayerManager> nsDisplay
   }
 
   if (widgetTransaction) {
     layerBuilder->DidBeginRetainedLayerTransaction(layerManager);
   }
 
   nsIFrame* frame = aBuilder->RootReferenceFrame();
   nsPresContext* presContext = frame->PresContext();
-  nsIPresShell* presShell = presContext->GetPresShell();
+  nsIPresShell* presShell = presContext->PresShell();
   nsRootPresContext* rootPresContext = presContext->GetRootPresContext();
 
   NotifySubDocInvalidationFunc computeInvalidFunc =
     presContext->MayHavePaintEventListenerInSubDocument() ? nsPresContext::NotifySubDocInvalidation : 0;
   bool computeInvalidRect = (computeInvalidFunc ||
                              (!layerManager->IsCompositingCheap() && layerManager->NeedsWidgetInvalidation())) &&
                             widgetTransaction;
 
@@ -1804,20 +1804,17 @@ already_AddRefed<LayerManager> nsDisplay
   }
 
   ContainerLayerParameters containerParameters
     (presShell->GetResolution(), presShell->GetResolution());
   RefPtr<ContainerLayer> root = layerBuilder->
     BuildContainerLayerFor(aBuilder, layerManager, frame, nullptr, this,
                            containerParameters, nullptr);
 
-  nsIDocument* document = nullptr;
-  if (presShell) {
-    document = presShell->GetDocument();
-  }
+  nsIDocument* document = presShell->GetDocument();
 
   if (!root) {
     layerManager->SetUserData(&gLayerManagerLayerBuilder, oldBuilder);
     return nullptr;
   }
   // Root is being scaled up by the X/Y resolution. Scale it back down.
   root->SetPostScale(1.0f/containerParameters.mXScale,
                      1.0f/containerParameters.mYScale);
--- a/mobile/android/base/java/org/mozilla/gecko/ActionBarTextSelection.java
+++ b/mobile/android/base/java/org/mozilla/gecko/ActionBarTextSelection.java
@@ -80,21 +80,25 @@ class ActionBarTextSelection implements 
     @Override
     public boolean dismiss() {
         // We do not call endActionMode() here because this is already handled by the activity.
         return false;
     }
 
     @Override
     public void destroy() {
-        EventDispatcher.getInstance().unregisterGeckoThreadListener(this,
-            "TextSelection:ActionbarInit",
-            "TextSelection:ActionbarStatus",
-            "TextSelection:ActionbarUninit",
-            "TextSelection:Update");
+        if (anchorHandle == null) {
+            Log.e(LOGTAG, "Do not unregister TextSelection:* listeners since anchorHandle is null");
+        } else {
+            EventDispatcher.getInstance().unregisterGeckoThreadListener(this,
+                    "TextSelection:ActionbarInit",
+                    "TextSelection:ActionbarStatus",
+                    "TextSelection:ActionbarUninit",
+                    "TextSelection:Update");
+        }
     }
 
     @Override
     public void handleMessage(final String event, final JSONObject message) {
         ThreadUtils.postToUiThread(new Runnable() {
             @Override
             public void run() {
                 try {
--- a/mobile/android/base/java/org/mozilla/gecko/icons/IconResponse.java
+++ b/mobile/android/base/java/org/mozilla/gecko/icons/IconResponse.java
@@ -65,17 +65,21 @@ public class IconResponse {
     private Bitmap bitmap;
     private int color;
     private boolean fromNetwork;
     private boolean fromMemory;
     private boolean fromDisk;
     private boolean generated;
     private String url;
 
-    private IconResponse(@NonNull Bitmap bitmap) {
+    private IconResponse(Bitmap bitmap) {
+        if (bitmap == null) {
+            throw new NullPointerException("Bitmap is null");
+        }
+
         this.bitmap = bitmap;
         this.color = 0;
         this.url = null;
         this.fromNetwork = false;
         this.fromMemory = false;
         this.fromDisk = false;
         this.generated = false;
     }
--- a/mobile/android/base/java/org/mozilla/gecko/icons/IconTask.java
+++ b/mobile/android/base/java/org/mozilla/gecko/icons/IconTask.java
@@ -18,17 +18,17 @@ import org.mozilla.gecko.util.ThreadUtil
 import java.util.List;
 import java.util.concurrent.Callable;
 
 /**
  * Task that will be run by the IconRequestExecutor for every icon request.
  */
 /* package-private */ class IconTask implements Callable<IconResponse> {
     private static final String LOGTAG = "Gecko/IconTask";
-    private static final boolean DEBUG = true;
+    private static final boolean DEBUG = false;
 
     private final List<Preparer> preparers;
     private final List<IconLoader> loaders;
     private final List<Processor> processors;
     private final IconLoader generator;
     private final IconRequest request;
 
     /* package-private */ IconTask(
--- a/mobile/android/base/java/org/mozilla/gecko/icons/decoders/LoadFaviconResult.java
+++ b/mobile/android/base/java/org/mozilla/gecko/icons/decoders/LoadFaviconResult.java
@@ -1,15 +1,16 @@
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 package org.mozilla.gecko.icons.decoders;
 
 import android.graphics.Bitmap;
+import android.support.annotation.Nullable;
 import android.util.Log;
 import android.util.SparseArray;
 
 import java.io.ByteArrayOutputStream;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
@@ -72,16 +73,17 @@ public class LoadFaviconResult {
         } catch (OutOfMemoryError e) {
             Log.w(LOGTAG, "Out of memory re-compressing favicon.");
         }
 
         Log.w(LOGTAG, "Favicon re-compression failed.");
         return null;
     }
 
+    @Nullable
     public Bitmap getBestBitmap(int targetWidthAndHeight) {
         final SparseArray<Bitmap> iconMap = new SparseArray<>();
         final List<Integer> sizes = new ArrayList<>();
 
         while (bitmapsDecoded.hasNext()) {
             final Bitmap b = bitmapsDecoded.next();
 
             // It's possible to receive null, most likely due to OOM or a zero-sized image,
--- a/mobile/android/base/java/org/mozilla/gecko/icons/loader/IconDownloader.java
+++ b/mobile/android/base/java/org/mozilla/gecko/icons/loader/IconDownloader.java
@@ -1,16 +1,17 @@
 /* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*-
  * This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 package org.mozilla.gecko.icons.loader;
 
 import android.content.Context;
+import android.graphics.Bitmap;
 import android.support.annotation.VisibleForTesting;
 import android.util.Log;
 
 import org.mozilla.gecko.GeckoAppShell;
 import org.mozilla.gecko.icons.decoders.FaviconDecoder;
 import org.mozilla.gecko.icons.decoders.LoadFaviconResult;
 import org.mozilla.gecko.icons.IconRequest;
 import org.mozilla.gecko.icons.IconResponse;
@@ -55,19 +56,22 @@ public class IconDownloader implements I
         }
 
         try {
             LoadFaviconResult result = downloadAndDecodeImage(request.getContext(), iconUrl);
             if (result == null) {
                 return null;
             }
 
-            return IconResponse.createFromNetwork(
-                    result.getBestBitmap(request.getTargetSize()),
-                    iconUrl);
+            final Bitmap bitmap = result.getBestBitmap(request.getTargetSize());
+            if (bitmap == null) {
+                return null;
+            }
+
+            return IconResponse.createFromNetwork(bitmap, iconUrl);
         } catch (Exception e) {
             Log.e(LOGTAG, "Error reading favicon", e);
         } catch (OutOfMemoryError e) {
             Log.e(LOGTAG, "Insufficient memory to process favicon");
         }
 
         return null;
     }
--- a/mobile/android/base/java/org/mozilla/gecko/icons/storage/DiskStorage.java
+++ b/mobile/android/base/java/org/mozilla/gecko/icons/storage/DiskStorage.java
@@ -61,17 +61,17 @@ public class DiskStorage {
     private DiskLruCache cache;
 
     private DiskStorage(Context context) {
         this.context = context.getApplicationContext();
     }
 
     @CheckResult
     private synchronized DiskLruCache ensureCacheIsReady() throws IOException {
-        if (cache == null) {
+        if (cache == null || cache.isClosed()) {
             cache = DiskLruCache.open(
                     new File(context.getCacheDir(), "icons"),
                     CACHE_VERSION,
                     1,
                     DISK_CACHE_SIZE);
         }
 
         return cache;
@@ -230,16 +230,17 @@ public class DiskStorage {
     /**
      * Remove all entries from this cache.
      */
     public void evictAll() {
         try {
             final DiskLruCache cache = ensureCacheIsReady();
 
             cache.delete();
+
         } catch (IOException e) {
             Log.w(LOGTAG, "IOException while accessing disk cache", e);
         }
     }
 
     /**
      * Create a key for this URL using the given prefix.
      *
--- a/modules/libpref/init/all.js
+++ b/modules/libpref/init/all.js
@@ -4215,24 +4215,25 @@ pref("font.name.sans-serif.he", "Clear S
 pref("font.name.monospace.he", "Droid Sans Mono");
 pref("font.name-list.serif.he", "Noto Serif");
 pref("font.name-list.sans-serif.he", "Droid Sans Hebrew, Clear Sans, Droid Sans");
 
 pref("font.name.serif.ja", "Charis SIL Compact");
 pref("font.name.sans-serif.ja", "Clear Sans");
 pref("font.name.monospace.ja", "MotoyaLMaru");
 pref("font.name-list.serif.ja", "Noto Serif, Droid Serif");
-pref("font.name-list.sans-serif.ja", "Clear Sans, Roboto, Droid Sans, MotoyaLMaru, MotoyaLCedar, Noto Sans JP, Droid Sans Japanese");
-pref("font.name-list.monospace.ja", "MotoyaLMaru, MotoyaLCedar, Droid Sans Mono");
+pref("font.name-list.sans-serif.ja", "Clear Sans, Roboto, Droid Sans, MotoyaLMaru, MotoyaLCedar, Noto Sans JP, Noto Sans CJK JP, Droid Sans Japanese");
+pref("font.name-list.monospace.ja", "MotoyaLMaru, MotoyaLCedar, Droid Sans Mono CJK JP, Droid Sans Mono");
 
 pref("font.name.serif.ko", "Charis SIL Compact");
 pref("font.name.sans-serif.ko", "Clear Sans");
 pref("font.name.monospace.ko", "Droid Sans Mono");
 pref("font.name-list.serif.ko", "Noto Serif, Droid Serif, HYSerif");
-pref("font.name-list.sans-serif.ko", "SmartGothic, NanumGothic, Noto Sans KR, DroidSansFallback, Droid Sans Fallback");
+pref("font.name-list.sans-serif.ko", "SmartGothic, NanumGothic, Noto Sans KR, Noto Sans CJK KR, DroidSansFallback, Droid Sans Fallback");
+pref("font.name-list.monospace.ko", "Noto Sans Mono CJK KR");
 
 pref("font.name.serif.th", "Charis SIL Compact");
 pref("font.name.sans-serif.th", "Clear Sans");
 pref("font.name.monospace.th", "Droid Sans Mono");
 pref("font.name-list.serif.th", "Noto Serif, Droid Serif");
 pref("font.name-list.sans-serif.th", "Droid Sans Thai, Clear Sans, Droid Sans");
 
 pref("font.name.serif.x-cyrillic", "Charis SIL Compact");
@@ -4252,32 +4253,32 @@ pref("font.name.sans-serif.x-western", "
 pref("font.name.monospace.x-western", "Droid Sans Mono");
 pref("font.name-list.serif.x-western", "Noto Serif, Droid Serif");
 pref("font.name-list.sans-serif.x-western", "Clear Sans, Roboto, Droid Sans");
 
 pref("font.name.serif.zh-CN", "Charis SIL Compact");
 pref("font.name.sans-serif.zh-CN", "Clear Sans");
 pref("font.name.monospace.zh-CN", "Droid Sans Mono");
 pref("font.name-list.serif.zh-CN", "Noto Serif, Droid Serif, Droid Sans Fallback");
-pref("font.name-list.sans-serif.zh-CN", "Roboto, Droid Sans, Noto Sans SC, Droid Sans Fallback");
-pref("font.name-list.monospace.zh-CN", "Droid Sans Fallback");
+pref("font.name-list.sans-serif.zh-CN", "Roboto, Droid Sans, Noto Sans SC, Noto Sans CJK SC, Droid Sans Fallback");
+pref("font.name-list.monospace.zh-CN", "Noto Sans Mono CJK SC, Droid Sans Fallback");
 
 pref("font.name.serif.zh-HK", "Charis SIL Compact");
 pref("font.name.sans-serif.zh-HK", "Clear Sans");
 pref("font.name.monospace.zh-HK", "Droid Sans Mono");
 pref("font.name-list.serif.zh-HK", "Noto Serif, Droid Serif, Droid Sans Fallback");
-pref("font.name-list.sans-serif.zh-HK", "Roboto, Droid Sans, Noto Sans TC, Noto Sans SC, Droid Sans Fallback");
-pref("font.name-list.monospace.zh-HK", "Droid Sans Fallback");
+pref("font.name-list.sans-serif.zh-HK", "Roboto, Droid Sans, Noto Sans TC, Noto Sans SC, Noto Sans CJK TC, Droid Sans Fallback");
+pref("font.name-list.monospace.zh-HK", "Noto Sans Mono CJK TC, Droid Sans Fallback");
 
 pref("font.name.serif.zh-TW", "Charis SIL Compact");
 pref("font.name.sans-serif.zh-TW", "Clear Sans");
 pref("font.name.monospace.zh-TW", "Droid Sans Mono");
 pref("font.name-list.serif.zh-TW", "Noto Serif, Droid Serif, Droid Sans Fallback");
-pref("font.name-list.sans-serif.zh-TW", "Roboto, Droid Sans, Noto Sans TC, Noto Sans SC, Droid Sans Fallback");
-pref("font.name-list.monospace.zh-TW", "Droid Sans Fallback");
+pref("font.name-list.sans-serif.zh-TW", "Roboto, Droid Sans, Noto Sans TC, Noto Sans SC, Noto Sans CJK TC, Droid Sans Fallback");
+pref("font.name-list.monospace.zh-TW", "Noto Sans Mono CJK TC, Droid Sans Fallback");
 
 pref("font.name.serif.x-math", "Latin Modern Math");
 pref("font.name-list.serif.x-math", "Latin Modern Math, XITS Math, Cambria Math, Libertinus Math, DejaVu Math TeX Gyre, TeX Gyre Bonum Math, TeX Gyre Pagella Math, TeX Gyre Schola, TeX Gyre Termes Math, STIX Math, Asana Math, STIXGeneral, DejaVu Serif, DejaVu Sans, Charis SIL Compact");
 pref("font.name.sans-serif.x-math", "Clear Sans");
 pref("font.name.monospace.x-math", "Droid Sans Mono");
 
 #endif
 
--- a/netwerk/ipc/NeckoParent.cpp
+++ b/netwerk/ipc/NeckoParent.cpp
@@ -143,16 +143,17 @@ NeckoParent::GetValidatedAppInfo(const S
       continue;
     }
     aAttrs = DocShellOriginAttributes();
     aAttrs.mAppId = appId;
     aAttrs.mInIsolatedMozBrowser = inBrowserElement;
     aAttrs.mSignedPkg = aSerialized.mOriginAttributes.mSignedPkg;
     aAttrs.mUserContextId = aSerialized.mOriginAttributes.mUserContextId;
     aAttrs.mPrivateBrowsingId = aSerialized.mOriginAttributes.mPrivateBrowsingId;
+    aAttrs.mFirstPartyDomain = aSerialized.mOriginAttributes.mFirstPartyDomain;
 
     return nullptr;
   }
 
   if (contextArray.Length() != 0) {
     return "App does not have permission";
   }
 
--- a/netwerk/protocol/http/HttpBaseChannel.cpp
+++ b/netwerk/protocol/http/HttpBaseChannel.cpp
@@ -2896,16 +2896,46 @@ HttpBaseChannel::SetupReplacementChannel
     }
   }
 
   // make a copy of the loadinfo, append to the redirectchain
   // and set it on the new channel
   if (mLoadInfo) {
     nsCOMPtr<nsILoadInfo> newLoadInfo =
       static_cast<mozilla::LoadInfo*>(mLoadInfo.get())->Clone();
+
+    // re-compute the origin attributes of the loadInfo if it's top-level load.
+    bool isTopLevelDoc =
+      newLoadInfo->GetExternalContentPolicyType() == nsIContentPolicy::TYPE_DOCUMENT;
+
+    if (isTopLevelDoc) {
+      nsCOMPtr<nsILoadContext> loadContext;
+      NS_QueryNotificationCallbacks(this, loadContext);
+      DocShellOriginAttributes docShellAttrs;
+      if (loadContext) {
+        loadContext->GetOriginAttributes(docShellAttrs);
+      }
+      MOZ_ASSERT(docShellAttrs.mFirstPartyDomain.IsEmpty(),
+                 "top-level docshell shouldn't have firstPartyDomain attribute.");
+
+      NeckoOriginAttributes attrs = newLoadInfo->GetOriginAttributes();
+
+      MOZ_ASSERT(docShellAttrs.mAppId == attrs.mAppId,
+                "docshell and necko should have the same appId attribute.");
+      MOZ_ASSERT(docShellAttrs.mUserContextId == attrs.mUserContextId,
+                "docshell and necko should have the same userContextId attribute.");
+      MOZ_ASSERT(docShellAttrs.mInIsolatedMozBrowser == attrs.mInIsolatedMozBrowser,
+                "docshell and necko should have the same inIsolatedMozBrowser attribute.");
+      MOZ_ASSERT(docShellAttrs.mPrivateBrowsingId == attrs.mPrivateBrowsingId,
+                 "docshell and necko should have the same privateBrowsingId attribute.");
+
+      attrs.InheritFromDocShellToNecko(docShellAttrs, true, newURI);
+      newLoadInfo->SetOriginAttributes(attrs);
+    }
+
     bool isInternalRedirect =
       (redirectFlags & (nsIChannelEventSink::REDIRECT_INTERNAL |
                         nsIChannelEventSink::REDIRECT_STS_UPGRADE));
     newLoadInfo->AppendRedirectedPrincipal(GetURIPrincipal(), isInternalRedirect);
     newChannel->SetLoadInfo(newLoadInfo);
   }
   else {
     // the newChannel was created with a dummy loadInfo, we should clear
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/debug/debugging_flags.h
@@ -0,0 +1,19 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// This is a copy of a file that is generated by the chromium build.
+
+// Generated by build/write_buildflag_header.py
+// From "//base:debugging_flags"
+
+#ifndef BASE_DEBUG_DEBUGGING_FLAGS_H_
+#define BASE_DEBUG_DEBUGGING_FLAGS_H_
+
+#include "build/buildflag.h"
+
+#define BUILDFLAG_INTERNAL_ENABLE_PROFILING() (0)
+
+#endif  // BASE_DEBUG_DEBUGGING_FLAGS_H_
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/file_version_info_win.h
@@ -0,0 +1,29 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// This is a dummy version of Chromium source file base/file_version_info_win.h
+// Within our copy of Chromium files FileVersionInfoWin is only used in
+// base/win/windows_version.cc in GetVersionFromKernel32, which we don't use.
+
+#ifndef BASE_FILE_VERSION_INFO_WIN_H_
+#define BASE_FILE_VERSION_INFO_WIN_H_
+
+struct tagVS_FIXEDFILEINFO;
+typedef tagVS_FIXEDFILEINFO VS_FIXEDFILEINFO;
+
+namespace base {
+class FilePath;
+}
+
+class FileVersionInfoWin {
+ public:
+  static FileVersionInfoWin*
+    CreateFileVersionInfo(const base::FilePath& file_path) { return nullptr; }
+
+  VS_FIXEDFILEINFO* fixed_file_info() { return nullptr; }
+};
+
+#endif  // BASE_FILE_VERSION_INFO_WIN_H_
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/files/file_path.cpp
@@ -0,0 +1,19 @@
+// Copyright (c) 2012 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+// This is a dummy version of Chromium source file base/file/file_path.cc.
+// To provide the functions required in base/win/windows_version.cc
+// GetVersionFromKernel32, which we don't use.
+
+#include "base/files/file_path.h"
+
+namespace base {
+
+FilePath::FilePath(FilePath::StringPieceType path) {
+}
+
+FilePath::~FilePath() {
+}
+
+} // namespace base
--- a/security/sandbox/chromium-shim/base/logging.cpp
+++ b/security/sandbox/chromium-shim/base/logging.cpp
@@ -21,26 +21,51 @@
 #if defined(OS_POSIX)
 #include <errno.h>
 #endif
 
 #if defined(OS_WIN)
 #include "base/strings/utf_string_conversions.h"
 #endif
 
+#include <algorithm>
+
 namespace logging {
 
 namespace {
 
-int min_log_level = 0;
+int g_min_log_level = 0;
+
+LoggingDestination g_logging_destination = LOG_DEFAULT;
+
+// For LOG_ERROR and above, always print to stderr.
+const int kAlwaysPrintErrorLevel = LOG_ERROR;
+
+// A log message handler that gets notified of every log message we process.
+LogMessageHandlerFunction log_message_handler = nullptr;
 
 }  // namespace
 
+void SetMinLogLevel(int level) {
+  g_min_log_level = std::min(LOG_FATAL, level);
+}
+
 int GetMinLogLevel() {
-  return min_log_level;
+  return g_min_log_level;
+}
+
+bool ShouldCreateLogMessage(int severity) {
+  if (severity < g_min_log_level)
+    return false;
+
+  // Return true here unless we know ~LogMessage won't do anything. Note that
+  // ~LogMessage writes to stderr if severity_ >= kAlwaysPrintErrorLevel, even
+  // when g_logging_destination is LOG_NONE.
+  return g_logging_destination != LOG_NONE || log_message_handler ||
+         severity >= kAlwaysPrintErrorLevel;
 }
 
 int GetVlogLevelHelper(const char* file, size_t N) {
   return 0;
 }
 
 // Explicit instantiations for commonly used comparisons.
 template std::string* MakeCheckOpString<int, int>(
@@ -62,16 +87,20 @@ LogMessage::SaveLastError::~SaveLastErro
   ::SetLastError(last_error_);
 }
 #endif  // defined(OS_WIN)
 
 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
     : severity_(severity), file_(file), line_(line) {
 }
 
+LogMessage::LogMessage(const char* file, int line, const char* condition)
+    : severity_(LOG_FATAL), file_(file), line_(line) {
+}
+
 LogMessage::LogMessage(const char* file, int line, std::string* result)
     : severity_(LOG_FATAL), file_(file), line_(line) {
   delete result;
 }
 
 LogMessage::LogMessage(const char* file, int line, LogSeverity severity,
                        std::string* result)
     : severity_(severity), file_(file), line_(line) {
--- a/security/sandbox/chromium-shim/base/win/sdkdecls.h
+++ b/security/sandbox/chromium-shim/base/win/sdkdecls.h
@@ -43,16 +43,34 @@ typedef LPSTARTUPINFOEXA LPSTARTUPINFOEX
 #define ProcThreadAttributeHandleList 2
 
 #define PROC_THREAD_ATTRIBUTE_HANDLE_LIST \
     ProcThreadAttributeValue (ProcThreadAttributeHandleList, FALSE, TRUE, FALSE)
 
 #define PROCESS_DEP_ENABLE                          0x00000001
 #define PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION     0x00000002
 
+// They dynamically load these, but they still use the functions to describe the
+// function pointers!
+WINBASEAPI
+int
+WINAPI
+GetUserDefaultLocaleName(
+    _Out_writes_(cchLocaleName) LPWSTR lpLocaleName,
+    _In_ int cchLocaleName
+);
+
+WINBASEAPI
+BOOL
+WINAPI
+QueryThreadCycleTime(
+    _In_ HANDLE ThreadHandle,
+    _Out_ PULONG64 CycleTime
+    );
+
 #endif // (_WIN32_WINNT >= 0x0600)
 
 #if (_WIN32_WINNT < 0x0601)
 #define ProcThreadAttributeMitigationPolicy 7
 #define PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY \
     ProcThreadAttributeValue (ProcThreadAttributeMitigationPolicy, FALSE, TRUE, FALSE)
 
 #define PROCESS_CREATION_MITIGATION_POLICY_DEP_ENABLE            0x01
--- a/security/sandbox/chromium/LICENSE
+++ b/security/sandbox/chromium/LICENSE
@@ -1,9 +1,9 @@
-// Copyright 2014 The Chromium Authors. All rights reserved.
+// Copyright 2015 The Chromium Authors. 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
--- a/security/sandbox/chromium/base/at_exit.h
+++ b/security/sandbox/chromium/base/at_exit.h
@@ -3,18 +3,18 @@
 // found in the LICENSE file.
 
 #ifndef BASE_AT_EXIT_H_
 #define BASE_AT_EXIT_H_
 
 #include <stack>
 
 #include "base/base_export.h"
-#include "base/basictypes.h"
 #include "base/callback.h"
+#include "base/macros.h"
 #include "base/synchronization/lock.h"
 
 namespace base {
 
 // This class provides a facility similar to the CRT atexit(), except that
 // we control when the callbacks are executed. Under Windows for a DLL they
 // happen at a really bad time and under the loader lock. This facility is
 // mostly used by base::Singleton.
--- a/security/sandbox/chromium/base/atomic_ref_count.h
+++ b/security/sandbox/chromium/base/atomic_ref_count.h
@@ -1,17 +1,14 @@
 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
 // This is a low level implementation of atomic semantics for reference
 // counting.  Please use base/memory/ref_counted.h directly instead.
-//
-// The implementation includes annotations to avoid some false positives
-// when using data race detection tools.
 
 #ifndef BASE_ATOMIC_REF_COUNT_H_
 #define BASE_ATOMIC_REF_COUNT_H_
 
 #include "base/atomicops.h"
 
 namespace base {
 
--- a/security/sandbox/chromium/base/atomic_sequence_num.h
+++ b/security/sandbox/chromium/base/atomic_sequence_num.h
@@ -1,17 +1,17 @@
 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
 #ifndef BASE_ATOMIC_SEQUENCE_NUM_H_
 #define BASE_ATOMIC_SEQUENCE_NUM_H_
 
 #include "base/atomicops.h"
-#include "base/basictypes.h"
+#include "base/macros.h"
 
 namespace base {
 
 class AtomicSequenceNumber;
 
 // Static (POD) AtomicSequenceNumber that MUST be used in global scope (or
 // non-function scope) ONLY. This implementation does not generate any static
 // initializer.  Note that it does not implement any constructor which means
--- a/security/sandbox/chromium/base/atomicops.h
+++ b/security/sandbox/chromium/base/atomicops.h
@@ -23,20 +23,24 @@
 //   NoBarrier_Load()
 // Although there are currently no compiler enforcement, you are encouraged
 // to use these.
 //
 
 #ifndef BASE_ATOMICOPS_H_
 #define BASE_ATOMICOPS_H_
 
-#include <cassert>  // Small C++ header which defines implementation specific
-                    // macros used to identify the STL implementation.
 #include <stdint.h>
 
+// Small C++ header which defines implementation specific macros used to
+// identify the STL implementation.
+// - libc++: captures __config for _LIBCPP_VERSION
+// - libstdc++: captures bits/c++config.h for __GLIBCXX__
+#include <cstddef>
+
 #include "base/base_export.h"
 #include "build/build_config.h"
 
 #if defined(OS_WIN) && defined(ARCH_CPU_64_BITS)
 // windows.h #defines this (only on x64). This causes problems because the
 // public API also uses MemoryBarrier at the public name for this fence. So, on
 // X64, undef it, and call its documented
 // (http://msdn.microsoft.com/en-us/library/windows/desktop/ms684208.aspx)
@@ -135,75 +139,23 @@ void Release_Store(volatile Atomic64* pt
 Atomic64 NoBarrier_Load(volatile const Atomic64* ptr);
 Atomic64 Acquire_Load(volatile const Atomic64* ptr);
 Atomic64 Release_Load(volatile const Atomic64* ptr);
 #endif  // ARCH_CPU_64_BITS
 
 }  // namespace subtle
 }  // namespace base
 
-// The following x86 CPU features are used in atomicops_internals_x86_gcc.h, but
-// this file is duplicated inside of Chrome: protobuf and tcmalloc rely on the
-// struct being present at link time. Some parts of Chrome can currently use the
-// portable interface whereas others still use GCC one. The include guards are
-// the same as in atomicops_internals_x86_gcc.cc.
-#if defined(__i386__) || defined(__x86_64__)
-// This struct is not part of the public API of this module; clients may not
-// use it.  (However, it's exported via BASE_EXPORT because clients implicitly
-// do use it at link time by inlining these functions.)
-// Features of this x86.  Values may not be correct before main() is run,
-// but are set conservatively.
-struct AtomicOps_x86CPUFeatureStruct {
-  bool has_amd_lock_mb_bug; // Processor has AMD memory-barrier bug; do lfence
-                            // after acquire compare-and-swap.
-  // The following fields are unused by Chrome's base implementation but are
-  // still used by copies of the same code in other parts of the code base. This
-  // causes an ODR violation, and the other code is likely reading invalid
-  // memory.
-  // TODO(jfb) Delete these fields once the rest of the Chrome code base doesn't
-  //           depend on them.
-  bool has_sse2;            // Processor has SSE2.
-  bool has_cmpxchg16b;      // Processor supports cmpxchg16b instruction.
-};
-BASE_EXPORT extern struct AtomicOps_x86CPUFeatureStruct
-    AtomicOps_Internalx86CPUFeatures;
+#if defined(OS_WIN)
+// TODO(jfb): The MSVC header includes windows.h, which other files end up
+//            relying on. Fix this as part of crbug.com/559247.
+#  include "base/atomicops_internals_x86_msvc.h"
+#else
+#  include "base/atomicops_internals_portable.h"
 #endif
 
-// Try to use a portable implementation based on C++11 atomics.
-//
-// Some toolchains support C++11 language features without supporting library
-// features (recent compiler, older STL). Whitelist libstdc++ and libc++ that we
-// know will have <atomic> when compiling C++11.
-#if ((__cplusplus >= 201103L) &&                            \
-     ((defined(__GLIBCXX__) && (__GLIBCXX__ > 20110216)) || \
-      (defined(_LIBCPP_VERSION) && (_LIBCPP_STD_VER >= 11))))
-#  include "base/atomicops_internals_portable.h"
-#else  // Otherwise use a platform specific implementation.
-#  if defined(THREAD_SANITIZER)
-#    error "Thread sanitizer must use the portable atomic operations"
-#  elif (defined(OS_WIN) && defined(COMPILER_MSVC) && \
-         defined(ARCH_CPU_X86_FAMILY))
-#    include "base/atomicops_internals_x86_msvc.h"
-#  elif defined(OS_MACOSX)
-#    include "base/atomicops_internals_mac.h"
-#  elif defined(OS_NACL)
-#    include "base/atomicops_internals_gcc.h"
-#  elif defined(COMPILER_GCC) && defined(ARCH_CPU_ARMEL)
-#    include "base/atomicops_internals_arm_gcc.h"
-#  elif defined(COMPILER_GCC) && defined(ARCH_CPU_ARM64)
-#    include "base/atomicops_internals_arm64_gcc.h"
-#  elif defined(COMPILER_GCC) && defined(ARCH_CPU_X86_FAMILY)
-#    include "base/atomicops_internals_x86_gcc.h"
-#  elif (defined(COMPILER_GCC) && \
-         (defined(ARCH_CPU_MIPS_FAMILY) || defined(ARCH_CPU_MIPS64_FAMILY)))
-#    include "base/atomicops_internals_mips_gcc.h"
-#  else
-#    error "Atomic operations are not supported on your platform"
-#  endif
-#endif   // Portable / non-portable includes.
-
 // On some platforms we need additional declarations to make
 // AtomicWord compatible with our other Atomic* types.
 #if defined(OS_MACOSX) || defined(OS_OPENBSD)
 #include "base/atomicops_internals_atomicword_compat.h"
 #endif
 
 #endif  // BASE_ATOMICOPS_H_
deleted file mode 100644
--- a/security/sandbox/chromium/base/atomicops_internals_arm_gcc.h
+++ /dev/null
@@ -1,294 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// This file is an internal atomic implementation, use base/atomicops.h instead.
-//
-// LinuxKernelCmpxchg and Barrier_AtomicIncrement are from Google Gears.
-
-#ifndef BASE_ATOMICOPS_INTERNALS_ARM_GCC_H_
-#define BASE_ATOMICOPS_INTERNALS_ARM_GCC_H_
-
-#if defined(OS_QNX)
-#include <sys/cpuinline.h>
-#endif
-
-namespace base {
-namespace subtle {
-
-// Memory barriers on ARM are funky, but the kernel is here to help:
-//
-// * ARMv5 didn't support SMP, there is no memory barrier instruction at
-//   all on this architecture, or when targeting its machine code.
-//
-// * Some ARMv6 CPUs support SMP. A full memory barrier can be produced by
-//   writing a random value to a very specific coprocessor register.
-//
-// * On ARMv7, the "dmb" instruction is used to perform a full memory
-//   barrier (though writing to the co-processor will still work).
-//   However, on single core devices (e.g. Nexus One, or Nexus S),
-//   this instruction will take up to 200 ns, which is huge, even though
-//   it's completely un-needed on these devices.
-//
-// * There is no easy way to determine at runtime if the device is
-//   single or multi-core. However, the kernel provides a useful helper
-//   function at a fixed memory address (0xffff0fa0), which will always
-//   perform a memory barrier in the most efficient way. I.e. on single
-//   core devices, this is an empty function that exits immediately.
-//   On multi-core devices, it implements a full memory barrier.
-//
-// * This source could be compiled to ARMv5 machine code that runs on a
-//   multi-core ARMv6 or ARMv7 device. In this case, memory barriers
-//   are needed for correct execution. Always call the kernel helper, even
-//   when targeting ARMv5TE.
-//
-
-inline void MemoryBarrier() {
-#if defined(OS_LINUX) || defined(OS_ANDROID)
-  // Note: This is a function call, which is also an implicit compiler barrier.
-  typedef void (*KernelMemoryBarrierFunc)();
-  ((KernelMemoryBarrierFunc)0xffff0fa0)();
-#elif defined(OS_QNX)
-  __cpu_membarrier();
-#else
-#error MemoryBarrier() is not implemented on this platform.
-#endif
-}
-
-// An ARM toolchain would only define one of these depending on which
-// variant of the target architecture is being used. This tests against
-// any known ARMv6 or ARMv7 variant, where it is possible to directly
-// use ldrex/strex instructions to implement fast atomic operations.
-#if defined(__ARM_ARCH_7__) || defined(__ARM_ARCH_7A__) || \
-    defined(__ARM_ARCH_7R__) || defined(__ARM_ARCH_7M__) || \
-    defined(__ARM_ARCH_6__) || defined(__ARM_ARCH_6J__) || \
-    defined(__ARM_ARCH_6K__) || defined(__ARM_ARCH_6Z__) || \
-    defined(__ARM_ARCH_6ZK__) || defined(__ARM_ARCH_6T2__)
-
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
-                                         Atomic32 old_value,
-                                         Atomic32 new_value) {
-  Atomic32 prev_value;
-  int reloop;
-  do {
-    // The following is equivalent to:
-    //
-    //   prev_value = LDREX(ptr)
-    //   reloop = 0
-    //   if (prev_value != old_value)
-    //      reloop = STREX(ptr, new_value)
-    __asm__ __volatile__("    ldrex %0, [%3]\n"
-                         "    mov %1, #0\n"
-                         "    cmp %0, %4\n"
-#ifdef __thumb2__
-                         "    it eq\n"
-#endif
-                         "    strexeq %1, %5, [%3]\n"
-                         : "=&r"(prev_value), "=&r"(reloop), "+m"(*ptr)
-                         : "r"(ptr), "r"(old_value), "r"(new_value)
-                         : "cc", "memory");
-  } while (reloop != 0);
-  return prev_value;
-}
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
-                                       Atomic32 old_value,
-                                       Atomic32 new_value) {
-  Atomic32 result = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-  MemoryBarrier();
-  return result;
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
-                                       Atomic32 old_value,
-                                       Atomic32 new_value) {
-  MemoryBarrier();
-  return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
-                                          Atomic32 increment) {
-  Atomic32 value;
-  int reloop;
-  do {
-    // Equivalent to:
-    //
-    //  value = LDREX(ptr)
-    //  value += increment
-    //  reloop = STREX(ptr, value)
-    //
-    __asm__ __volatile__("    ldrex %0, [%3]\n"
-                         "    add %0, %0, %4\n"
-                         "    strex %1, %0, [%3]\n"
-                         : "=&r"(value), "=&r"(reloop), "+m"(*ptr)
-                         : "r"(ptr), "r"(increment)
-                         : "cc", "memory");
-  } while (reloop);
-  return value;
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
-                                        Atomic32 increment) {
-  // TODO(digit): Investigate if it's possible to implement this with
-  // a single MemoryBarrier() operation between the LDREX and STREX.
-  // See http://crbug.com/246514
-  MemoryBarrier();
-  Atomic32 result = NoBarrier_AtomicIncrement(ptr, increment);
-  MemoryBarrier();
-  return result;
-}
-
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
-                                         Atomic32 new_value) {
-  Atomic32 old_value;
-  int reloop;
-  do {
-    // old_value = LDREX(ptr)
-    // reloop = STREX(ptr, new_value)
-    __asm__ __volatile__("   ldrex %0, [%3]\n"
-                         "   strex %1, %4, [%3]\n"
-                         : "=&r"(old_value), "=&r"(reloop), "+m"(*ptr)
-                         : "r"(ptr), "r"(new_value)
-                         : "cc", "memory");
-  } while (reloop != 0);
-  return old_value;
-}
-
-// This tests against any known ARMv5 variant.
-#elif defined(__ARM_ARCH_5__) || defined(__ARM_ARCH_5T__) || \
-      defined(__ARM_ARCH_5TE__) || defined(__ARM_ARCH_5TEJ__)
-
-// The kernel also provides a helper function to perform an atomic
-// compare-and-swap operation at the hard-wired address 0xffff0fc0.
-// On ARMv5, this is implemented by a special code path that the kernel
-// detects and treats specially when thread pre-emption happens.
-// On ARMv6 and higher, it uses LDREX/STREX instructions instead.
-//
-// Note that this always perform a full memory barrier, there is no
-// need to add calls MemoryBarrier() before or after it. It also
-// returns 0 on success, and 1 on exit.
-//
-// Available and reliable since Linux 2.6.24. Both Android and ChromeOS
-// use newer kernel revisions, so this should not be a concern.
-namespace {
-
-inline int LinuxKernelCmpxchg(Atomic32 old_value,
-                              Atomic32 new_value,
-                              volatile Atomic32* ptr) {
-  typedef int (*KernelCmpxchgFunc)(Atomic32, Atomic32, volatile Atomic32*);
-  return ((KernelCmpxchgFunc)0xffff0fc0)(old_value, new_value, ptr);
-}
-
-}  // namespace
-
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
-                                         Atomic32 old_value,
-                                         Atomic32 new_value) {
-  Atomic32 prev_value;
-  for (;;) {
-    prev_value = *ptr;
-    if (prev_value != old_value)
-      return prev_value;
-    if (!LinuxKernelCmpxchg(old_value, new_value, ptr))
-      return old_value;
-  }
-}
-
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
-                                         Atomic32 new_value) {
-  Atomic32 old_value;
-  do {
-    old_value = *ptr;
-  } while (LinuxKernelCmpxchg(old_value, new_value, ptr));
-  return old_value;
-}
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
-                                          Atomic32 increment) {
-  return Barrier_AtomicIncrement(ptr, increment);
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
-                                        Atomic32 increment) {
-  for (;;) {
-    // Atomic exchange the old value with an incremented one.
-    Atomic32 old_value = *ptr;
-    Atomic32 new_value = old_value + increment;
-    if (!LinuxKernelCmpxchg(old_value, new_value, ptr)) {
-      // The exchange took place as expected.
-      return new_value;
-    }
-    // Otherwise, *ptr changed mid-loop and we need to retry.
-  }
-}
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
-                                       Atomic32 old_value,
-                                       Atomic32 new_value) {
-  Atomic32 prev_value;
-  for (;;) {
-    prev_value = *ptr;
-    if (prev_value != old_value) {
-      // Always ensure acquire semantics.
-      MemoryBarrier();
-      return prev_value;
-    }
-    if (!LinuxKernelCmpxchg(old_value, new_value, ptr))
-      return old_value;
-  }
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
-                                       Atomic32 old_value,
-                                       Atomic32 new_value) {
-  // This could be implemented as:
-  //    MemoryBarrier();
-  //    return NoBarrier_CompareAndSwap();
-  //
-  // But would use 3 barriers per succesful CAS. To save performance,
-  // use Acquire_CompareAndSwap(). Its implementation guarantees that:
-  // - A succesful swap uses only 2 barriers (in the kernel helper).
-  // - An early return due to (prev_value != old_value) performs
-  //   a memory barrier with no store, which is equivalent to the
-  //   generic implementation above.
-  return Acquire_CompareAndSwap(ptr, old_value, new_value);
-}
-
-#else
-#  error "Your CPU's ARM architecture is not supported yet"
-#endif
-
-// NOTE: Atomicity of the following load and store operations is only
-// guaranteed in case of 32-bit alignement of |ptr| values.
-
-inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
-  *ptr = value;
-}
-
-inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
-  *ptr = value;
-  MemoryBarrier();
-}
-
-inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
-  MemoryBarrier();
-  *ptr = value;
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) { return *ptr; }
-
-inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
-  Atomic32 value = *ptr;
-  MemoryBarrier();
-  return value;
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
-  MemoryBarrier();
-  return *ptr;
-}
-
-}  // namespace base::subtle
-}  // namespace base
-
-#endif  // BASE_ATOMICOPS_INTERNALS_ARM_GCC_H_
--- a/security/sandbox/chromium/base/atomicops_internals_portable.h
+++ b/security/sandbox/chromium/base/atomicops_internals_portable.h
@@ -29,16 +29,18 @@
 //    needs to increment twice (which the compiler should be able to detect and
 //    optimize).
 
 #ifndef BASE_ATOMICOPS_INTERNALS_PORTABLE_H_
 #define BASE_ATOMICOPS_INTERNALS_PORTABLE_H_
 
 #include <atomic>
 
+#include "build/build_config.h"
+
 namespace base {
 namespace subtle {
 
 // This implementation is transitional and maintains the original API for
 // atomicops.h. This requires casting memory locations to the atomic types, and
 // assumes that the API and the C++11 implementation are layout-compatible,
 // which isn't true for all implementations or hardware platforms. The static
 // assertion should detect this issue, were it to fire then this header
@@ -216,12 +218,12 @@ inline Atomic64 Acquire_Load(volatile co
 }
 
 inline Atomic64 Release_Load(volatile const Atomic64* ptr) {
   MemoryBarrier();
   return ((AtomicLocation64)ptr)->load(std::memory_order_relaxed);
 }
 
 #endif  // defined(ARCH_CPU_64_BITS)
-}
-}  // namespace base::subtle
+}  // namespace subtle
+}  // namespace base
 
 #endif  // BASE_ATOMICOPS_INTERNALS_PORTABLE_H_
deleted file mode 100644
--- a/security/sandbox/chromium/base/atomicops_internals_x86_gcc.h
+++ /dev/null
@@ -1,228 +0,0 @@
-// Copyright (c) 2011 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// This file is an internal atomic implementation, use base/atomicops.h instead.
-
-#ifndef BASE_ATOMICOPS_INTERNALS_X86_GCC_H_
-#define BASE_ATOMICOPS_INTERNALS_X86_GCC_H_
-
-#define ATOMICOPS_COMPILER_BARRIER() __asm__ __volatile__("" : : : "memory")
-
-namespace base {
-namespace subtle {
-
-// 32-bit low-level operations on any platform.
-
-inline Atomic32 NoBarrier_CompareAndSwap(volatile Atomic32* ptr,
-                                         Atomic32 old_value,
-                                         Atomic32 new_value) {
-  Atomic32 prev;
-  __asm__ __volatile__("lock; cmpxchgl %1,%2"
-                       : "=a" (prev)
-                       : "q" (new_value), "m" (*ptr), "0" (old_value)
-                       : "memory");
-  return prev;
-}
-
-inline Atomic32 NoBarrier_AtomicExchange(volatile Atomic32* ptr,
-                                         Atomic32 new_value) {
-  __asm__ __volatile__("xchgl %1,%0"  // The lock prefix is implicit for xchg.
-                       : "=r" (new_value)
-                       : "m" (*ptr), "0" (new_value)
-                       : "memory");
-  return new_value;  // Now it's the previous value.
-}
-
-inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
-                                          Atomic32 increment) {
-  Atomic32 temp = increment;
-  __asm__ __volatile__("lock; xaddl %0,%1"
-                       : "+r" (temp), "+m" (*ptr)
-                       : : "memory");
-  // temp now holds the old value of *ptr
-  return temp + increment;
-}
-
-inline Atomic32 Barrier_AtomicIncrement(volatile Atomic32* ptr,
-                                        Atomic32 increment) {
-  Atomic32 temp = increment;
-  __asm__ __volatile__("lock; xaddl %0,%1"
-                       : "+r" (temp), "+m" (*ptr)
-                       : : "memory");
-  // temp now holds the old value of *ptr
-  if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
-    __asm__ __volatile__("lfence" : : : "memory");
-  }
-  return temp + increment;
-}
-
-inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
-                                       Atomic32 old_value,
-                                       Atomic32 new_value) {
-  Atomic32 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-  if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
-    __asm__ __volatile__("lfence" : : : "memory");
-  }
-  return x;
-}
-
-inline Atomic32 Release_CompareAndSwap(volatile Atomic32* ptr,
-                                       Atomic32 old_value,
-                                       Atomic32 new_value) {
-  return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-inline void NoBarrier_Store(volatile Atomic32* ptr, Atomic32 value) {
-  *ptr = value;
-}
-
-inline void MemoryBarrier() {
-  __asm__ __volatile__("mfence" : : : "memory");
-}
-
-inline void Acquire_Store(volatile Atomic32* ptr, Atomic32 value) {
-  *ptr = value;
-  MemoryBarrier();
-}
-
-inline void Release_Store(volatile Atomic32* ptr, Atomic32 value) {
-  ATOMICOPS_COMPILER_BARRIER();
-  *ptr = value; // An x86 store acts as a release barrier.
-  // See comments in Atomic64 version of Release_Store(), below.
-}
-
-inline Atomic32 NoBarrier_Load(volatile const Atomic32* ptr) {
-  return *ptr;
-}
-
-inline Atomic32 Acquire_Load(volatile const Atomic32* ptr) {
-  Atomic32 value = *ptr; // An x86 load acts as a acquire barrier.
-  // See comments in Atomic64 version of Release_Store(), below.
-  ATOMICOPS_COMPILER_BARRIER();
-  return value;
-}
-
-inline Atomic32 Release_Load(volatile const Atomic32* ptr) {
-  MemoryBarrier();
-  return *ptr;
-}
-
-#if defined(__x86_64__)
-
-// 64-bit low-level operations on 64-bit platform.
-
-inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
-                                         Atomic64 old_value,
-                                         Atomic64 new_value) {
-  Atomic64 prev;
-  __asm__ __volatile__("lock; cmpxchgq %1,%2"
-                       : "=a" (prev)
-                       : "q" (new_value), "m" (*ptr), "0" (old_value)
-                       : "memory");
-  return prev;
-}
-
-inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr,
-                                         Atomic64 new_value) {
-  __asm__ __volatile__("xchgq %1,%0"  // The lock prefix is implicit for xchg.
-                       : "=r" (new_value)
-                       : "m" (*ptr), "0" (new_value)
-                       : "memory");
-  return new_value;  // Now it's the previous value.
-}
-
-inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr,
-                                          Atomic64 increment) {
-  Atomic64 temp = increment;
-  __asm__ __volatile__("lock; xaddq %0,%1"
-                       : "+r" (temp), "+m" (*ptr)
-                       : : "memory");
-  // temp now contains the previous value of *ptr
-  return temp + increment;
-}
-
-inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr,
-                                        Atomic64 increment) {
-  Atomic64 temp = increment;
-  __asm__ __volatile__("lock; xaddq %0,%1"
-                       : "+r" (temp), "+m" (*ptr)
-                       : : "memory");
-  // temp now contains the previous value of *ptr
-  if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
-    __asm__ __volatile__("lfence" : : : "memory");
-  }
-  return temp + increment;
-}
-
-inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) {
-  *ptr = value;
-}
-
-inline void Acquire_Store(volatile Atomic64* ptr, Atomic64 value) {
-  *ptr = value;
-  MemoryBarrier();
-}
-
-inline void Release_Store(volatile Atomic64* ptr, Atomic64 value) {
-  ATOMICOPS_COMPILER_BARRIER();
-
-  *ptr = value; // An x86 store acts as a release barrier
-                // for current AMD/Intel chips as of Jan 2008.
-                // See also Acquire_Load(), below.
-
-  // When new chips come out, check:
-  //  IA-32 Intel Architecture Software Developer's Manual, Volume 3:
-  //  System Programming Guide, Chatper 7: Multiple-processor management,
-  //  Section 7.2, Memory Ordering.
-  // Last seen at:
-  //   http://developer.intel.com/design/pentium4/manuals/index_new.htm
-  //
-  // x86 stores/loads fail to act as barriers for a few instructions (clflush
-  // maskmovdqu maskmovq movntdq movnti movntpd movntps movntq) but these are
-  // not generated by the compiler, and are rare.  Users of these instructions
-  // need to know about cache behaviour in any case since all of these involve
-  // either flushing cache lines or non-temporal cache hints.
-}
-
-inline Atomic64 NoBarrier_Load(volatile const Atomic64* ptr) {
-  return *ptr;
-}
-
-inline Atomic64 Acquire_Load(volatile const Atomic64* ptr) {
-  Atomic64 value = *ptr; // An x86 load acts as a acquire barrier,
-                         // for current AMD/Intel chips as of Jan 2008.
-                         // See also Release_Store(), above.
-  ATOMICOPS_COMPILER_BARRIER();
-  return value;
-}
-
-inline Atomic64 Release_Load(volatile const Atomic64* ptr) {
-  MemoryBarrier();
-  return *ptr;
-}
-
-inline Atomic64 Acquire_CompareAndSwap(volatile Atomic64* ptr,
-                                       Atomic64 old_value,
-                                       Atomic64 new_value) {
-  Atomic64 x = NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-  if (AtomicOps_Internalx86CPUFeatures.has_amd_lock_mb_bug) {
-    __asm__ __volatile__("lfence" : : : "memory");
-  }
-  return x;
-}
-
-inline Atomic64 Release_CompareAndSwap(volatile Atomic64* ptr,
-                                       Atomic64 old_value,
-                                       Atomic64 new_value) {
-  return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
-}
-
-#endif  // defined(__x86_64__)
-
-} // namespace base::subtle
-} // namespace base
-
-#undef ATOMICOPS_COMPILER_BARRIER
-
-#endif  // BASE_ATOMICOPS_INTERNALS_X86_GCC_H_
--- a/security/sandbox/chromium/base/atomicops_internals_x86_msvc.h
+++ b/security/sandbox/chromium/base/atomicops_internals_x86_msvc.h
@@ -7,16 +7,17 @@
 #ifndef BASE_ATOMICOPS_INTERNALS_X86_MSVC_H_
 #define BASE_ATOMICOPS_INTERNALS_X86_MSVC_H_
 
 #include <windows.h>
 
 #include <intrin.h>
 
 #include "base/macros.h"
+#include "build/build_config.h"
 
 #if defined(ARCH_CPU_64_BITS)
 // windows.h #defines this (only on x64). This causes problems because the
 // public API also uses MemoryBarrier at the public name for this fence. So, on
 // X64, undef it, and call its documented
 // (http://msdn.microsoft.com/en-us/library/windows/desktop/ms684208.aspx)
 // implementation directly.
 #undef MemoryBarrier
@@ -50,19 +51,16 @@ inline Atomic32 Barrier_AtomicIncrement(
       static_cast<LONG>(increment)) + increment;
 }
 
 inline Atomic32 NoBarrier_AtomicIncrement(volatile Atomic32* ptr,
                                           Atomic32 increment) {
   return Barrier_AtomicIncrement(ptr, increment);
 }
 
-#if !(defined(_MSC_VER) && _MSC_VER >= 1400)
-#error "We require at least vs2005 for MemoryBarrier"
-#endif
 inline void MemoryBarrier() {
 #if defined(ARCH_CPU_64_BITS)
   // See #undef and note at the top of this file.
   __faststorefence();
 #else
   // We use MemoryBarrier from WinNT.h
   ::MemoryBarrier();
 #endif
@@ -107,17 +105,17 @@ inline Atomic32 Release_Load(volatile co
   MemoryBarrier();
   return *ptr;
 }
 
 #if defined(_WIN64)
 
 // 64-bit low-level operations on 64-bit platform.
 
-COMPILE_ASSERT(sizeof(Atomic64) == sizeof(PVOID), atomic_word_is_atomic);
+static_assert(sizeof(Atomic64) == sizeof(PVOID), "atomic word is atomic");
 
 inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
                                          Atomic64 old_value,
                                          Atomic64 new_value) {
   PVOID result = InterlockedCompareExchangePointer(
     reinterpret_cast<volatile PVOID*>(ptr),
     reinterpret_cast<PVOID>(new_value), reinterpret_cast<PVOID>(old_value));
   return reinterpret_cast<Atomic64>(result);
@@ -187,12 +185,12 @@ inline Atomic64 Release_CompareAndSwap(v
                                        Atomic64 old_value,
                                        Atomic64 new_value) {
   return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
 }
 
 
 #endif  // defined(_WIN64)
 
-}  // namespace base::subtle
+}  // namespace subtle
 }  // namespace base
 
 #endif  // BASE_ATOMICOPS_INTERNALS_X86_MSVC_H_
--- a/security/sandbox/chromium/base/base_export.h
+++ b/security/sandbox/chromium/base/base_export.h
@@ -5,30 +5,25 @@
 #ifndef BASE_BASE_EXPORT_H_
 #define BASE_BASE_EXPORT_H_
 
 #if defined(COMPONENT_BUILD)
 #if defined(WIN32)
 
 #if defined(BASE_IMPLEMENTATION)
 #define BASE_EXPORT __declspec(dllexport)
-#define BASE_EXPORT_PRIVATE __declspec(dllexport)
 #else
 #define BASE_EXPORT __declspec(dllimport)
-#define BASE_EXPORT_PRIVATE __declspec(dllimport)
 #endif  // defined(BASE_IMPLEMENTATION)
 
 #else  // defined(WIN32)
 #if defined(BASE_IMPLEMENTATION)
 #define BASE_EXPORT __attribute__((visibility("default")))
-#define BASE_EXPORT_PRIVATE __attribute__((visibility("default")))
 #else
 #define BASE_EXPORT
-#define BASE_EXPORT_PRIVATE
 #endif  // defined(BASE_IMPLEMENTATION)
 #endif
 
 #else  // defined(COMPONENT_BUILD)
 #define BASE_EXPORT
-#define BASE_EXPORT_PRIVATE
 #endif
 
 #endif  // BASE_BASE_EXPORT_H_
--- a/security/sandbox/chromium/base/base_paths_win.h
+++ b/security/sandbox/chromium/base/base_paths_win.h
@@ -1,28 +1,34 @@
 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-#ifndef BASE_BASE_PATHS_WIN_H__
-#define BASE_BASE_PATHS_WIN_H__
+#ifndef BASE_BASE_PATHS_WIN_H_
+#define BASE_BASE_PATHS_WIN_H_
 
 // This file declares windows-specific path keys for the base module.
 // These can be used with the PathService to access various special
 // directories and files.
 
 namespace base {
 
 enum {
   PATH_WIN_START = 100,
 
   DIR_WINDOWS,  // Windows directory, usually "c:\windows"
   DIR_SYSTEM,   // Usually c:\windows\system32"
-  DIR_PROGRAM_FILES,      // Usually c:\program files
-  DIR_PROGRAM_FILESX86,   // Usually c:\program files or c:\program files (x86)
+  //                         32-bit     32-bit on 64-bit   64-bit on 64-bit
+  // DIR_PROGRAM_FILES         1               2                  1
+  // DIR_PROGRAM_FILESX86      1               2                  2
+  // DIR_PROGRAM_FILES6432     1               1                  1
+  // 1 - C:\Program Files   2 - C:\Program Files (x86)
+  DIR_PROGRAM_FILES,      // See table above.
+  DIR_PROGRAM_FILESX86,   // See table above.
+  DIR_PROGRAM_FILES6432,  // See table above.
 
   DIR_IE_INTERNET_CACHE,  // Temporary Internet Files directory.
   DIR_COMMON_START_MENU,  // Usually "C:\Documents and Settings\All Users\
                           // Start Menu\Programs"
   DIR_START_MENU,         // Usually "C:\Documents and Settings\<user>\
                           // Start Menu\Programs"
   DIR_APP_DATA,           // Application Data directory under the user profile.
   DIR_LOCAL_APP_DATA,     // "Local Settings\Application Data" directory under
@@ -31,18 +37,18 @@ enum {
                           // All Users\Application Data".
                           // Vista, W2K8 and above: "C:\ProgramData".
   DIR_APP_SHORTCUTS,      // Where tiles on the start screen are stored, only
                           // for Windows 8. Maps to "Local\AppData\Microsoft\
                           // Windows\Application Shortcuts\".
   DIR_COMMON_DESKTOP,     // Directory for the common desktop (visible
                           // on all user's Desktop).
   DIR_USER_QUICK_LAUNCH,  // Directory for the quick launch shortcuts.
-  DIR_TASKBAR_PINS,       // Directory for the shortcuts pinned to taskbar via
-                          // base::win::TaskbarPinShortcutLink().
+  DIR_TASKBAR_PINS,       // Directory for the shortcuts pinned to taskbar
+                          // (Win7-8) via base::win::PinShortcutToTaskbar().
   DIR_WINDOWS_FONTS,      // Usually C:\Windows\Fonts.
 
   PATH_WIN_END
 };
 
 }  // namespace base
 
-#endif  // BASE_BASE_PATHS_WIN_H__
+#endif  // BASE_BASE_PATHS_WIN_H_
--- a/security/sandbox/chromium/base/base_switches.cc
+++ b/security/sandbox/chromium/base/base_switches.cc
@@ -1,31 +1,48 @@
 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
 #include "base/base_switches.h"
+#include "build/build_config.h"
 
 namespace switches {
 
 // Disables the crash reporting.
 const char kDisableBreakpad[]               = "disable-breakpad";
 
 // Indicates that crash reporting should be enabled. On platforms where helper
 // processes cannot access to files needed to make this decision, this flag is
 // generated internally.
 const char kEnableCrashReporter[]           = "enable-crash-reporter";
 
+// Makes memory allocators keep track of their allocations and context, so a
+// detailed breakdown of memory usage can be presented in chrome://tracing when
+// the memory-infra category is enabled.
+const char kEnableHeapProfiling[]           = "enable-heap-profiling";
+
 // Generates full memory crash dump.
 const char kFullMemoryCrashReport[]         = "full-memory-crash-report";
 
-// Force low-end device when set to 1;
-// Auto-detect low-end device when set to 2;
-// Force non-low-end device when set to other values or empty;
-const char kLowEndDeviceMode[]              = "low-end-device-mode";
+// Force low-end device mode when set.
+const char kEnableLowEndDeviceMode[]        = "enable-low-end-device-mode";
+
+// Force disabling of low-end device mode when set.
+const char kDisableLowEndDeviceMode[]       = "disable-low-end-device-mode";
+
+// This option can be used to force field trials when testing changes locally.
+// The argument is a list of name and value pairs, separated by slashes. If a
+// trial name is prefixed with an asterisk, that trial will start activated.
+// For example, the following argument defines two trials, with the second one
+// activated: "GoogleNow/Enable/*MaterialDesignNTP/Default/" This option can
+// also be used by the browser process to send the list of trials to a
+// non-browser process, using the same format. See
+// FieldTrialList::CreateTrialsFromString() in field_trial.h for details.
+const char kForceFieldTrials[]              = "force-fieldtrials";
 
 // Suppresses all error dialogs when present.
 const char kNoErrorDialogs[]                = "noerrdialogs";
 
 // When running certain tests that spawn child processes, this switch indicates
 // to the test framework that the current process is a child process.
 const char kTestChildProcess[]              = "test-child-process";
 
@@ -42,35 +59,37 @@ const char kV[]                         
 // against the whole pathname and not just the module.  E.g.,
 // "*/foo/bar/*=2" would change the logging level for all code in
 // source files under a "foo/bar" directory.
 const char kVModule[]                       = "vmodule";
 
 // Will wait for 60 seconds for a debugger to come to attach to the process.
 const char kWaitForDebugger[]               = "wait-for-debugger";
 
-// Sends a pretty-printed version of tracing info to the console.
-const char kTraceToConsole[]                = "trace-to-console";
-
 // Sends trace events from these categories to a file.
 // --trace-to-file on its own sends to default categories.
 const char kTraceToFile[]                   = "trace-to-file";
 
 // Specifies the file name for --trace-to-file. If unspecified, it will
 // go to a default file name.
 const char kTraceToFileName[]               = "trace-to-file-name";
 
 // Configure whether chrome://profiler will contain timing information. This
 // option is enabled by default. A value of "0" will disable profiler timing,
 // while all other values will enable it.
 const char kProfilerTiming[]                = "profiler-timing";
 // Value of the --profiler-timing flag that will disable timing information for
 // chrome://profiler.
 const char kProfilerTimingDisabledValue[]   = "0";
 
+#if defined(OS_WIN)
+// Disables the USB keyboard detection for blocking the OSK on Win8+.
+const char kDisableUsbKeyboardDetect[]      = "disable-usb-keyboard-detect";
+#endif
+
 #if defined(OS_POSIX)
 // Used for turning on Breakpad crash reporting in a debug environment where
 // crash reporting is typically compiled but disabled.
 const char kEnableCrashReporterForTesting[] =
     "enable-crash-reporter-for-testing";
 #endif
 
 }  // namespace switches
--- a/security/sandbox/chromium/base/base_switches.h
+++ b/security/sandbox/chromium/base/base_switches.h
@@ -7,29 +7,35 @@
 #ifndef BASE_BASE_SWITCHES_H_
 #define BASE_BASE_SWITCHES_H_
 
 #include "build/build_config.h"
 
 namespace switches {
 
 extern const char kDisableBreakpad[];
+extern const char kDisableLowEndDeviceMode[];
 extern const char kEnableCrashReporter[];
+extern const char kEnableHeapProfiling[];
+extern const char kEnableLowEndDeviceMode[];
+extern const char kForceFieldTrials[];
 extern const char kFullMemoryCrashReport[];
-extern const char kLowEndDeviceMode[];
 extern const char kNoErrorDialogs[];
 extern const char kProfilerTiming[];
 extern const char kProfilerTimingDisabledValue[];
 extern const char kTestChildProcess[];
-extern const char kTraceToConsole[];
 extern const char kTraceToFile[];
 extern const char kTraceToFileName[];
 extern const char kV[];
 extern const char kVModule[];
 extern const char kWaitForDebugger[];
 
+#if defined(OS_WIN)
+extern const char kDisableUsbKeyboardDetect[];
+#endif
+
 #if defined(OS_POSIX)
 extern const char kEnableCrashReporterForTesting[];
 #endif
 
 }  // namespace switches
 
 #endif  // BASE_BASE_SWITCHES_H_
deleted file mode 100644
--- a/security/sandbox/chromium/base/basictypes.h
+++ /dev/null
@@ -1,45 +0,0 @@
-// Copyright 2013 The Chromium Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style license that can be
-// found in the LICENSE file.
-
-// This file contains definitions of our old basic integral types
-// ((u)int{8,16,32,64}) and further includes. I recommend that you use the C99
-// standard types instead, and include <stdint.h>/<stddef.h>/etc. as needed.
-// Note that the macros and macro-like constructs that were formerly defined in
-// this file are now available separately in base/macros.h.
-
-#ifndef BASE_BASICTYPES_H_
-#define BASE_BASICTYPES_H_
-
-#include <limits.h>  // So we can set the bounds of our types.
-#include <stddef.h>  // For size_t.
-#include <stdint.h>  // For intptr_t.
-
-#include "base/macros.h"
-#include "base/port.h"  // Types that only need exist on certain systems.
-
-// DEPRECATED: Please use (u)int{8,16,32,64}_t instead (and include <stdint.h>).
-typedef int8_t int8;
-typedef uint8_t uint8;
-typedef int16_t int16;
-typedef uint16_t uint16;
-typedef int32_t int32;
-typedef uint32_t uint32;
-typedef int64_t int64;
-typedef uint64_t uint64;
-
-// DEPRECATED: Please use std::numeric_limits (from <limits>) instead.
-const uint8  kuint8max  =  0xFF;
-const uint16 kuint16max =  0xFFFF;
-const uint32 kuint32max =  0xFFFFFFFF;
-const uint64 kuint64max =  0xFFFFFFFFFFFFFFFFULL;
-const  int8  kint8min   = -0x7F - 1;
-const  int8  kint8max   =  0x7F;
-const  int16 kint16min  = -0x7FFF - 1;
-const  int16 kint16max  =  0x7FFF;
-const  int32 kint32min  = -0x7FFFFFFF - 1;
-const  int32 kint32max  =  0x7FFFFFFF;
-const  int64 kint64min  = -0x7FFFFFFFFFFFFFFFLL - 1;
-const  int64 kint64max  =  0x7FFFFFFFFFFFFFFFLL;
-
-#endif  // BASE_BASICTYPES_H_
--- a/security/sandbox/chromium/base/bind.h
+++ b/security/sandbox/chromium/base/bind.h
@@ -1,13 +1,8 @@
-// This file was GENERATED by command:
-//     pump.py bind.h.pump
-// DO NOT EDIT BY HAND!!!
-
-
 // Copyright (c) 2011 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 BASE_BIND_H_
 #define BASE_BIND_H_
 
 #include "base/bind_internal.h"
@@ -41,471 +36,66 @@
 // function_type is one of {function, method, const_method} would require
 // one specialization.  We eventually have to do a similar number of
 // specializations anyways in the implementation (see the Invoker<>,
 // classes).  However, it is avoidable in Bind if we return the result
 // via an indirection like we do below.
 //
 // TODO(ajwong): We might be able to avoid this now, but need to test.
 //
-// It is possible to move most of the COMPILE_ASSERT asserts into BindState<>,
-// but it feels a little nicer to have the asserts here so people do not
-// need to crack open bind_internal.h.  On the other hand, it makes Bind()
-// harder to read.
+// It is possible to move most of the static_assert into BindState<>, but it
+// feels a little nicer to have the asserts here so people do not need to crack
+// open bind_internal.h.  On the other hand, it makes Bind() harder to read.
 
 namespace base {
 
-template <typename Functor>
-base::Callback<
-    typename internal::BindState<
-        typename internal::FunctorTraits<Functor>::RunnableType,
-        typename internal::FunctorTraits<Functor>::RunType,
-        void()>
-            ::UnboundRunType>
-Bind(Functor functor) {
-  // Typedefs for how to store and run the functor.
-  typedef typename internal::FunctorTraits<Functor>::RunnableType RunnableType;
-  typedef typename internal::FunctorTraits<Functor>::RunType RunType;
-
-  typedef internal::BindState<RunnableType, RunType, void()> BindState;
-
-
-  return Callback<typename BindState::UnboundRunType>(
-      new BindState(internal::MakeRunnable(functor)));
-}
-
-template <typename Functor, typename P1>
-base::Callback<
-    typename internal::BindState<
-        typename internal::FunctorTraits<Functor>::RunnableType,
-        typename internal::FunctorTraits<Functor>::RunType,
-        void(typename internal::CallbackParamTraits<P1>::StorageType)>
-            ::UnboundRunType>
-Bind(Functor functor, const P1& p1) {
-  // Typedefs for how to store and run the functor.
-  typedef typename internal::FunctorTraits<Functor>::RunnableType RunnableType;
-  typedef typename internal::FunctorTraits<Functor>::RunType RunType;
-
-  // Use RunnableType::RunType instead of RunType above because our
-  // checks should below for bound references need to know what the actual
-  // functor is going to interpret the argument as.
-  typedef internal::FunctionTraits<typename RunnableType::RunType>
-      BoundFunctorTraits;
-
-  // Do not allow binding a non-const reference parameter. Non-const reference
-  // parameters are disallowed by the Google style guide.  Also, binding a
-  // non-const reference parameter can make for subtle bugs because the
-  // invoked function will receive a reference to the stored copy of the
-  // argument and not the original.
-  COMPILE_ASSERT(
-      !(is_non_const_reference<typename BoundFunctorTraits::A1Type>::value ),
-      do_not_bind_functions_with_nonconst_ref);
-
-  // For methods, we need to be careful for parameter 1.  We do not require
-  // a scoped_refptr because BindState<> itself takes care of AddRef() for
-  // methods. We also disallow binding of an array as the method's target
-  // object.
-  COMPILE_ASSERT(
-      internal::HasIsMethodTag<RunnableType>::value ||
-          !internal::NeedsScopedRefptrButGetsRawPtr<P1>::value,
-      p1_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::HasIsMethodTag<RunnableType>::value ||
-                     !is_array<P1>::value,
-                 first_bound_argument_to_method_cannot_be_array);
-  typedef internal::BindState<RunnableType, RunType,
-      void(typename internal::CallbackParamTraits<P1>::StorageType)> BindState;
-
-
-  return Callback<typename BindState::UnboundRunType>(
-      new BindState(internal::MakeRunnable(functor), p1));
-}
-
-template <typename Functor, typename P1, typename P2>
+template <typename Functor, typename... Args>
 base::Callback<
     typename internal::BindState<
         typename internal::FunctorTraits<Functor>::RunnableType,
         typename internal::FunctorTraits<Functor>::RunType,
-        void(typename internal::CallbackParamTraits<P1>::StorageType,
-            typename internal::CallbackParamTraits<P2>::StorageType)>
+        typename internal::CallbackParamTraits<Args>::StorageType...>
             ::UnboundRunType>
-Bind(Functor functor, const P1& p1, const P2& p2) {
-  // Typedefs for how to store and run the functor.
-  typedef typename internal::FunctorTraits<Functor>::RunnableType RunnableType;
-  typedef typename internal::FunctorTraits<Functor>::RunType RunType;
-
-  // Use RunnableType::RunType instead of RunType above because our
-  // checks should below for bound references need to know what the actual
-  // functor is going to interpret the argument as.
-  typedef internal::FunctionTraits<typename RunnableType::RunType>
-      BoundFunctorTraits;
-
-  // Do not allow binding a non-const reference parameter. Non-const reference
-  // parameters are disallowed by the Google style guide.  Also, binding a
-  // non-const reference parameter can make for subtle bugs because the
-  // invoked function will receive a reference to the stored copy of the
-  // argument and not the original.
-  COMPILE_ASSERT(
-      !(is_non_const_reference<typename BoundFunctorTraits::A1Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A2Type>::value ),
-      do_not_bind_functions_with_nonconst_ref);
-
-  // For methods, we need to be careful for parameter 1.  We do not require
-  // a scoped_refptr because BindState<> itself takes care of AddRef() for
-  // methods. We also disallow binding of an array as the method's target
-  // object.
-  COMPILE_ASSERT(
-      internal::HasIsMethodTag<RunnableType>::value ||
-          !internal::NeedsScopedRefptrButGetsRawPtr<P1>::value,
-      p1_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::HasIsMethodTag<RunnableType>::value ||
-                     !is_array<P1>::value,
-                 first_bound_argument_to_method_cannot_be_array);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P2>::value,
-                 p2_is_refcounted_type_and_needs_scoped_refptr);
-  typedef internal::BindState<RunnableType, RunType,
-      void(typename internal::CallbackParamTraits<P1>::StorageType,
-      typename internal::CallbackParamTraits<P2>::StorageType)> BindState;
-
-
-  return Callback<typename BindState::UnboundRunType>(
-      new BindState(internal::MakeRunnable(functor), p1, p2));
-}
-
-template <typename Functor, typename P1, typename P2, typename P3>
-base::Callback<
-    typename internal::BindState<
-        typename internal::FunctorTraits<Functor>::RunnableType,
-        typename internal::FunctorTraits<Functor>::RunType,
-        void(typename internal::CallbackParamTraits<P1>::StorageType,
-            typename internal::CallbackParamTraits<P2>::StorageType,
-            typename internal::CallbackParamTraits<P3>::StorageType)>
-            ::UnboundRunType>
-Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3) {
-  // Typedefs for how to store and run the functor.
-  typedef typename internal::FunctorTraits<Functor>::RunnableType RunnableType;
-  typedef typename internal::FunctorTraits<Functor>::RunType RunType;
+Bind(Functor functor, const Args&... args) {
+  // Type aliases for how to store and run the functor.
+  using RunnableType = typename internal::FunctorTraits<Functor>::RunnableType;
+  using RunType = typename internal::FunctorTraits<Functor>::RunType;
 
   // Use RunnableType::RunType instead of RunType above because our
-  // checks should below for bound references need to know what the actual
+  // checks below for bound references need to know what the actual
   // functor is going to interpret the argument as.
-  typedef internal::FunctionTraits<typename RunnableType::RunType>
-      BoundFunctorTraits;
-
-  // Do not allow binding a non-const reference parameter. Non-const reference
-  // parameters are disallowed by the Google style guide.  Also, binding a
-  // non-const reference parameter can make for subtle bugs because the
-  // invoked function will receive a reference to the stored copy of the
-  // argument and not the original.
-  COMPILE_ASSERT(
-      !(is_non_const_reference<typename BoundFunctorTraits::A1Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A2Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A3Type>::value ),
-      do_not_bind_functions_with_nonconst_ref);
+  using BoundRunType = typename RunnableType::RunType;
 
-  // For methods, we need to be careful for parameter 1.  We do not require
-  // a scoped_refptr because BindState<> itself takes care of AddRef() for
-  // methods. We also disallow binding of an array as the method's target
-  // object.
-  COMPILE_ASSERT(
-      internal::HasIsMethodTag<RunnableType>::value ||
-          !internal::NeedsScopedRefptrButGetsRawPtr<P1>::value,
-      p1_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::HasIsMethodTag<RunnableType>::value ||
-                     !is_array<P1>::value,
-                 first_bound_argument_to_method_cannot_be_array);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P2>::value,
-                 p2_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P3>::value,
-                 p3_is_refcounted_type_and_needs_scoped_refptr);
-  typedef internal::BindState<RunnableType, RunType,
-      void(typename internal::CallbackParamTraits<P1>::StorageType,
-      typename internal::CallbackParamTraits<P2>::StorageType,
-      typename internal::CallbackParamTraits<P3>::StorageType)> BindState;
-
-
-  return Callback<typename BindState::UnboundRunType>(
-      new BindState(internal::MakeRunnable(functor), p1, p2, p3));
-}
-
-template <typename Functor, typename P1, typename P2, typename P3, typename P4>
-base::Callback<
-    typename internal::BindState<
-        typename internal::FunctorTraits<Functor>::RunnableType,
-        typename internal::FunctorTraits<Functor>::RunType,
-        void(typename internal::CallbackParamTraits<P1>::StorageType,
-            typename internal::CallbackParamTraits<P2>::StorageType,
-            typename internal::CallbackParamTraits<P3>::StorageType,
-            typename internal::CallbackParamTraits<P4>::StorageType)>
-            ::UnboundRunType>
-Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4) {
-  // Typedefs for how to store and run the functor.
-  typedef typename internal::FunctorTraits<Functor>::RunnableType RunnableType;
-  typedef typename internal::FunctorTraits<Functor>::RunType RunType;
-
-  // Use RunnableType::RunType instead of RunType above because our
-  // checks should below for bound references need to know what the actual
-  // functor is going to interpret the argument as.
-  typedef internal::FunctionTraits<typename RunnableType::RunType>
-      BoundFunctorTraits;
+  using BoundArgs =
+      internal::TakeTypeListItem<sizeof...(Args),
+                                 internal::ExtractArgs<BoundRunType>>;
 
   // Do not allow binding a non-const reference parameter. Non-const reference
   // parameters are disallowed by the Google style guide.  Also, binding a
   // non-const reference parameter can make for subtle bugs because the
   // invoked function will receive a reference to the stored copy of the
   // argument and not the original.
-  COMPILE_ASSERT(
-      !(is_non_const_reference<typename BoundFunctorTraits::A1Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A2Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A3Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A4Type>::value ),
-      do_not_bind_functions_with_nonconst_ref);
-
-  // For methods, we need to be careful for parameter 1.  We do not require
-  // a scoped_refptr because BindState<> itself takes care of AddRef() for
-  // methods. We also disallow binding of an array as the method's target
-  // object.
-  COMPILE_ASSERT(
-      internal::HasIsMethodTag<RunnableType>::value ||
-          !internal::NeedsScopedRefptrButGetsRawPtr<P1>::value,
-      p1_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::HasIsMethodTag<RunnableType>::value ||
-                     !is_array<P1>::value,
-                 first_bound_argument_to_method_cannot_be_array);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P2>::value,
-                 p2_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P3>::value,
-                 p3_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P4>::value,
-                 p4_is_refcounted_type_and_needs_scoped_refptr);
-  typedef internal::BindState<RunnableType, RunType,
-      void(typename internal::CallbackParamTraits<P1>::StorageType,
-      typename internal::CallbackParamTraits<P2>::StorageType,
-      typename internal::CallbackParamTraits<P3>::StorageType,
-      typename internal::CallbackParamTraits<P4>::StorageType)> BindState;
-
-
-  return Callback<typename BindState::UnboundRunType>(
-      new BindState(internal::MakeRunnable(functor), p1, p2, p3, p4));
-}
+  static_assert(!internal::HasNonConstReferenceItem<BoundArgs>::value,
+                "do not bind functions with nonconst ref");
 
-template <typename Functor, typename P1, typename P2, typename P3, typename P4,
-    typename P5>
-base::Callback<
-    typename internal::BindState<
-        typename internal::FunctorTraits<Functor>::RunnableType,
-        typename internal::FunctorTraits<Functor>::RunType,
-        void(typename internal::CallbackParamTraits<P1>::StorageType,
-            typename internal::CallbackParamTraits<P2>::StorageType,
-            typename internal::CallbackParamTraits<P3>::StorageType,
-            typename internal::CallbackParamTraits<P4>::StorageType,
-            typename internal::CallbackParamTraits<P5>::StorageType)>
-            ::UnboundRunType>
-Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4,
-    const P5& p5) {
-  // Typedefs for how to store and run the functor.
-  typedef typename internal::FunctorTraits<Functor>::RunnableType RunnableType;
-  typedef typename internal::FunctorTraits<Functor>::RunType RunType;
-
-  // Use RunnableType::RunType instead of RunType above because our
-  // checks should below for bound references need to know what the actual
-  // functor is going to interpret the argument as.
-  typedef internal::FunctionTraits<typename RunnableType::RunType>
-      BoundFunctorTraits;
-
-  // Do not allow binding a non-const reference parameter. Non-const reference
-  // parameters are disallowed by the Google style guide.  Also, binding a
-  // non-const reference parameter can make for subtle bugs because the
-  // invoked function will receive a reference to the stored copy of the
-  // argument and not the original.
-  COMPILE_ASSERT(
-      !(is_non_const_reference<typename BoundFunctorTraits::A1Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A2Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A3Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A4Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A5Type>::value ),
-      do_not_bind_functions_with_nonconst_ref);
+  const bool is_method = internal::HasIsMethodTag<RunnableType>::value;
 
   // For methods, we need to be careful for parameter 1.  We do not require
   // a scoped_refptr because BindState<> itself takes care of AddRef() for
   // methods. We also disallow binding of an array as the method's target
   // object.
-  COMPILE_ASSERT(
-      internal::HasIsMethodTag<RunnableType>::value ||
-          !internal::NeedsScopedRefptrButGetsRawPtr<P1>::value,
-      p1_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::HasIsMethodTag<RunnableType>::value ||
-                     !is_array<P1>::value,
-                 first_bound_argument_to_method_cannot_be_array);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P2>::value,
-                 p2_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P3>::value,
-                 p3_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P4>::value,
-                 p4_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P5>::value,
-                 p5_is_refcounted_type_and_needs_scoped_refptr);
-  typedef internal::BindState<RunnableType, RunType,
-      void(typename internal::CallbackParamTraits<P1>::StorageType,
-      typename internal::CallbackParamTraits<P2>::StorageType,
-      typename internal::CallbackParamTraits<P3>::StorageType,
-      typename internal::CallbackParamTraits<P4>::StorageType,
-      typename internal::CallbackParamTraits<P5>::StorageType)> BindState;
+  static_assert(!internal::BindsArrayToFirstArg<is_method, Args...>::value,
+                "first bound argument to method cannot be array");
+  static_assert(
+      !internal::HasRefCountedParamAsRawPtr<is_method, Args...>::value,
+      "a parameter is a refcounted type and needs scoped_refptr");
 
+  using BindState = internal::BindState<
+      RunnableType, RunType,
+      typename internal::CallbackParamTraits<Args>::StorageType...>;
 
   return Callback<typename BindState::UnboundRunType>(
-      new BindState(internal::MakeRunnable(functor), p1, p2, p3, p4, p5));
-}
-
-template <typename Functor, typename P1, typename P2, typename P3, typename P4,
-    typename P5, typename P6>
-base::Callback<
-    typename internal::BindState<
-        typename internal::FunctorTraits<Functor>::RunnableType,
-        typename internal::FunctorTraits<Functor>::RunType,
-        void(typename internal::CallbackParamTraits<P1>::StorageType,
-            typename internal::CallbackParamTraits<P2>::StorageType,
-            typename internal::CallbackParamTraits<P3>::StorageType,
-            typename internal::CallbackParamTraits<P4>::StorageType,
-            typename internal::CallbackParamTraits<P5>::StorageType,
-            typename internal::CallbackParamTraits<P6>::StorageType)>
-            ::UnboundRunType>
-Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4,
-    const P5& p5, const P6& p6) {
-  // Typedefs for how to store and run the functor.
-  typedef typename internal::FunctorTraits<Functor>::RunnableType RunnableType;
-  typedef typename internal::FunctorTraits<Functor>::RunType RunType;
-
-  // Use RunnableType::RunType instead of RunType above because our
-  // checks should below for bound references need to know what the actual
-  // functor is going to interpret the argument as.
-  typedef internal::FunctionTraits<typename RunnableType::RunType>
-      BoundFunctorTraits;
-
-  // Do not allow binding a non-const reference parameter. Non-const reference
-  // parameters are disallowed by the Google style guide.  Also, binding a
-  // non-const reference parameter can make for subtle bugs because the
-  // invoked function will receive a reference to the stored copy of the
-  // argument and not the original.
-  COMPILE_ASSERT(
-      !(is_non_const_reference<typename BoundFunctorTraits::A1Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A2Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A3Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A4Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A5Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A6Type>::value ),
-      do_not_bind_functions_with_nonconst_ref);
-
-  // For methods, we need to be careful for parameter 1.  We do not require
-  // a scoped_refptr because BindState<> itself takes care of AddRef() for
-  // methods. We also disallow binding of an array as the method's target
-  // object.
-  COMPILE_ASSERT(
-      internal::HasIsMethodTag<RunnableType>::value ||
-          !internal::NeedsScopedRefptrButGetsRawPtr<P1>::value,
-      p1_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::HasIsMethodTag<RunnableType>::value ||
-                     !is_array<P1>::value,
-                 first_bound_argument_to_method_cannot_be_array);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P2>::value,
-                 p2_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P3>::value,
-                 p3_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P4>::value,
-                 p4_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P5>::value,
-                 p5_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P6>::value,
-                 p6_is_refcounted_type_and_needs_scoped_refptr);
-  typedef internal::BindState<RunnableType, RunType,
-      void(typename internal::CallbackParamTraits<P1>::StorageType,
-      typename internal::CallbackParamTraits<P2>::StorageType,
-      typename internal::CallbackParamTraits<P3>::StorageType,
-      typename internal::CallbackParamTraits<P4>::StorageType,
-      typename internal::CallbackParamTraits<P5>::StorageType,
-      typename internal::CallbackParamTraits<P6>::StorageType)> BindState;
-
-
-  return Callback<typename BindState::UnboundRunType>(
-      new BindState(internal::MakeRunnable(functor), p1, p2, p3, p4, p5, p6));
-}
-
-template <typename Functor, typename P1, typename P2, typename P3, typename P4,
-    typename P5, typename P6, typename P7>
-base::Callback<
-    typename internal::BindState<
-        typename internal::FunctorTraits<Functor>::RunnableType,
-        typename internal::FunctorTraits<Functor>::RunType,
-        void(typename internal::CallbackParamTraits<P1>::StorageType,
-            typename internal::CallbackParamTraits<P2>::StorageType,
-            typename internal::CallbackParamTraits<P3>::StorageType,
-            typename internal::CallbackParamTraits<P4>::StorageType,
-            typename internal::CallbackParamTraits<P5>::StorageType,
-            typename internal::CallbackParamTraits<P6>::StorageType,
-            typename internal::CallbackParamTraits<P7>::StorageType)>
-            ::UnboundRunType>
-Bind(Functor functor, const P1& p1, const P2& p2, const P3& p3, const P4& p4,
-    const P5& p5, const P6& p6, const P7& p7) {
-  // Typedefs for how to store and run the functor.
-  typedef typename internal::FunctorTraits<Functor>::RunnableType RunnableType;
-  typedef typename internal::FunctorTraits<Functor>::RunType RunType;
-
-  // Use RunnableType::RunType instead of RunType above because our
-  // checks should below for bound references need to know what the actual
-  // functor is going to interpret the argument as.
-  typedef internal::FunctionTraits<typename RunnableType::RunType>
-      BoundFunctorTraits;
-
-  // Do not allow binding a non-const reference parameter. Non-const reference
-  // parameters are disallowed by the Google style guide.  Also, binding a
-  // non-const reference parameter can make for subtle bugs because the
-  // invoked function will receive a reference to the stored copy of the
-  // argument and not the original.
-  COMPILE_ASSERT(
-      !(is_non_const_reference<typename BoundFunctorTraits::A1Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A2Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A3Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A4Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A5Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A6Type>::value ||
-          is_non_const_reference<typename BoundFunctorTraits::A7Type>::value ),
-      do_not_bind_functions_with_nonconst_ref);
-
-  // For methods, we need to be careful for parameter 1.  We do not require
-  // a scoped_refptr because BindState<> itself takes care of AddRef() for
-  // methods. We also disallow binding of an array as the method's target
-  // object.
-  COMPILE_ASSERT(
-      internal::HasIsMethodTag<RunnableType>::value ||
-          !internal::NeedsScopedRefptrButGetsRawPtr<P1>::value,
-      p1_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::HasIsMethodTag<RunnableType>::value ||
-                     !is_array<P1>::value,
-                 first_bound_argument_to_method_cannot_be_array);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P2>::value,
-                 p2_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P3>::value,
-                 p3_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P4>::value,
-                 p4_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P5>::value,
-                 p5_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P6>::value,
-                 p6_is_refcounted_type_and_needs_scoped_refptr);
-  COMPILE_ASSERT(!internal::NeedsScopedRefptrButGetsRawPtr<P7>::value,
-                 p7_is_refcounted_type_and_needs_scoped_refptr);
-  typedef internal::BindState<RunnableType, RunType,
-      void(typename internal::CallbackParamTraits<P1>::StorageType,
-      typename internal::CallbackParamTraits<P2>::StorageType,
-      typename internal::CallbackParamTraits<P3>::StorageType,
-      typename internal::CallbackParamTraits<P4>::StorageType,
-      typename internal::CallbackParamTraits<P5>::StorageType,
-      typename internal::CallbackParamTraits<P6>::StorageType,
-      typename internal::CallbackParamTraits<P7>::StorageType)> BindState;
-
-
-  return Callback<typename BindState::UnboundRunType>(
-      new BindState(internal::MakeRunnable(functor), p1, p2, p3, p4, p5, p6,
-          p7));
+      new BindState(internal::MakeRunnable(functor), args...));
 }
 
 }  // namespace base
 
 #endif  // BASE_BIND_H_
--- a/security/sandbox/chromium/base/bind_helpers.h
+++ b/security/sandbox/chromium/base/bind_helpers.h
@@ -106,17 +106,17 @@
 // EXAMPLE OF Passed():
 //
 //   void TakesOwnership(scoped_ptr<Foo> arg) { }
 //   scoped_ptr<Foo> CreateFoo() { return scoped_ptr<Foo>(new Foo()); }
 //
 //   scoped_ptr<Foo> f(new Foo());
 //
 //   // |cb| is given ownership of Foo(). |f| is now NULL.
-//   // You can use f.Pass() in place of &f, but it's more verbose.
+//   // You can use std::move(f) in place of &f, but it's more verbose.
 //   Closure cb = Bind(&TakesOwnership, Passed(&f));
 //
 //   // Run was never called so |cb| still owns Foo() and deletes
 //   // it on Reset().
 //   cb.Reset();
 //
 //   // |cb| is given a new Foo created by CreateFoo().
 //   cb = Bind(&TakesOwnership, Passed(CreateFoo()));
@@ -124,34 +124,39 @@
 //   // |arg| in TakesOwnership() is given ownership of Foo(). |cb|
 //   // no longer owns Foo() and, if reset, would not delete Foo().
 //   cb.Run();  // Foo() is now transferred to |arg| and deleted.
 //   cb.Run();  // This CHECK()s since Foo() already been used once.
 //
 // Passed() is particularly useful with PostTask() when you are transferring
 // ownership of an argument into a task, but don't necessarily know if the
 // task will always be executed. This can happen if the task is cancellable
-// or if it is posted to a MessageLoopProxy.
+// or if it is posted to a TaskRunner.
 //
 //
 // SIMPLE FUNCTIONS AND UTILITIES.
 //
 //   DoNothing() - Useful for creating a Closure that does nothing when called.
 //   DeletePointer<T>() - Useful for creating a Closure that will delete a
 //                        pointer when invoked. Only use this when necessary.
 //                        In most cases MessageLoop::DeleteSoon() is a better
 //                        fit.
 
 #ifndef BASE_BIND_HELPERS_H_
 #define BASE_BIND_HELPERS_H_
 
-#include "base/basictypes.h"
+#include <stddef.h>
+
+#include <type_traits>
+#include <utility>
+
 #include "base/callback.h"
 #include "base/memory/weak_ptr.h"
 #include "base/template_util.h"
+#include "build/build_config.h"
 
 namespace base {
 namespace internal {
 
 // Use the Substitution Failure Is Not An Error (SFINAE) trick to inspect T
 // for the existence of AddRef() and Release() functions of the correct
 // signature.
 //
@@ -180,17 +185,17 @@ namespace internal {
 // |value| will be false.  This formulation only checks for whether or
 // not TargetFunc exist directly in the class being introspected.
 //
 // To get around this, we play a dirty trick with multiple inheritance.
 // First, We create a class BaseMixin that declares each function that we
 // want to probe for.  Then we create a class Base that inherits from both T
 // (the class we wish to probe) and BaseMixin.  Note that the function
 // signature in BaseMixin does not need to match the signature of the function
-// we are probing for; thus it's easiest to just use void(void).
+// we are probing for; thus it's easiest to just use void().
 //
 // Now, if TargetFunc exists somewhere in T, then &Base::TargetFunc has an
 // ambiguous resolution between BaseMixin and T.  This lets us write the
 // following:
 //
 //   template <typename C>
 //   No GoodCheck(Helper<&C::TargetFunc>*);
 //
@@ -217,18 +222,18 @@ namespace internal {
 //
 // TODO(ajwong): Move to ref_counted.h or template_util.h when we've vetted
 // this works well.
 //
 // TODO(ajwong): Make this check for Release() as well.
 // See http://crbug.com/82038.
 template <typename T>
 class SupportsAddRefAndRelease {
-  typedef char Yes[1];
-  typedef char No[2];
+  using Yes = char[1];
+  using No = char[2];
 
   struct BaseMixin {
     void AddRef();
   };
 
 // MSVC warns when you try to use Base if T has a private destructor, the
 // common pattern for refcounted types. It does this even though no attempt to
 // instantiate Base is made.  We disable the warning for this definition.
@@ -237,17 +242,17 @@ class SupportsAddRefAndRelease {
 #pragma warning(disable:4624)
 #endif
   struct Base : public T, public BaseMixin {
   };
 #if defined(OS_WIN)
 #pragma warning(pop)
 #endif
 
-  template <void(BaseMixin::*)(void)> struct Helper {};
+  template <void(BaseMixin::*)()> struct Helper {};
 
   template <typename C>
   static No& Check(Helper<&C::AddRef>*);
 
   template <typename >
   static Yes& Check(...);
 
  public:
@@ -271,18 +276,18 @@ struct UnsafeBindtoRefCountedArg : false
 
 template <typename T>
 struct UnsafeBindtoRefCountedArg<T*>
     : UnsafeBindtoRefCountedArgHelper<is_class<T>::value, T> {
 };
 
 template <typename T>
 class HasIsMethodTag {
-  typedef char Yes[1];
-  typedef char No[2];
+  using Yes = char[1];
+  using No = char[2];
 
   template <typename U>
   static Yes& Check(typename U::IsMethod*);
 
   template <typename U>
   static No& Check(...);
 
  public:
@@ -354,147 +359,248 @@ class OwnedWrapper {
 // This conundrum cannot be solved without either C++11 rvalue references or
 // a O(2^n) blowup of Bind() templates to handle each combination of regular
 // types and movable-but-not-copyable types.  Thus we introduce a wrapper type
 // that is copyable to transmit the correct type information down into
 // BindState<>. Ignoring const in this type makes sense because it is only
 // created when we are explicitly trying to do a destructive move.
 //
 // Two notes:
-//  1) PassedWrapper supports any type that has a "Pass()" function.
-//     This is intentional. The whitelisting of which specific types we
-//     support is maintained by CallbackParamTraits<>.
+//  1) PassedWrapper supports any type that has a move constructor, however
+//     the type will need to be specifically whitelisted in order for it to be
+//     bound to a Callback. We guard this explicitly at the call of Passed()
+//     to make for clear errors. Things not given to Passed() will be forwarded
+//     and stored by value which will not work for general move-only types.
 //  2) is_valid_ is distinct from NULL because it is valid to bind a "NULL"
 //     scoper to a Callback and allow the Callback to execute once.
 template <typename T>
 class PassedWrapper {
  public:
-  explicit PassedWrapper(T scoper) : is_valid_(true), scoper_(scoper.Pass()) {}
+  explicit PassedWrapper(T&& scoper)
+      : is_valid_(true), scoper_(std::move(scoper)) {}
   PassedWrapper(const PassedWrapper& other)
-      : is_valid_(other.is_valid_), scoper_(other.scoper_.Pass()) {
-  }
+      : is_valid_(other.is_valid_), scoper_(std::move(other.scoper_)) {}
   T Pass() const {
     CHECK(is_valid_);
     is_valid_ = false;
-    return scoper_.Pass();
+    return std::move(scoper_);
   }
 
  private:
   mutable bool is_valid_;
   mutable T scoper_;
 };
 
 // Unwrap the stored parameters for the wrappers above.
 template <typename T>
 struct UnwrapTraits {
-  typedef const T& ForwardType;
+  using ForwardType = const T&;
   static ForwardType Unwrap(const T& o) { return o; }
 };
 
 template <typename T>
 struct UnwrapTraits<UnretainedWrapper<T> > {
-  typedef T* ForwardType;
+  using ForwardType = T*;
   static ForwardType Unwrap(UnretainedWrapper<T> unretained) {
     return unretained.get();
   }
 };
 
 template <typename T>
 struct UnwrapTraits<ConstRefWrapper<T> > {
-  typedef const T& ForwardType;
+  using ForwardType = const T&;
   static ForwardType Unwrap(ConstRefWrapper<T> const_ref) {
     return const_ref.get();
   }
 };
 
 template <typename T>
 struct UnwrapTraits<scoped_refptr<T> > {
-  typedef T* ForwardType;
+  using ForwardType = T*;
   static ForwardType Unwrap(const scoped_refptr<T>& o) { return o.get(); }
 };
 
 template <typename T>
 struct UnwrapTraits<WeakPtr<T> > {
-  typedef const WeakPtr<T>& ForwardType;
+  using ForwardType = const WeakPtr<T>&;
   static ForwardType Unwrap(const WeakPtr<T>& o) { return o; }
 };
 
 template <typename T>
 struct UnwrapTraits<OwnedWrapper<T> > {
-  typedef T* ForwardType;
+  using ForwardType = T*;
   static ForwardType Unwrap(const OwnedWrapper<T>& o) {
     return o.get();
   }
 };
 
 template <typename T>
 struct UnwrapTraits<PassedWrapper<T> > {
-  typedef T ForwardType;
+  using ForwardType = T;
   static T Unwrap(PassedWrapper<T>& o) {
     return o.Pass();
   }
 };
 
 // Utility for handling different refcounting semantics in the Bind()
 // function.
-template <bool is_method, typename T>
-struct MaybeRefcount;
+template <bool is_method, typename... T>
+struct MaybeScopedRefPtr;
 
-template <typename T>
-struct MaybeRefcount<false, T> {
-  static void AddRef(const T&) {}
-  static void Release(const T&) {}
+template <bool is_method>
+struct MaybeScopedRefPtr<is_method> {
+  MaybeScopedRefPtr() {}
+};
+
+template <typename T, typename... Rest>
+struct MaybeScopedRefPtr<false, T, Rest...> {
+  MaybeScopedRefPtr(const T&, const Rest&...) {}
 };
 
-template <typename T, size_t n>
-struct MaybeRefcount<false, T[n]> {
-  static void AddRef(const T*) {}
-  static void Release(const T*) {}
+template <typename T, size_t n, typename... Rest>
+struct MaybeScopedRefPtr<false, T[n], Rest...> {
+  MaybeScopedRefPtr(const T*, const Rest&...) {}
 };
 
-template <typename T>
-struct MaybeRefcount<true, T> {
-  static void AddRef(const T&) {}
-  static void Release(const T&) {}
+template <typename T, typename... Rest>
+struct MaybeScopedRefPtr<true, T, Rest...> {
+  MaybeScopedRefPtr(const T& o, const Rest&...) {}
 };
 
-template <typename T>
-struct MaybeRefcount<true, T*> {
-  static void AddRef(T* o) { o->AddRef(); }
-  static void Release(T* o) { o->Release(); }
+template <typename T, typename... Rest>
+struct MaybeScopedRefPtr<true, T*, Rest...> {
+  MaybeScopedRefPtr(T* o, const Rest&...) : ref_(o) {}
+  scoped_refptr<T> ref_;
 };
 
 // No need to additionally AddRef() and Release() since we are storing a
 // scoped_refptr<> inside the storage object already.
-template <typename T>
-struct MaybeRefcount<true, scoped_refptr<T> > {
-  static void AddRef(const scoped_refptr<T>& o) {}
-  static void Release(const scoped_refptr<T>& o) {}
+template <typename T, typename... Rest>
+struct MaybeScopedRefPtr<true, scoped_refptr<T>, Rest...> {
+  MaybeScopedRefPtr(const scoped_refptr<T>&, const Rest&...) {}
 };
 
-template <typename T>
-struct MaybeRefcount<true, const T*> {
-  static void AddRef(const T* o) { o->AddRef(); }
-  static void Release(const T* o) { o->Release(); }
+template <typename T, typename... Rest>
+struct MaybeScopedRefPtr<true, const T*, Rest...> {
+  MaybeScopedRefPtr(const T* o, const Rest&...) : ref_(o) {}
+  scoped_refptr<const T> ref_;
 };
 
 // IsWeakMethod is a helper that determine if we are binding a WeakPtr<> to a
 // method.  It is used internally by Bind() to select the correct
 // InvokeHelper that will no-op itself in the event the WeakPtr<> for
 // the target object is invalidated.
 //
-// P1 should be the type of the object that will be received of the method.
-template <bool IsMethod, typename P1>
+// The first argument should be the type of the object that will be received by
+// the method.
+template <bool IsMethod, typename... Args>
 struct IsWeakMethod : public false_type {};
 
-template <typename T>
-struct IsWeakMethod<true, WeakPtr<T> > : public true_type {};
+template <typename T, typename... Args>
+struct IsWeakMethod<true, WeakPtr<T>, Args...> : public true_type {};
+
+template <typename T, typename... Args>
+struct IsWeakMethod<true, ConstRefWrapper<WeakPtr<T>>, Args...>
+    : public true_type {};
+
+
+// Packs a list of types to hold them in a single type.
+template <typename... Types>
+struct TypeList {};
+
+// Used for DropTypeListItem implementation.
+template <size_t n, typename List>
+struct DropTypeListItemImpl;
+
+// Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
+template <size_t n, typename T, typename... List>
+struct DropTypeListItemImpl<n, TypeList<T, List...>>
+    : DropTypeListItemImpl<n - 1, TypeList<List...>> {};
+
+template <typename T, typename... List>
+struct DropTypeListItemImpl<0, TypeList<T, List...>> {
+  using Type = TypeList<T, List...>;
+};
+
+template <>
+struct DropTypeListItemImpl<0, TypeList<>> {
+  using Type = TypeList<>;
+};
+
+// A type-level function that drops |n| list item from given TypeList.
+template <size_t n, typename List>
+using DropTypeListItem = typename DropTypeListItemImpl<n, List>::Type;
+
+// Used for TakeTypeListItem implementation.
+template <size_t n, typename List, typename... Accum>
+struct TakeTypeListItemImpl;
+
+// Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
+template <size_t n, typename T, typename... List, typename... Accum>
+struct TakeTypeListItemImpl<n, TypeList<T, List...>, Accum...>
+    : TakeTypeListItemImpl<n - 1, TypeList<List...>, Accum..., T> {};
+
+template <typename T, typename... List, typename... Accum>
+struct TakeTypeListItemImpl<0, TypeList<T, List...>, Accum...> {
+  using Type = TypeList<Accum...>;
+};
 
-template <typename T>
-struct IsWeakMethod<true, ConstRefWrapper<WeakPtr<T> > > : public true_type {};
+template <typename... Accum>
+struct TakeTypeListItemImpl<0, TypeList<>, Accum...> {
+  using Type = TypeList<Accum...>;
+};
+
+// A type-level function that takes first |n| list item from given TypeList.
+// E.g. TakeTypeListItem<3, TypeList<A, B, C, D>> is evaluated to
+// TypeList<A, B, C>.
+template <size_t n, typename List>
+using TakeTypeListItem = typename TakeTypeListItemImpl<n, List>::Type;
+
+// Used for ConcatTypeLists implementation.
+template <typename List1, typename List2>
+struct ConcatTypeListsImpl;
+
+template <typename... Types1, typename... Types2>
+struct ConcatTypeListsImpl<TypeList<Types1...>, TypeList<Types2...>> {
+  using Type = TypeList<Types1..., Types2...>;
+};
+
+// A type-level function that concats two TypeLists.
+template <typename List1, typename List2>
+using ConcatTypeLists = typename ConcatTypeListsImpl<List1, List2>::Type;
+
+// Used for MakeFunctionType implementation.
+template <typename R, typename ArgList>
+struct MakeFunctionTypeImpl;
+
+template <typename R, typename... Args>
+struct MakeFunctionTypeImpl<R, TypeList<Args...>> {
+  // MSVC 2013 doesn't support Type Alias of function types.
+  // Revisit this after we update it to newer version.
+  typedef R Type(Args...);
+};
+
+// A type-level function that constructs a function type that has |R| as its
+// return type and has TypeLists items as its arguments.
+template <typename R, typename ArgList>
+using MakeFunctionType = typename MakeFunctionTypeImpl<R, ArgList>::Type;
+
+// Used for ExtractArgs.
+template <typename Signature>
+struct ExtractArgsImpl;
+
+template <typename R, typename... Args>
+struct ExtractArgsImpl<R(Args...)> {
+  using Type = TypeList<Args...>;
+};
+
+// A type-level function that extracts function arguments into a TypeList.
+// E.g. ExtractArgs<R(A, B, C)> is evaluated to TypeList<A, B, C>.
+template <typename Signature>
+using ExtractArgs = typename ExtractArgsImpl<Signature>::Type;
 
 }  // namespace internal
 
 template <typename T>
 static inline internal::UnretainedWrapper<T> Unretained(T* o) {
   return internal::UnretainedWrapper<T>(o);
 }
 
@@ -503,27 +609,35 @@ static inline internal::ConstRefWrapper<
   return internal::ConstRefWrapper<T>(o);
 }
 
 template <typename T>
 static inline internal::OwnedWrapper<T> Owned(T* o) {
   return internal::OwnedWrapper<T>(o);
 }
 
-// We offer 2 syntaxes for calling Passed().  The first takes a temporary and
-// is best suited for use with the return value of a function. The second
-// takes a pointer to the scoper and is just syntactic sugar to avoid having
-// to write Passed(scoper.Pass()).
-template <typename T>
-static inline internal::PassedWrapper<T> Passed(T scoper) {
-  return internal::PassedWrapper<T>(scoper.Pass());
+// We offer 2 syntaxes for calling Passed().  The first takes an rvalue and
+// is best suited for use with the return value of a function or other temporary
+// rvalues. The second takes a pointer to the scoper and is just syntactic sugar
+// to avoid having to write Passed(std::move(scoper)).
+//
+// Both versions of Passed() prevent T from being an lvalue reference. The first
+// via use of enable_if, and the second takes a T* which will not bind to T&.
+template <typename T,
+          typename std::enable_if<internal::IsMoveOnlyType<T>::value &&
+                                  !std::is_lvalue_reference<T>::value>::type* =
+              nullptr>
+static inline internal::PassedWrapper<T> Passed(T&& scoper) {
+  return internal::PassedWrapper<T>(std::move(scoper));
 }
-template <typename T>
+template <typename T,
+          typename std::enable_if<internal::IsMoveOnlyType<T>::value>::type* =
+              nullptr>
 static inline internal::PassedWrapper<T> Passed(T* scoper) {
-  return internal::PassedWrapper<T>(scoper->Pass());
+  return internal::PassedWrapper<T>(std::move(*scoper));
 }
 
 template <typename T>
 static inline internal::IgnoreResultHelper<T> IgnoreResult(T data) {
   return internal::IgnoreResultHelper<T>(data);
 }
 
 template <typename T>
--- a/security/sandbox/chromium/base/bind_internal.h
+++ b/security/sandbox/chromium/base/bind_internal.h
@@ -1,25 +1,25 @@
-// This file was GENERATED by command:
-//     pump.py bind_internal.h.pump
-// DO NOT EDIT BY HAND!!!
-
-
 // Copyright (c) 2011 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 BASE_BIND_INTERNAL_H_
 #define BASE_BIND_INTERNAL_H_
 
+#include <stddef.h>
+
+#include <type_traits>
+
 #include "base/bind_helpers.h"
 #include "base/callback_internal.h"
 #include "base/memory/raw_scoped_refptr_mismatch_checker.h"
 #include "base/memory/weak_ptr.h"
 #include "base/template_util.h"
+#include "base/tuple.h"
 #include "build/build_config.h"
 
 #if defined(OS_WIN)
 #include "base/bind_internal_win.h"
 #endif
 
 namespace base {
 namespace internal {
@@ -36,53 +36,93 @@ namespace internal {
 //              Runnable declares itself a method, Bind() will enforce special
 //              refcounting + WeakPtr handling semantics for the first
 //              parameter which is expected to be an object.
 //  Functor -- A copyable type representing something that should be called.
 //             All function pointers, Callback<>, and Runnables are functors
 //             even if the invocation syntax differs.
 //  RunType -- A function type (as opposed to function _pointer_ type) for
 //             a Run() function.  Usually just a convenience typedef.
-//  (Bound)ArgsType -- A function type that is being (ab)used to store the
-//                     types of set of arguments.  The "return" type is always
-//                     void here.  We use this hack so that we do not need
-//                     a new type name for each arity of type. (eg.,
-//                     BindState1, BindState2).  This makes forward
-//                     declarations and friending much much easier.
+//  (Bound)Args -- A set of types that stores the arguments.
 //
 // Types:
 //  RunnableAdapter<> -- Wraps the various "function" pointer types into an
 //                       object that adheres to the Runnable interface.
-//                       There are |3*ARITY| RunnableAdapter types.
-//  FunctionTraits<> -- Type traits that unwrap a function signature into a
-//                      a set of easier to use typedefs.  Used mainly for
-//                      compile time asserts.
-//                      There are |ARITY| FunctionTraits types.
 //  ForceVoidReturn<> -- Helper class for translating function signatures to
 //                       equivalent forms with a "void" return type.
-//                    There are |ARITY| ForceVoidReturn types.
 //  FunctorTraits<> -- Type traits used determine the correct RunType and
 //                     RunnableType for a Functor.  This is where function
 //                     signature adapters are applied.
-//                    There are |ARITY| ForceVoidReturn types.
 //  MakeRunnable<> -- Takes a Functor and returns an object in the Runnable
 //                    type class that represents the underlying Functor.
-//                    There are |O(1)| MakeRunnable types.
 //  InvokeHelper<> -- Take a Runnable + arguments and actully invokes it.
-// Handle the differing syntaxes needed for WeakPtr<> support,
-//                    and for ignoring return values.  This is separate from
-//                    Invoker to avoid creating multiple version of Invoker<>
-//                    which grows at O(n^2) with the arity.
-//                    There are |k*ARITY| InvokeHelper types.
+//                    Handle the differing syntaxes needed for WeakPtr<>
+//                    support, and for ignoring return values.  This is separate
+//                    from Invoker to avoid creating multiple version of
+//                    Invoker<>.
 //  Invoker<> -- Unwraps the curried parameters and executes the Runnable.
-//               There are |(ARITY^2 + ARITY)/2| Invoketypes.
 //  BindState<> -- Stores the curried parameters, and is the main entry point
 //                 into the Bind() system, doing most of the type resolution.
 //                 There are ARITY BindState types.
 
+// HasNonConstReferenceParam selects true_type when any of the parameters in
+// |Sig| is a non-const reference.
+// Implementation note: This non-specialized case handles zero-arity case only.
+// Non-zero-arity cases should be handled by the specialization below.
+template <typename List>
+struct HasNonConstReferenceItem : false_type {};
+
+// Implementation note: Select true_type if the first parameter is a non-const
+// reference.  Otherwise, skip the first parameter and check rest of parameters
+// recursively.
+template <typename T, typename... Args>
+struct HasNonConstReferenceItem<TypeList<T, Args...>>
+    : std::conditional<is_non_const_reference<T>::value,
+                       true_type,
+                       HasNonConstReferenceItem<TypeList<Args...>>>::type {};
+
+// HasRefCountedTypeAsRawPtr selects true_type when any of the |Args| is a raw
+// pointer to a RefCounted type.
+// Implementation note: This non-specialized case handles zero-arity case only.
+// Non-zero-arity cases should be handled by the specialization below.
+template <typename... Args>
+struct HasRefCountedTypeAsRawPtr : false_type {};
+
+// Implementation note: Select true_type if the first parameter is a raw pointer
+// to a RefCounted type. Otherwise, skip the first parameter and check rest of
+// parameters recursively.
+template <typename T, typename... Args>
+struct HasRefCountedTypeAsRawPtr<T, Args...>
+    : std::conditional<NeedsScopedRefptrButGetsRawPtr<T>::value,
+                       true_type,
+                       HasRefCountedTypeAsRawPtr<Args...>>::type {};
+
+// BindsArrayToFirstArg selects true_type when |is_method| is true and the first
+// item of |Args| is an array type.
+// Implementation note: This non-specialized case handles !is_method case and
+// zero-arity case only.  Other cases should be handled by the specialization
+// below.
+template <bool is_method, typename... Args>
+struct BindsArrayToFirstArg : false_type {};
+
+template <typename T, typename... Args>
+struct BindsArrayToFirstArg<true, T, Args...> : is_array<T> {};
+
+// HasRefCountedParamAsRawPtr is the same to HasRefCountedTypeAsRawPtr except
+// when |is_method| is true HasRefCountedParamAsRawPtr skips the first argument.
+// Implementation note: This non-specialized case handles !is_method case and
+// zero-arity case only.  Other cases should be handled by the specialization
+// below.
+template <bool is_method, typename... Args>
+struct HasRefCountedParamAsRawPtr : HasRefCountedTypeAsRawPtr<Args...> {};
+
+template <typename T, typename... Args>
+struct HasRefCountedParamAsRawPtr<true, T, Args...>
+    : HasRefCountedTypeAsRawPtr<Args...> {};
+
 // RunnableAdapter<>
 //
 // The RunnableAdapter<> templates provide a uniform interface for invoking
 // a function pointer, method pointer, or const method pointer. The adapter
 // exposes a Run() method with an appropriate signature. Using this wrapper
 // allows for writing code that supports all three pointer types without
 // undue repetition.  Without it, a lot of code would need to be repeated 3
 // times.
@@ -96,708 +136,112 @@ namespace internal {
 //
 // If and only if the wrapper contains a method or const method pointer, an
 // IsMethod typedef is exposed.  The existence of this typedef (NOT the value)
 // marks that the wrapper should be considered a method wrapper.
 
 template <typename Functor>
 class RunnableAdapter;
 
-// Function: Arity 0.
-template <typename R>
-class RunnableAdapter<R(*)()> {
- public:
-  typedef R (RunType)();
-
-  explicit RunnableAdapter(R(*function)())
-      : function_(function) {
-  }
-
-  R Run() {
-    return function_();
-  }
-
- private:
-  R (*function_)();
-};
-
-// Method: Arity 0.
-template <typename R, typename T>
-class RunnableAdapter<R(T::*)()> {
- public:
-  typedef R (RunType)(T*);
-  typedef true_type IsMethod;
-
-  explicit RunnableAdapter(R(T::*method)())
-      : method_(method) {
-  }
-
-  R Run(T* object) {
-    return (object->*method_)();
-  }
-
- private:
-  R (T::*method_)();
-};
-
-// Const Method: Arity 0.
-template <typename R, typename T>
-class RunnableAdapter<R(T::*)() const> {
- public:
-  typedef R (RunType)(const T*);
-  typedef true_type IsMethod;
-
-  explicit RunnableAdapter(R(T::*method)() const)
-      : method_(method) {
-  }
-
-  R Run(const T* object) {
-    return (object->*method_)();
-  }
-
- private:
-  R (T::*method_)() const;
-};
-
-// Function: Arity 1.
-template <typename R, typename A1>
-class RunnableAdapter<R(*)(A1)> {
+// Function.
+template <typename R, typename... Args>
+class RunnableAdapter<R(*)(Args...)> {
  public:
-  typedef R (RunType)(A1);
-
-  explicit RunnableAdapter(R(*function)(A1))
-      : function_(function) {
-  }
-
-  R Run(typename CallbackParamTraits<A1>::ForwardType a1) {
-    return function_(CallbackForward(a1));
-  }
-
- private:
-  R (*function_)(A1);
-};
-
-// Method: Arity 1.
-template <typename R, typename T, typename A1>
-class RunnableAdapter<R(T::*)(A1)> {
- public:
-  typedef R (RunType)(T*, A1);
-  typedef true_type IsMethod;
-
-  explicit RunnableAdapter(R(T::*method)(A1))
-      : method_(method) {
-  }
-
-  R Run(T* object, typename CallbackParamTraits<A1>::ForwardType a1) {
-    return (object->*method_)(CallbackForward(a1));
-  }
+  // MSVC 2013 doesn't support Type Alias of function types.
+  // Revisit this after we update it to newer version.
+  typedef R RunType(Args...);
 
- private:
-  R (T::*method_)(A1);
-};
-
-// Const Method: Arity 1.
-template <typename R, typename T, typename A1>
-class RunnableAdapter<R(T::*)(A1) const> {
- public:
-  typedef R (RunType)(const T*, A1);
-  typedef true_type IsMethod;
-
-  explicit RunnableAdapter(R(T::*method)(A1) const)
-      : method_(method) {
-  }
-
-  R Run(const T* object, typename CallbackParamTraits<A1>::ForwardType a1) {
-    return (object->*method_)(CallbackForward(a1));
-  }
-
- private:
-  R (T::*method_)(A1) const;
-};
-
-// Function: Arity 2.
-template <typename R, typename A1, typename A2>
-class RunnableAdapter<R(*)(A1, A2)> {
- public:
-  typedef R (RunType)(A1, A2);
-
-  explicit RunnableAdapter(R(*function)(A1, A2))
+  explicit RunnableAdapter(R(*function)(Args...))
       : function_(function) {
   }
 
-  R Run(typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2) {
-    return function_(CallbackForward(a1), CallbackForward(a2));
-  }
-
- private:
-  R (*function_)(A1, A2);
-};
-
-// Method: Arity 2.
-template <typename R, typename T, typename A1, typename A2>
-class RunnableAdapter<R(T::*)(A1, A2)> {
- public:
-  typedef R (RunType)(T*, A1, A2);
-  typedef true_type IsMethod;
-
-  explicit RunnableAdapter(R(T::*method)(A1, A2))
-      : method_(method) {
-  }
-
-  R Run(T* object, typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2) {
-    return (object->*method_)(CallbackForward(a1), CallbackForward(a2));
-  }
-
- private:
-  R (T::*method_)(A1, A2);
-};
-
-// Const Method: Arity 2.
-template <typename R, typename T, typename A1, typename A2>
-class RunnableAdapter<R(T::*)(A1, A2) const> {
- public:
-  typedef R (RunType)(const T*, A1, A2);
-  typedef true_type IsMethod;
-
-  explicit RunnableAdapter(R(T::*method)(A1, A2) const)
-      : method_(method) {
-  }
-
-  R Run(const T* object, typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2) {
-    return (object->*method_)(CallbackForward(a1), CallbackForward(a2));
-  }
-
- private:
-  R (T::*method_)(A1, A2) const;
-};
-
-// Function: Arity 3.
-template <typename R, typename A1, typename A2, typename A3>
-class RunnableAdapter<R(*)(A1, A2, A3)> {
- public:
-  typedef R (RunType)(A1, A2, A3);
-
-  explicit RunnableAdapter(R(*function)(A1, A2, A3))
-      : function_(function) {
-  }
-
-  R Run(typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2,
-      typename CallbackParamTraits<A3>::ForwardType a3) {
-    return function_(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3));
-  }
-
- private:
-  R (*function_)(A1, A2, A3);
-};
-
-// Method: Arity 3.
-template <typename R, typename T, typename A1, typename A2, typename A3>
-class RunnableAdapter<R(T::*)(A1, A2, A3)> {
- public:
-  typedef R (RunType)(T*, A1, A2, A3);
-  typedef true_type IsMethod;
-
-  explicit RunnableAdapter(R(T::*method)(A1, A2, A3))
-      : method_(method) {
-  }
-
-  R Run(T* object, typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2,
-      typename CallbackParamTraits<A3>::ForwardType a3) {
-    return (object->*method_)(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3));
-  }
-
- private:
-  R (T::*method_)(A1, A2, A3);
-};
-
-// Const Method: Arity 3.
-template <typename R, typename T, typename A1, typename A2, typename A3>
-class RunnableAdapter<R(T::*)(A1, A2, A3) const> {
- public:
-  typedef R (RunType)(const T*, A1, A2, A3);
-  typedef true_type IsMethod;
-
-  explicit RunnableAdapter(R(T::*method)(A1, A2, A3) const)
-      : method_(method) {
-  }
-
-  R Run(const T* object, typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2,
-      typename CallbackParamTraits<A3>::ForwardType a3) {
-    return (object->*method_)(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3));
-  }
-
- private:
-  R (T::*method_)(A1, A2, A3) const;
-};
-
-// Function: Arity 4.
-template <typename R, typename A1, typename A2, typename A3, typename A4>
-class RunnableAdapter<R(*)(A1, A2, A3, A4)> {
- public:
-  typedef R (RunType)(A1, A2, A3, A4);
-
-  explicit RunnableAdapter(R(*function)(A1, A2, A3, A4))
-      : function_(function) {
-  }
-
-  R Run(typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2,
-      typename CallbackParamTraits<A3>::ForwardType a3,
-      typename CallbackParamTraits<A4>::ForwardType a4) {
-    return function_(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3), CallbackForward(a4));
-  }
-
- private:
-  R (*function_)(A1, A2, A3, A4);
-};
-
-// Method: Arity 4.
-template <typename R, typename T, typename A1, typename A2, typename A3,
-    typename A4>
-class RunnableAdapter<R(T::*)(A1, A2, A3, A4)> {
- public:
-  typedef R (RunType)(T*, A1, A2, A3, A4);
-  typedef true_type IsMethod;
-
-  explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4))
-      : method_(method) {
-  }
-
-  R Run(T* object, typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2,
-      typename CallbackParamTraits<A3>::ForwardType a3,
-      typename CallbackParamTraits<A4>::ForwardType a4) {
-    return (object->*method_)(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3), CallbackForward(a4));
-  }
-
- private:
-  R (T::*method_)(A1, A2, A3, A4);
-};
-
-// Const Method: Arity 4.
-template <typename R, typename T, typename A1, typename A2, typename A3,
-    typename A4>
-class RunnableAdapter<R(T::*)(A1, A2, A3, A4) const> {
- public:
-  typedef R (RunType)(const T*, A1, A2, A3, A4);
-  typedef true_type IsMethod;
-
-  explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4) const)
-      : method_(method) {
-  }
-
-  R Run(const T* object, typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2,
-      typename CallbackParamTraits<A3>::ForwardType a3,
-      typename CallbackParamTraits<A4>::ForwardType a4) {
-    return (object->*method_)(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3), CallbackForward(a4));
+  R Run(typename CallbackParamTraits<Args>::ForwardType... args) {
+    return function_(CallbackForward(args)...);
   }
 
  private:
-  R (T::*method_)(A1, A2, A3, A4) const;
-};
-
-// Function: Arity 5.
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5>
-class RunnableAdapter<R(*)(A1, A2, A3, A4, A5)> {
- public:
-  typedef R (RunType)(A1, A2, A3, A4, A5);
-
-  explicit RunnableAdapter(R(*function)(A1, A2, A3, A4, A5))
-      : function_(function) {
-  }
-
-  R Run(typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2,
-      typename CallbackParamTraits<A3>::ForwardType a3,
-      typename CallbackParamTraits<A4>::ForwardType a4,
-      typename CallbackParamTraits<A5>::ForwardType a5) {
-    return function_(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3), CallbackForward(a4), CallbackForward(a5));
-  }
-
- private:
-  R (*function_)(A1, A2, A3, A4, A5);
+  R (*function_)(Args...);
 };
 
-// Method: Arity 5.
-template <typename R, typename T, typename A1, typename A2, typename A3,
-    typename A4, typename A5>
-class RunnableAdapter<R(T::*)(A1, A2, A3, A4, A5)> {
+// Method.
+template <typename R, typename T, typename... Args>
+class RunnableAdapter<R(T::*)(Args...)> {
  public:
-  typedef R (RunType)(T*, A1, A2, A3, A4, A5);
-  typedef true_type IsMethod;
-
-  explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5))
-      : method_(method) {
-  }
+  // MSVC 2013 doesn't support Type Alias of function types.
+  // Revisit this after we update it to newer version.
+  typedef R RunType(T*, Args...);
+  using IsMethod = true_type;
 
-  R Run(T* object, typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2,
-      typename CallbackParamTraits<A3>::ForwardType a3,
-      typename CallbackParamTraits<A4>::ForwardType a4,
-      typename CallbackParamTraits<A5>::ForwardType a5) {
-    return (object->*method_)(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3), CallbackForward(a4), CallbackForward(a5));
-  }
-
- private:
-  R (T::*method_)(A1, A2, A3, A4, A5);
-};
-
-// Const Method: Arity 5.
-template <typename R, typename T, typename A1, typename A2, typename A3,
-    typename A4, typename A5>
-class RunnableAdapter<R(T::*)(A1, A2, A3, A4, A5) const> {
- public:
-  typedef R (RunType)(const T*, A1, A2, A3, A4, A5);
-  typedef true_type IsMethod;
-
-  explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5) const)
+  explicit RunnableAdapter(R(T::*method)(Args...))
       : method_(method) {
   }
 
-  R Run(const T* object, typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2,
-      typename CallbackParamTraits<A3>::ForwardType a3,
-      typename CallbackParamTraits<A4>::ForwardType a4,
-      typename CallbackParamTraits<A5>::ForwardType a5) {
-    return (object->*method_)(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3), CallbackForward(a4), CallbackForward(a5));
-  }
-
- private:
-  R (T::*method_)(A1, A2, A3, A4, A5) const;
-};
-
-// Function: Arity 6.
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6>
-class RunnableAdapter<R(*)(A1, A2, A3, A4, A5, A6)> {
- public:
-  typedef R (RunType)(A1, A2, A3, A4, A5, A6);
-
-  explicit RunnableAdapter(R(*function)(A1, A2, A3, A4, A5, A6))
-      : function_(function) {
-  }
-
-  R Run(typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2,
-      typename CallbackParamTraits<A3>::ForwardType a3,
-      typename CallbackParamTraits<A4>::ForwardType a4,
-      typename CallbackParamTraits<A5>::ForwardType a5,
-      typename CallbackParamTraits<A6>::ForwardType a6) {
-    return function_(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3), CallbackForward(a4), CallbackForward(a5),
-        CallbackForward(a6));
-  }
-
- private:
-  R (*function_)(A1, A2, A3, A4, A5, A6);
-};
-
-// Method: Arity 6.
-template <typename R, typename T, typename A1, typename A2, typename A3,
-    typename A4, typename A5, typename A6>
-class RunnableAdapter<R(T::*)(A1, A2, A3, A4, A5, A6)> {
- public:
-  typedef R (RunType)(T*, A1, A2, A3, A4, A5, A6);
-  typedef true_type IsMethod;
-
-  explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5, A6))
-      : method_(method) {
-  }
-
-  R Run(T* object, typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2,
-      typename CallbackParamTraits<A3>::ForwardType a3,
-      typename CallbackParamTraits<A4>::ForwardType a4,
-      typename CallbackParamTraits<A5>::ForwardType a5,
-      typename CallbackParamTraits<A6>::ForwardType a6) {
-    return (object->*method_)(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3), CallbackForward(a4), CallbackForward(a5),
-        CallbackForward(a6));
-  }
-
- private:
-  R (T::*method_)(A1, A2, A3, A4, A5, A6);
-};
-
-// Const Method: Arity 6.
-template <typename R, typename T, typename A1, typename A2, typename A3,
-    typename A4, typename A5, typename A6>
-class RunnableAdapter<R(T::*)(A1, A2, A3, A4, A5, A6) const> {
- public:
-  typedef R (RunType)(const T*, A1, A2, A3, A4, A5, A6);
-  typedef true_type IsMethod;
-
-  explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5, A6) const)
-      : method_(method) {
-  }
-
-  R Run(const T* object, typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2,
-      typename CallbackParamTraits<A3>::ForwardType a3,
-      typename CallbackParamTraits<A4>::ForwardType a4,
-      typename CallbackParamTraits<A5>::ForwardType a5,
-      typename CallbackParamTraits<A6>::ForwardType a6) {
-    return (object->*method_)(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3), CallbackForward(a4), CallbackForward(a5),
-        CallbackForward(a6));
+  R Run(T* object, typename CallbackParamTraits<Args>::ForwardType... args) {
+    return (object->*method_)(CallbackForward(args)...);
   }
 
  private:
-  R (T::*method_)(A1, A2, A3, A4, A5, A6) const;
-};
-
-// Function: Arity 7.
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6, typename A7>
-class RunnableAdapter<R(*)(A1, A2, A3, A4, A5, A6, A7)> {
- public:
-  typedef R (RunType)(A1, A2, A3, A4, A5, A6, A7);
-
-  explicit RunnableAdapter(R(*function)(A1, A2, A3, A4, A5, A6, A7))
-      : function_(function) {
-  }
-
-  R Run(typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2,
-      typename CallbackParamTraits<A3>::ForwardType a3,
-      typename CallbackParamTraits<A4>::ForwardType a4,
-      typename CallbackParamTraits<A5>::ForwardType a5,
-      typename CallbackParamTraits<A6>::ForwardType a6,
-      typename CallbackParamTraits<A7>::ForwardType a7) {
-    return function_(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3), CallbackForward(a4), CallbackForward(a5),
-        CallbackForward(a6), CallbackForward(a7));
-  }
-
- private:
-  R (*function_)(A1, A2, A3, A4, A5, A6, A7);
+  R (T::*method_)(Args...);
 };
 
-// Method: Arity 7.
-template <typename R, typename T, typename A1, typename A2, typename A3,
-    typename A4, typename A5, typename A6, typename A7>
-class RunnableAdapter<R(T::*)(A1, A2, A3, A4, A5, A6, A7)> {
+// Const Method.
+template <typename R, typename T, typename... Args>
+class RunnableAdapter<R(T::*)(Args...) const> {
  public:
-  typedef R (RunType)(T*, A1, A2, A3, A4, A5, A6, A7);
-  typedef true_type IsMethod;
-
-  explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5, A6, A7))
-      : method_(method) {
-  }
+  using RunType = R(const T*, Args...);
+  using IsMethod = true_type;
 
-  R Run(T* object, typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2,
-      typename CallbackParamTraits<A3>::ForwardType a3,
-      typename CallbackParamTraits<A4>::ForwardType a4,
-      typename CallbackParamTraits<A5>::ForwardType a5,
-      typename CallbackParamTraits<A6>::ForwardType a6,
-      typename CallbackParamTraits<A7>::ForwardType a7) {
-    return (object->*method_)(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3), CallbackForward(a4), CallbackForward(a5),
-        CallbackForward(a6), CallbackForward(a7));
-  }
-
- private:
-  R (T::*method_)(A1, A2, A3, A4, A5, A6, A7);
-};
-
-// Const Method: Arity 7.
-template <typename R, typename T, typename A1, typename A2, typename A3,
-    typename A4, typename A5, typename A6, typename A7>
-class RunnableAdapter<R(T::*)(A1, A2, A3, A4, A5, A6, A7) const> {
- public:
-  typedef R (RunType)(const T*, A1, A2, A3, A4, A5, A6, A7);
-  typedef true_type IsMethod;
-
-  explicit RunnableAdapter(R(T::*method)(A1, A2, A3, A4, A5, A6, A7) const)
+  explicit RunnableAdapter(R(T::*method)(Args...) const)
       : method_(method) {
   }
 
-  R Run(const T* object, typename CallbackParamTraits<A1>::ForwardType a1,
-      typename CallbackParamTraits<A2>::ForwardType a2,
-      typename CallbackParamTraits<A3>::ForwardType a3,
-      typename CallbackParamTraits<A4>::ForwardType a4,
-      typename CallbackParamTraits<A5>::ForwardType a5,
-      typename CallbackParamTraits<A6>::ForwardType a6,
-      typename CallbackParamTraits<A7>::ForwardType a7) {
-    return (object->*method_)(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3), CallbackForward(a4), CallbackForward(a5),
-        CallbackForward(a6), CallbackForward(a7));
+  R Run(const T* object,
+        typename CallbackParamTraits<Args>::ForwardType... args) {
+    return (object->*method_)(CallbackForward(args)...);
   }
 
  private:
-  R (T::*method_)(A1, A2, A3, A4, A5, A6, A7) const;
-};
-
-
-// FunctionTraits<>
-//
-// Breaks a function signature apart into typedefs for easier introspection.
-template <typename Sig>
-struct FunctionTraits;
-
-template <typename R>
-struct FunctionTraits<R()> {
-  typedef R ReturnType;
-};
-
-template <typename R, typename A1>
-struct FunctionTraits<R(A1)> {
-  typedef R ReturnType;
-  typedef A1 A1Type;
-};
-
-template <typename R, typename A1, typename A2>
-struct FunctionTraits<R(A1, A2)> {
-  typedef R ReturnType;
-  typedef A1 A1Type;
-  typedef A2 A2Type;
-};
-
-template <typename R, typename A1, typename A2, typename A3>
-struct FunctionTraits<R(A1, A2, A3)> {
-  typedef R ReturnType;
-  typedef A1 A1Type;
-  typedef A2 A2Type;
-  typedef A3 A3Type;
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4>
-struct FunctionTraits<R(A1, A2, A3, A4)> {
-  typedef R ReturnType;
-  typedef A1 A1Type;
-  typedef A2 A2Type;
-  typedef A3 A3Type;
-  typedef A4 A4Type;
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5>
-struct FunctionTraits<R(A1, A2, A3, A4, A5)> {
-  typedef R ReturnType;
-  typedef A1 A1Type;
-  typedef A2 A2Type;
-  typedef A3 A3Type;
-  typedef A4 A4Type;
-  typedef A5 A5Type;
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6>
-struct FunctionTraits<R(A1, A2, A3, A4, A5, A6)> {
-  typedef R ReturnType;
-  typedef A1 A1Type;
-  typedef A2 A2Type;
-  typedef A3 A3Type;
-  typedef A4 A4Type;
-  typedef A5 A5Type;
-  typedef A6 A6Type;
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6, typename A7>
-struct FunctionTraits<R(A1, A2, A3, A4, A5, A6, A7)> {
-  typedef R ReturnType;
-  typedef A1 A1Type;
-  typedef A2 A2Type;
-  typedef A3 A3Type;
-  typedef A4 A4Type;
-  typedef A5 A5Type;
-  typedef A6 A6Type;
-  typedef A7 A7Type;
+  R (T::*method_)(Args...) const;
 };
 
 
 // ForceVoidReturn<>
 //
 // Set of templates that support forcing the function return type to void.
 template <typename Sig>
 struct ForceVoidReturn;
 
-template <typename R>
-struct ForceVoidReturn<R()> {
-  typedef void(RunType)();
-};
-
-template <typename R, typename A1>
-struct ForceVoidReturn<R(A1)> {
-  typedef void(RunType)(A1);
-};
-
-template <typename R, typename A1, typename A2>
-struct ForceVoidReturn<R(A1, A2)> {
-  typedef void(RunType)(A1, A2);
-};
-
-template <typename R, typename A1, typename A2, typename A3>
-struct ForceVoidReturn<R(A1, A2, A3)> {
-  typedef void(RunType)(A1, A2, A3);
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4>
-struct ForceVoidReturn<R(A1, A2, A3, A4)> {
-  typedef void(RunType)(A1, A2, A3, A4);
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5>
-struct ForceVoidReturn<R(A1, A2, A3, A4, A5)> {
-  typedef void(RunType)(A1, A2, A3, A4, A5);
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6>
-struct ForceVoidReturn<R(A1, A2, A3, A4, A5, A6)> {
-  typedef void(RunType)(A1, A2, A3, A4, A5, A6);
-};
-
-template <typename R, typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6, typename A7>
-struct ForceVoidReturn<R(A1, A2, A3, A4, A5, A6, A7)> {
-  typedef void(RunType)(A1, A2, A3, A4, A5, A6, A7);
+template <typename R, typename... Args>
+struct ForceVoidReturn<R(Args...)> {
+  // MSVC 2013 doesn't support Type Alias of function types.
+  // Revisit this after we update it to newer version.
+  typedef void RunType(Args...);
 };
 
 
 // FunctorTraits<>
 //
 // See description at top of file.
 template <typename T>
 struct FunctorTraits {
-  typedef RunnableAdapter<T> RunnableType;
-  typedef typename RunnableType::RunType RunType;
+  using RunnableType = RunnableAdapter<T>;
+  using RunType = typename RunnableType::RunType;
 };
 
 template <typename T>
-struct FunctorTraits<IgnoreResultHelper<T> > {
-  typedef typename FunctorTraits<T>::RunnableType RunnableType;
-  typedef typename ForceVoidReturn<
-      typename RunnableType::RunType>::RunType RunType;
+struct FunctorTraits<IgnoreResultHelper<T>> {
+  using RunnableType = typename FunctorTraits<T>::RunnableType;
+  using RunType =
+      typename ForceVoidReturn<typename RunnableType::RunType>::RunType;
 };
 
 template <typename T>
-struct FunctorTraits<Callback<T> > {
-  typedef Callback<T> RunnableType;
-  typedef typename Callback<T>::RunType RunType;
+struct FunctorTraits<Callback<T>> {
+  using RunnableType = Callback<T> ;
+  using RunType = typename Callback<T>::RunType;
 };
 
 
 // MakeRunnable<>
 //
 // Converts a passed in functor to a RunnableType using type inference.
 
 template <typename T>
@@ -807,17 +251,17 @@ typename FunctorTraits<T>::RunnableType 
 
 template <typename T>
 typename FunctorTraits<T>::RunnableType
 MakeRunnable(const IgnoreResultHelper<T>& t) {
   return MakeRunnable(t.functor_);
 }
 
 template <typename T>
-const typename FunctorTraits<Callback<T> >::RunnableType&
+const typename FunctorTraits<Callback<T>>::RunnableType&
 MakeRunnable(const Callback<T>& t) {
   DCHECK(!t.is_null());
   return t;
 }
 
 
 // InvokeHelper<>
 //
@@ -835,1955 +279,147 @@ MakeRunnable(const Callback<T>& t) {
 // from the invocation call.
 //
 // WeakCalls similarly need special syntax that is applied to the first
 // argument to check if they should no-op themselves.
 template <bool IsWeakCall, typename ReturnType, typename Runnable,
           typename ArgsType>
 struct InvokeHelper;
 
-template <typename ReturnType, typename Runnable>
-struct InvokeHelper<false, ReturnType, Runnable,
-    void()>  {
-  static ReturnType MakeItSo(Runnable runnable) {
-    return runnable.Run();
-  }
-};
-
-template <typename Runnable>
-struct InvokeHelper<false, void, Runnable,
-    void()>  {
-  static void MakeItSo(Runnable runnable) {
-    runnable.Run();
-  }
-};
-
-template <typename ReturnType, typename Runnable,typename A1>
-struct InvokeHelper<false, ReturnType, Runnable,
-    void(A1)>  {
-  static ReturnType MakeItSo(Runnable runnable, A1 a1) {
-    return runnable.Run(CallbackForward(a1));
-  }
-};
-
-template <typename Runnable,typename A1>
-struct InvokeHelper<false, void, Runnable,
-    void(A1)>  {
-  static void MakeItSo(Runnable runnable, A1 a1) {
-    runnable.Run(CallbackForward(a1));
-  }
-};
-
-template <typename Runnable, typename BoundWeakPtr>
-struct InvokeHelper<true, void, Runnable,
-    void(BoundWeakPtr)>  {
-  static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr) {
-    if (!weak_ptr.get()) {
-      return;
-    }
-    runnable.Run(weak_ptr.get());
-  }
-};
-
-template <typename ReturnType, typename Runnable,typename A1, typename A2>
-struct InvokeHelper<false, ReturnType, Runnable,
-    void(A1, A2)>  {
-  static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2) {
-    return runnable.Run(CallbackForward(a1), CallbackForward(a2));
-  }
-};
-
-template <typename Runnable,typename A1, typename A2>
-struct InvokeHelper<false, void, Runnable,
-    void(A1, A2)>  {
-  static void MakeItSo(Runnable runnable, A1 a1, A2 a2) {
-    runnable.Run(CallbackForward(a1), CallbackForward(a2));
-  }
-};
-
-template <typename Runnable, typename BoundWeakPtr, typename A2>
-struct InvokeHelper<true, void, Runnable,
-    void(BoundWeakPtr, A2)>  {
-  static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2) {
-    if (!weak_ptr.get()) {
-      return;
-    }
-    runnable.Run(weak_ptr.get(), CallbackForward(a2));
-  }
-};
-
-template <typename ReturnType, typename Runnable,typename A1, typename A2,
-    typename A3>
-struct InvokeHelper<false, ReturnType, Runnable,
-    void(A1, A2, A3)>  {
-  static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3) {
-    return runnable.Run(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3));
-  }
-};
-
-template <typename Runnable,typename A1, typename A2, typename A3>
-struct InvokeHelper<false, void, Runnable,
-    void(A1, A2, A3)>  {
-  static void MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3) {
-    runnable.Run(CallbackForward(a1), CallbackForward(a2), CallbackForward(a3));
-  }
-};
-
-template <typename Runnable, typename BoundWeakPtr, typename A2, typename A3>
-struct InvokeHelper<true, void, Runnable,
-    void(BoundWeakPtr, A2, A3)>  {
-  static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2, A3 a3) {
-    if (!weak_ptr.get()) {
-      return;
-    }
-    runnable.Run(weak_ptr.get(), CallbackForward(a2), CallbackForward(a3));
-  }
-};
-
-template <typename ReturnType, typename Runnable,typename A1, typename A2,
-    typename A3, typename A4>
-struct InvokeHelper<false, ReturnType, Runnable,
-    void(A1, A2, A3, A4)>  {
-  static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4) {
-    return runnable.Run(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3), CallbackForward(a4));
-  }
-};
-
-template <typename Runnable,typename A1, typename A2, typename A3, typename A4>
-struct InvokeHelper<false, void, Runnable,
-    void(A1, A2, A3, A4)>  {
-  static void MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4) {
-    runnable.Run(CallbackForward(a1), CallbackForward(a2), CallbackForward(a3),
-        CallbackForward(a4));
+template <typename ReturnType, typename Runnable, typename... Args>
+struct InvokeHelper<false, ReturnType, Runnable, TypeList<Args...>> {
+  static ReturnType MakeItSo(Runnable runnable, Args... args) {
+    return runnable.Run(CallbackForward(args)...);
   }
 };
 
-template <typename Runnable, typename BoundWeakPtr, typename A2, typename A3,
-    typename A4>
-struct InvokeHelper<true, void, Runnable,
-    void(BoundWeakPtr, A2, A3, A4)>  {
-  static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2, A3 a3,
-      A4 a4) {
-    if (!weak_ptr.get()) {
-      return;
-    }
-    runnable.Run(weak_ptr.get(), CallbackForward(a2), CallbackForward(a3),
-        CallbackForward(a4));
-  }
-};
-
-template <typename ReturnType, typename Runnable,typename A1, typename A2,
-    typename A3, typename A4, typename A5>
-struct InvokeHelper<false, ReturnType, Runnable,
-    void(A1, A2, A3, A4, A5)>  {
-  static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4,
-      A5 a5) {
-    return runnable.Run(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3), CallbackForward(a4), CallbackForward(a5));
-  }
-};
-
-template <typename Runnable,typename A1, typename A2, typename A3, typename A4,
-    typename A5>
-struct InvokeHelper<false, void, Runnable,
-    void(A1, A2, A3, A4, A5)>  {
-  static void MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) {
-    runnable.Run(CallbackForward(a1), CallbackForward(a2), CallbackForward(a3),
-        CallbackForward(a4), CallbackForward(a5));
-  }
-};
-
-template <typename Runnable, typename BoundWeakPtr, typename A2, typename A3,
-    typename A4, typename A5>
-struct InvokeHelper<true, void, Runnable,
-    void(BoundWeakPtr, A2, A3, A4, A5)>  {
-  static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2, A3 a3,
-      A4 a4, A5 a5) {
-    if (!weak_ptr.get()) {
-      return;
-    }
-    runnable.Run(weak_ptr.get(), CallbackForward(a2), CallbackForward(a3),
-        CallbackForward(a4), CallbackForward(a5));
-  }
-};
-
-template <typename ReturnType, typename Runnable,typename A1, typename A2,
-    typename A3, typename A4, typename A5, typename A6>
-struct InvokeHelper<false, ReturnType, Runnable,
-    void(A1, A2, A3, A4, A5, A6)>  {
-  static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4,
-      A5 a5, A6 a6) {
-    return runnable.Run(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3), CallbackForward(a4), CallbackForward(a5),
-        CallbackForward(a6));
+template <typename Runnable, typename... Args>
+struct InvokeHelper<false, void, Runnable, TypeList<Args...>> {
+  static void MakeItSo(Runnable runnable, Args... args) {
+    runnable.Run(CallbackForward(args)...);
   }
 };
 
-template <typename Runnable,typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6>
-struct InvokeHelper<false, void, Runnable,
-    void(A1, A2, A3, A4, A5, A6)>  {
-  static void MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5,
-      A6 a6) {
-    runnable.Run(CallbackForward(a1), CallbackForward(a2), CallbackForward(a3),
-        CallbackForward(a4), CallbackForward(a5), CallbackForward(a6));
-  }
-};
-
-template <typename Runnable, typename BoundWeakPtr, typename A2, typename A3,
-    typename A4, typename A5, typename A6>
-struct InvokeHelper<true, void, Runnable,
-    void(BoundWeakPtr, A2, A3, A4, A5, A6)>  {
-  static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2, A3 a3,
-      A4 a4, A5 a5, A6 a6) {
+template <typename Runnable, typename BoundWeakPtr, typename... Args>
+struct InvokeHelper<true, void, Runnable, TypeList<BoundWeakPtr, Args...>> {
+  static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, Args... args) {
     if (!weak_ptr.get()) {
       return;
     }
-    runnable.Run(weak_ptr.get(), CallbackForward(a2), CallbackForward(a3),
-        CallbackForward(a4), CallbackForward(a5), CallbackForward(a6));
-  }
-};
-
-template <typename ReturnType, typename Runnable,typename A1, typename A2,
-    typename A3, typename A4, typename A5, typename A6, typename A7>
-struct InvokeHelper<false, ReturnType, Runnable,
-    void(A1, A2, A3, A4, A5, A6, A7)>  {
-  static ReturnType MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4,
-      A5 a5, A6 a6, A7 a7) {
-    return runnable.Run(CallbackForward(a1), CallbackForward(a2),
-        CallbackForward(a3), CallbackForward(a4), CallbackForward(a5),
-        CallbackForward(a6), CallbackForward(a7));
-  }
-};
-
-template <typename Runnable,typename A1, typename A2, typename A3, typename A4,
-    typename A5, typename A6, typename A7>
-struct InvokeHelper<false, void, Runnable,
-    void(A1, A2, A3, A4, A5, A6, A7)>  {
-  static void MakeItSo(Runnable runnable, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5,
-      A6 a6, A7 a7) {
-    runnable.Run(CallbackForward(a1), CallbackForward(a2), CallbackForward(a3),
-        CallbackForward(a4), CallbackForward(a5), CallbackForward(a6),
-        CallbackForward(a7));
-  }
-};
-
-template <typename Runnable, typename BoundWeakPtr, typename A2, typename A3,
-    typename A4, typename A5, typename A6, typename A7>
-struct InvokeHelper<true, void, Runnable,
-    void(BoundWeakPtr, A2, A3, A4, A5, A6, A7)>  {
-  static void MakeItSo(Runnable runnable, BoundWeakPtr weak_ptr, A2 a2, A3 a3,
-      A4 a4, A5 a5, A6 a6, A7 a7) {
-    if (!weak_ptr.get()) {
-      return;
-    }
-    runnable.Run(weak_ptr.get(), CallbackForward(a2), CallbackForward(a3),
-        CallbackForward(a4), CallbackForward(a5), CallbackForward(a6),
-        CallbackForward(a7));
+    runnable.Run(weak_ptr.get(), CallbackForward(args)...);
   }
 };
 
 #if !defined(_MSC_VER)
 
 template <typename ReturnType, typename Runnable, typename ArgsType>
 struct InvokeHelper<true, ReturnType, Runnable, ArgsType> {
   // WeakCalls are only supported for functions with a void return type.
   // Otherwise, the function result would be undefined if the the WeakPtr<>
   // is invalidated.
-  COMPILE_ASSERT(is_void<ReturnType>::value,
-                 weak_ptrs_can_only_bind_to_methods_without_return_values);
+  static_assert(is_void<ReturnType>::value,
+                "weak_ptrs can only bind to methods without return values");
 };
 
 #endif
 
 // Invoker<>
 //
 // See description at the top of the file.
-template <int NumBound, typename Storage, typename RunType>
+template <typename BoundIndices,
+          typename StorageType, typename Unwrappers,
+          typename InvokeHelperType, typename UnboundForwardRunType>
 struct Invoker;
 
-// Arity 0 -> 0.
-template <typename StorageType, typename R>
-struct Invoker<0, StorageType, R()> {
-  typedef R(RunType)(BindStateBase*);
-
-  typedef R(UnboundRunType)();
-
-  static R Run(BindStateBase* base) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void()>
-               ::MakeItSo(storage->runnable_);
-  }
-};
-
-// Arity 1 -> 1.
-template <typename StorageType, typename R,typename X1>
-struct Invoker<0, StorageType, R(X1)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X1>::ForwardType);
-
-  typedef R(UnboundRunType)(X1);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X1>::ForwardType x1) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename CallbackParamTraits<X1>::ForwardType x1)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1));
-  }
-};
-
-// Arity 1 -> 0.
-template <typename StorageType, typename R,typename X1>
-struct Invoker<1, StorageType, R(X1)> {
-  typedef R(RunType)(BindStateBase*);
-
-  typedef R(UnboundRunType)();
-
-  static R Run(BindStateBase* base) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1));
-  }
-};
-
-// Arity 2 -> 2.
-template <typename StorageType, typename R,typename X1, typename X2>
-struct Invoker<0, StorageType, R(X1, X2)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X1>::ForwardType,
-      typename CallbackParamTraits<X2>::ForwardType);
-
-  typedef R(UnboundRunType)(X1, X2);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X1>::ForwardType x1,
-      typename CallbackParamTraits<X2>::ForwardType x2) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename CallbackParamTraits<X1>::ForwardType x1,
-               typename CallbackParamTraits<X2>::ForwardType x2)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2));
-  }
-};
-
-// Arity 2 -> 1.
-template <typename StorageType, typename R,typename X1, typename X2>
-struct Invoker<1, StorageType, R(X1, X2)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X2>::ForwardType);
-
-  typedef R(UnboundRunType)(X2);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X2>::ForwardType x2) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X2>::ForwardType x2)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2));
-  }
-};
-
-// Arity 2 -> 0.
-template <typename StorageType, typename R,typename X1, typename X2>
-struct Invoker<2, StorageType, R(X1, X2)> {
-  typedef R(RunType)(BindStateBase*);
-
-  typedef R(UnboundRunType)();
-
-  static R Run(BindStateBase* base) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2));
-  }
-};
-
-// Arity 3 -> 3.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3>
-struct Invoker<0, StorageType, R(X1, X2, X3)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X1>::ForwardType,
-      typename CallbackParamTraits<X2>::ForwardType,
-      typename CallbackParamTraits<X3>::ForwardType);
-
-  typedef R(UnboundRunType)(X1, X2, X3);
-
+template <size_t... bound_indices,
+          typename StorageType,
+          typename... Unwrappers,
+          typename InvokeHelperType,
+          typename R,
+          typename... UnboundForwardArgs>
+struct Invoker<IndexSequence<bound_indices...>,
+               StorageType, TypeList<Unwrappers...>,
+               InvokeHelperType, R(UnboundForwardArgs...)> {
   static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X1>::ForwardType x1,
-      typename CallbackParamTraits<X2>::ForwardType x2,
-      typename CallbackParamTraits<X3>::ForwardType x3) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename CallbackParamTraits<X1>::ForwardType x1,
-               typename CallbackParamTraits<X2>::ForwardType x2,
-               typename CallbackParamTraits<X3>::ForwardType x3)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3));
-  }
-};
-
-// Arity 3 -> 2.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3>
-struct Invoker<1, StorageType, R(X1, X2, X3)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X2>::ForwardType,
-      typename CallbackParamTraits<X3>::ForwardType);
-
-  typedef R(UnboundRunType)(X2, X3);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X2>::ForwardType x2,
-      typename CallbackParamTraits<X3>::ForwardType x3) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X2>::ForwardType x2,
-               typename CallbackParamTraits<X3>::ForwardType x3)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3));
-  }
-};
-
-// Arity 3 -> 1.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3>
-struct Invoker<2, StorageType, R(X1, X2, X3)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X3>::ForwardType);
-
-  typedef R(UnboundRunType)(X3);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X3>::ForwardType x3) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X3>::ForwardType x3)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3));
-  }
-};
-
-// Arity 3 -> 0.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3>
-struct Invoker<3, StorageType, R(X1, X2, X3)> {
-  typedef R(RunType)(BindStateBase*);
-
-  typedef R(UnboundRunType)();
-
-  static R Run(BindStateBase* base) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-    typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    typename Bound3UnwrapTraits::ForwardType x3 =
-        Bound3UnwrapTraits::Unwrap(storage->p3_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename Bound3UnwrapTraits::ForwardType)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3));
-  }
-};
-
-// Arity 4 -> 4.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4>
-struct Invoker<0, StorageType, R(X1, X2, X3, X4)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X1>::ForwardType,
-      typename CallbackParamTraits<X2>::ForwardType,
-      typename CallbackParamTraits<X3>::ForwardType,
-      typename CallbackParamTraits<X4>::ForwardType);
-
-  typedef R(UnboundRunType)(X1, X2, X3, X4);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X1>::ForwardType x1,
-      typename CallbackParamTraits<X2>::ForwardType x2,
-      typename CallbackParamTraits<X3>::ForwardType x3,
-      typename CallbackParamTraits<X4>::ForwardType x4) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename CallbackParamTraits<X1>::ForwardType x1,
-               typename CallbackParamTraits<X2>::ForwardType x2,
-               typename CallbackParamTraits<X3>::ForwardType x3,
-               typename CallbackParamTraits<X4>::ForwardType x4)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4));
-  }
-};
-
-// Arity 4 -> 3.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4>
-struct Invoker<1, StorageType, R(X1, X2, X3, X4)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X2>::ForwardType,
-      typename CallbackParamTraits<X3>::ForwardType,
-      typename CallbackParamTraits<X4>::ForwardType);
-
-  typedef R(UnboundRunType)(X2, X3, X4);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X2>::ForwardType x2,
-      typename CallbackParamTraits<X3>::ForwardType x3,
-      typename CallbackParamTraits<X4>::ForwardType x4) {
+               UnboundForwardArgs... unbound_args) {
     StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X2>::ForwardType x2,
-               typename CallbackParamTraits<X3>::ForwardType x3,
-               typename CallbackParamTraits<X4>::ForwardType x4)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4));
-  }
-};
-
-// Arity 4 -> 2.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4>
-struct Invoker<2, StorageType, R(X1, X2, X3, X4)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X3>::ForwardType,
-      typename CallbackParamTraits<X4>::ForwardType);
-
-  typedef R(UnboundRunType)(X3, X4);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X3>::ForwardType x3,
-      typename CallbackParamTraits<X4>::ForwardType x4) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X3>::ForwardType x3,
-               typename CallbackParamTraits<X4>::ForwardType x4)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4));
-  }
-};
-
-// Arity 4 -> 1.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4>
-struct Invoker<3, StorageType, R(X1, X2, X3, X4)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X4>::ForwardType);
-
-  typedef R(UnboundRunType)(X4);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X4>::ForwardType x4) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-    typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    typename Bound3UnwrapTraits::ForwardType x3 =
-        Bound3UnwrapTraits::Unwrap(storage->p3_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename Bound3UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X4>::ForwardType x4)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4));
-  }
-};
-
-// Arity 4 -> 0.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4>
-struct Invoker<4, StorageType, R(X1, X2, X3, X4)> {
-  typedef R(RunType)(BindStateBase*);
-
-  typedef R(UnboundRunType)();
-
-  static R Run(BindStateBase* base) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-    typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits;
-    typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    typename Bound3UnwrapTraits::ForwardType x3 =
-        Bound3UnwrapTraits::Unwrap(storage->p3_);
-    typename Bound4UnwrapTraits::ForwardType x4 =
-        Bound4UnwrapTraits::Unwrap(storage->p4_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename Bound3UnwrapTraits::ForwardType,
-               typename Bound4UnwrapTraits::ForwardType)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4));
-  }
-};
-
-// Arity 5 -> 5.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5>
-struct Invoker<0, StorageType, R(X1, X2, X3, X4, X5)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X1>::ForwardType,
-      typename CallbackParamTraits<X2>::ForwardType,
-      typename CallbackParamTraits<X3>::ForwardType,
-      typename CallbackParamTraits<X4>::ForwardType,
-      typename CallbackParamTraits<X5>::ForwardType);
-
-  typedef R(UnboundRunType)(X1, X2, X3, X4, X5);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X1>::ForwardType x1,
-      typename CallbackParamTraits<X2>::ForwardType x2,
-      typename CallbackParamTraits<X3>::ForwardType x3,
-      typename CallbackParamTraits<X4>::ForwardType x4,
-      typename CallbackParamTraits<X5>::ForwardType x5) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename CallbackParamTraits<X1>::ForwardType x1,
-               typename CallbackParamTraits<X2>::ForwardType x2,
-               typename CallbackParamTraits<X3>::ForwardType x3,
-               typename CallbackParamTraits<X4>::ForwardType x4,
-               typename CallbackParamTraits<X5>::ForwardType x5)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5));
-  }
-};
-
-// Arity 5 -> 4.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5>
-struct Invoker<1, StorageType, R(X1, X2, X3, X4, X5)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X2>::ForwardType,
-      typename CallbackParamTraits<X3>::ForwardType,
-      typename CallbackParamTraits<X4>::ForwardType,
-      typename CallbackParamTraits<X5>::ForwardType);
-
-  typedef R(UnboundRunType)(X2, X3, X4, X5);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X2>::ForwardType x2,
-      typename CallbackParamTraits<X3>::ForwardType x3,
-      typename CallbackParamTraits<X4>::ForwardType x4,
-      typename CallbackParamTraits<X5>::ForwardType x5) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X2>::ForwardType x2,
-               typename CallbackParamTraits<X3>::ForwardType x3,
-               typename CallbackParamTraits<X4>::ForwardType x4,
-               typename CallbackParamTraits<X5>::ForwardType x5)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5));
-  }
-};
-
-// Arity 5 -> 3.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5>
-struct Invoker<2, StorageType, R(X1, X2, X3, X4, X5)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X3>::ForwardType,
-      typename CallbackParamTraits<X4>::ForwardType,
-      typename CallbackParamTraits<X5>::ForwardType);
-
-  typedef R(UnboundRunType)(X3, X4, X5);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X3>::ForwardType x3,
-      typename CallbackParamTraits<X4>::ForwardType x4,
-      typename CallbackParamTraits<X5>::ForwardType x5) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X3>::ForwardType x3,
-               typename CallbackParamTraits<X4>::ForwardType x4,
-               typename CallbackParamTraits<X5>::ForwardType x5)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5));
-  }
-};
-
-// Arity 5 -> 2.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5>
-struct Invoker<3, StorageType, R(X1, X2, X3, X4, X5)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X4>::ForwardType,
-      typename CallbackParamTraits<X5>::ForwardType);
-
-  typedef R(UnboundRunType)(X4, X5);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X4>::ForwardType x4,
-      typename CallbackParamTraits<X5>::ForwardType x5) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-    typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    typename Bound3UnwrapTraits::ForwardType x3 =
-        Bound3UnwrapTraits::Unwrap(storage->p3_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename Bound3UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X4>::ForwardType x4,
-               typename CallbackParamTraits<X5>::ForwardType x5)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5));
-  }
-};
-
-// Arity 5 -> 1.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5>
-struct Invoker<4, StorageType, R(X1, X2, X3, X4, X5)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X5>::ForwardType);
-
-  typedef R(UnboundRunType)(X5);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X5>::ForwardType x5) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-    typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits;
-    typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    typename Bound3UnwrapTraits::ForwardType x3 =
-        Bound3UnwrapTraits::Unwrap(storage->p3_);
-    typename Bound4UnwrapTraits::ForwardType x4 =
-        Bound4UnwrapTraits::Unwrap(storage->p4_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename Bound3UnwrapTraits::ForwardType,
-               typename Bound4UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X5>::ForwardType x5)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5));
-  }
-};
-
-// Arity 5 -> 0.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5>
-struct Invoker<5, StorageType, R(X1, X2, X3, X4, X5)> {
-  typedef R(RunType)(BindStateBase*);
-
-  typedef R(UnboundRunType)();
-
-  static R Run(BindStateBase* base) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
     // Local references to make debugger stepping easier. If in a debugger,
     // you really want to warp ahead and step through the
     // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-    typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits;
-    typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits;
-    typedef typename StorageType::Bound5UnwrapTraits Bound5UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    typename Bound3UnwrapTraits::ForwardType x3 =
-        Bound3UnwrapTraits::Unwrap(storage->p3_);
-    typename Bound4UnwrapTraits::ForwardType x4 =
-        Bound4UnwrapTraits::Unwrap(storage->p4_);
-    typename Bound5UnwrapTraits::ForwardType x5 =
-        Bound5UnwrapTraits::Unwrap(storage->p5_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename Bound3UnwrapTraits::ForwardType,
-               typename Bound4UnwrapTraits::ForwardType,
-               typename Bound5UnwrapTraits::ForwardType)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5));
-  }
-};
-
-// Arity 6 -> 6.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5, typename X6>
-struct Invoker<0, StorageType, R(X1, X2, X3, X4, X5, X6)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X1>::ForwardType,
-      typename CallbackParamTraits<X2>::ForwardType,
-      typename CallbackParamTraits<X3>::ForwardType,
-      typename CallbackParamTraits<X4>::ForwardType,
-      typename CallbackParamTraits<X5>::ForwardType,
-      typename CallbackParamTraits<X6>::ForwardType);
-
-  typedef R(UnboundRunType)(X1, X2, X3, X4, X5, X6);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X1>::ForwardType x1,
-      typename CallbackParamTraits<X2>::ForwardType x2,
-      typename CallbackParamTraits<X3>::ForwardType x3,
-      typename CallbackParamTraits<X4>::ForwardType x4,
-      typename CallbackParamTraits<X5>::ForwardType x5,
-      typename CallbackParamTraits<X6>::ForwardType x6) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename CallbackParamTraits<X1>::ForwardType x1,
-               typename CallbackParamTraits<X2>::ForwardType x2,
-               typename CallbackParamTraits<X3>::ForwardType x3,
-               typename CallbackParamTraits<X4>::ForwardType x4,
-               typename CallbackParamTraits<X5>::ForwardType x5,
-               typename CallbackParamTraits<X6>::ForwardType x6)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5),
-                   CallbackForward(x6));
-  }
-};
-
-// Arity 6 -> 5.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5, typename X6>
-struct Invoker<1, StorageType, R(X1, X2, X3, X4, X5, X6)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X2>::ForwardType,
-      typename CallbackParamTraits<X3>::ForwardType,
-      typename CallbackParamTraits<X4>::ForwardType,
-      typename CallbackParamTraits<X5>::ForwardType,
-      typename CallbackParamTraits<X6>::ForwardType);
-
-  typedef R(UnboundRunType)(X2, X3, X4, X5, X6);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X2>::ForwardType x2,
-      typename CallbackParamTraits<X3>::ForwardType x3,
-      typename CallbackParamTraits<X4>::ForwardType x4,
-      typename CallbackParamTraits<X5>::ForwardType x5,
-      typename CallbackParamTraits<X6>::ForwardType x6) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X2>::ForwardType x2,
-               typename CallbackParamTraits<X3>::ForwardType x3,
-               typename CallbackParamTraits<X4>::ForwardType x4,
-               typename CallbackParamTraits<X5>::ForwardType x5,
-               typename CallbackParamTraits<X6>::ForwardType x6)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5),
-                   CallbackForward(x6));
-  }
-};
-
-// Arity 6 -> 4.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5, typename X6>
-struct Invoker<2, StorageType, R(X1, X2, X3, X4, X5, X6)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X3>::ForwardType,
-      typename CallbackParamTraits<X4>::ForwardType,
-      typename CallbackParamTraits<X5>::ForwardType,
-      typename CallbackParamTraits<X6>::ForwardType);
-
-  typedef R(UnboundRunType)(X3, X4, X5, X6);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X3>::ForwardType x3,
-      typename CallbackParamTraits<X4>::ForwardType x4,
-      typename CallbackParamTraits<X5>::ForwardType x5,
-      typename CallbackParamTraits<X6>::ForwardType x6) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X3>::ForwardType x3,
-               typename CallbackParamTraits<X4>::ForwardType x4,
-               typename CallbackParamTraits<X5>::ForwardType x5,
-               typename CallbackParamTraits<X6>::ForwardType x6)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5),
-                   CallbackForward(x6));
-  }
-};
-
-// Arity 6 -> 3.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5, typename X6>
-struct Invoker<3, StorageType, R(X1, X2, X3, X4, X5, X6)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X4>::ForwardType,
-      typename CallbackParamTraits<X5>::ForwardType,
-      typename CallbackParamTraits<X6>::ForwardType);
-
-  typedef R(UnboundRunType)(X4, X5, X6);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X4>::ForwardType x4,
-      typename CallbackParamTraits<X5>::ForwardType x5,
-      typename CallbackParamTraits<X6>::ForwardType x6) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-    typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    typename Bound3UnwrapTraits::ForwardType x3 =
-        Bound3UnwrapTraits::Unwrap(storage->p3_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename Bound3UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X4>::ForwardType x4,
-               typename CallbackParamTraits<X5>::ForwardType x5,
-               typename CallbackParamTraits<X6>::ForwardType x6)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5),
-                   CallbackForward(x6));
-  }
-};
-
-// Arity 6 -> 2.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5, typename X6>
-struct Invoker<4, StorageType, R(X1, X2, X3, X4, X5, X6)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X5>::ForwardType,
-      typename CallbackParamTraits<X6>::ForwardType);
-
-  typedef R(UnboundRunType)(X5, X6);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X5>::ForwardType x5,
-      typename CallbackParamTraits<X6>::ForwardType x6) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-    typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits;
-    typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    typename Bound3UnwrapTraits::ForwardType x3 =
-        Bound3UnwrapTraits::Unwrap(storage->p3_);
-    typename Bound4UnwrapTraits::ForwardType x4 =
-        Bound4UnwrapTraits::Unwrap(storage->p4_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename Bound3UnwrapTraits::ForwardType,
-               typename Bound4UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X5>::ForwardType x5,
-               typename CallbackParamTraits<X6>::ForwardType x6)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5),
-                   CallbackForward(x6));
-  }
-};
-
-// Arity 6 -> 1.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5, typename X6>
-struct Invoker<5, StorageType, R(X1, X2, X3, X4, X5, X6)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X6>::ForwardType);
-
-  typedef R(UnboundRunType)(X6);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X6>::ForwardType x6) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-    typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits;
-    typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits;
-    typedef typename StorageType::Bound5UnwrapTraits Bound5UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    typename Bound3UnwrapTraits::ForwardType x3 =
-        Bound3UnwrapTraits::Unwrap(storage->p3_);
-    typename Bound4UnwrapTraits::ForwardType x4 =
-        Bound4UnwrapTraits::Unwrap(storage->p4_);
-    typename Bound5UnwrapTraits::ForwardType x5 =
-        Bound5UnwrapTraits::Unwrap(storage->p5_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename Bound3UnwrapTraits::ForwardType,
-               typename Bound4UnwrapTraits::ForwardType,
-               typename Bound5UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X6>::ForwardType x6)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5),
-                   CallbackForward(x6));
-  }
-};
-
-// Arity 6 -> 0.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5, typename X6>
-struct Invoker<6, StorageType, R(X1, X2, X3, X4, X5, X6)> {
-  typedef R(RunType)(BindStateBase*);
-
-  typedef R(UnboundRunType)();
-
-  static R Run(BindStateBase* base) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-    typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits;
-    typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits;
-    typedef typename StorageType::Bound5UnwrapTraits Bound5UnwrapTraits;
-    typedef typename StorageType::Bound6UnwrapTraits Bound6UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    typename Bound3UnwrapTraits::ForwardType x3 =
-        Bound3UnwrapTraits::Unwrap(storage->p3_);
-    typename Bound4UnwrapTraits::ForwardType x4 =
-        Bound4UnwrapTraits::Unwrap(storage->p4_);
-    typename Bound5UnwrapTraits::ForwardType x5 =
-        Bound5UnwrapTraits::Unwrap(storage->p5_);
-    typename Bound6UnwrapTraits::ForwardType x6 =
-        Bound6UnwrapTraits::Unwrap(storage->p6_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename Bound3UnwrapTraits::ForwardType,
-               typename Bound4UnwrapTraits::ForwardType,
-               typename Bound5UnwrapTraits::ForwardType,
-               typename Bound6UnwrapTraits::ForwardType)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5),
-                   CallbackForward(x6));
-  }
-};
-
-// Arity 7 -> 7.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5, typename X6, typename X7>
-struct Invoker<0, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X1>::ForwardType,
-      typename CallbackParamTraits<X2>::ForwardType,
-      typename CallbackParamTraits<X3>::ForwardType,
-      typename CallbackParamTraits<X4>::ForwardType,
-      typename CallbackParamTraits<X5>::ForwardType,
-      typename CallbackParamTraits<X6>::ForwardType,
-      typename CallbackParamTraits<X7>::ForwardType);
-
-  typedef R(UnboundRunType)(X1, X2, X3, X4, X5, X6, X7);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X1>::ForwardType x1,
-      typename CallbackParamTraits<X2>::ForwardType x2,
-      typename CallbackParamTraits<X3>::ForwardType x3,
-      typename CallbackParamTraits<X4>::ForwardType x4,
-      typename CallbackParamTraits<X5>::ForwardType x5,
-      typename CallbackParamTraits<X6>::ForwardType x6,
-      typename CallbackParamTraits<X7>::ForwardType x7) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename CallbackParamTraits<X1>::ForwardType x1,
-               typename CallbackParamTraits<X2>::ForwardType x2,
-               typename CallbackParamTraits<X3>::ForwardType x3,
-               typename CallbackParamTraits<X4>::ForwardType x4,
-               typename CallbackParamTraits<X5>::ForwardType x5,
-               typename CallbackParamTraits<X6>::ForwardType x6,
-               typename CallbackParamTraits<X7>::ForwardType x7)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5),
-                   CallbackForward(x6), CallbackForward(x7));
-  }
-};
-
-// Arity 7 -> 6.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5, typename X6, typename X7>
-struct Invoker<1, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X2>::ForwardType,
-      typename CallbackParamTraits<X3>::ForwardType,
-      typename CallbackParamTraits<X4>::ForwardType,
-      typename CallbackParamTraits<X5>::ForwardType,
-      typename CallbackParamTraits<X6>::ForwardType,
-      typename CallbackParamTraits<X7>::ForwardType);
-
-  typedef R(UnboundRunType)(X2, X3, X4, X5, X6, X7);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X2>::ForwardType x2,
-      typename CallbackParamTraits<X3>::ForwardType x3,
-      typename CallbackParamTraits<X4>::ForwardType x4,
-      typename CallbackParamTraits<X5>::ForwardType x5,
-      typename CallbackParamTraits<X6>::ForwardType x6,
-      typename CallbackParamTraits<X7>::ForwardType x7) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X2>::ForwardType x2,
-               typename CallbackParamTraits<X3>::ForwardType x3,
-               typename CallbackParamTraits<X4>::ForwardType x4,
-               typename CallbackParamTraits<X5>::ForwardType x5,
-               typename CallbackParamTraits<X6>::ForwardType x6,
-               typename CallbackParamTraits<X7>::ForwardType x7)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5),
-                   CallbackForward(x6), CallbackForward(x7));
-  }
-};
-
-// Arity 7 -> 5.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5, typename X6, typename X7>
-struct Invoker<2, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X3>::ForwardType,
-      typename CallbackParamTraits<X4>::ForwardType,
-      typename CallbackParamTraits<X5>::ForwardType,
-      typename CallbackParamTraits<X6>::ForwardType,
-      typename CallbackParamTraits<X7>::ForwardType);
-
-  typedef R(UnboundRunType)(X3, X4, X5, X6, X7);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X3>::ForwardType x3,
-      typename CallbackParamTraits<X4>::ForwardType x4,
-      typename CallbackParamTraits<X5>::ForwardType x5,
-      typename CallbackParamTraits<X6>::ForwardType x6,
-      typename CallbackParamTraits<X7>::ForwardType x7) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X3>::ForwardType x3,
-               typename CallbackParamTraits<X4>::ForwardType x4,
-               typename CallbackParamTraits<X5>::ForwardType x5,
-               typename CallbackParamTraits<X6>::ForwardType x6,
-               typename CallbackParamTraits<X7>::ForwardType x7)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5),
-                   CallbackForward(x6), CallbackForward(x7));
-  }
-};
-
-// Arity 7 -> 4.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5, typename X6, typename X7>
-struct Invoker<3, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X4>::ForwardType,
-      typename CallbackParamTraits<X5>::ForwardType,
-      typename CallbackParamTraits<X6>::ForwardType,
-      typename CallbackParamTraits<X7>::ForwardType);
-
-  typedef R(UnboundRunType)(X4, X5, X6, X7);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X4>::ForwardType x4,
-      typename CallbackParamTraits<X5>::ForwardType x5,
-      typename CallbackParamTraits<X6>::ForwardType x6,
-      typename CallbackParamTraits<X7>::ForwardType x7) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-    typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    typename Bound3UnwrapTraits::ForwardType x3 =
-        Bound3UnwrapTraits::Unwrap(storage->p3_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename Bound3UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X4>::ForwardType x4,
-               typename CallbackParamTraits<X5>::ForwardType x5,
-               typename CallbackParamTraits<X6>::ForwardType x6,
-               typename CallbackParamTraits<X7>::ForwardType x7)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5),
-                   CallbackForward(x6), CallbackForward(x7));
-  }
-};
-
-// Arity 7 -> 3.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5, typename X6, typename X7>
-struct Invoker<4, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X5>::ForwardType,
-      typename CallbackParamTraits<X6>::ForwardType,
-      typename CallbackParamTraits<X7>::ForwardType);
-
-  typedef R(UnboundRunType)(X5, X6, X7);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X5>::ForwardType x5,
-      typename CallbackParamTraits<X6>::ForwardType x6,
-      typename CallbackParamTraits<X7>::ForwardType x7) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-    typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits;
-    typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    typename Bound3UnwrapTraits::ForwardType x3 =
-        Bound3UnwrapTraits::Unwrap(storage->p3_);
-    typename Bound4UnwrapTraits::ForwardType x4 =
-        Bound4UnwrapTraits::Unwrap(storage->p4_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename Bound3UnwrapTraits::ForwardType,
-               typename Bound4UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X5>::ForwardType x5,
-               typename CallbackParamTraits<X6>::ForwardType x6,
-               typename CallbackParamTraits<X7>::ForwardType x7)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5),
-                   CallbackForward(x6), CallbackForward(x7));
-  }
-};
-
-// Arity 7 -> 2.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5, typename X6, typename X7>
-struct Invoker<5, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X6>::ForwardType,
-      typename CallbackParamTraits<X7>::ForwardType);
-
-  typedef R(UnboundRunType)(X6, X7);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X6>::ForwardType x6,
-      typename CallbackParamTraits<X7>::ForwardType x7) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-    typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits;
-    typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits;
-    typedef typename StorageType::Bound5UnwrapTraits Bound5UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    typename Bound3UnwrapTraits::ForwardType x3 =
-        Bound3UnwrapTraits::Unwrap(storage->p3_);
-    typename Bound4UnwrapTraits::ForwardType x4 =
-        Bound4UnwrapTraits::Unwrap(storage->p4_);
-    typename Bound5UnwrapTraits::ForwardType x5 =
-        Bound5UnwrapTraits::Unwrap(storage->p5_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename Bound3UnwrapTraits::ForwardType,
-               typename Bound4UnwrapTraits::ForwardType,
-               typename Bound5UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X6>::ForwardType x6,
-               typename CallbackParamTraits<X7>::ForwardType x7)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5),
-                   CallbackForward(x6), CallbackForward(x7));
-  }
-};
-
-// Arity 7 -> 1.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5, typename X6, typename X7>
-struct Invoker<6, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> {
-  typedef R(RunType)(BindStateBase*,
-      typename CallbackParamTraits<X7>::ForwardType);
-
-  typedef R(UnboundRunType)(X7);
-
-  static R Run(BindStateBase* base,
-      typename CallbackParamTraits<X7>::ForwardType x7) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-    typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits;
-    typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits;
-    typedef typename StorageType::Bound5UnwrapTraits Bound5UnwrapTraits;
-    typedef typename StorageType::Bound6UnwrapTraits Bound6UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    typename Bound3UnwrapTraits::ForwardType x3 =
-        Bound3UnwrapTraits::Unwrap(storage->p3_);
-    typename Bound4UnwrapTraits::ForwardType x4 =
-        Bound4UnwrapTraits::Unwrap(storage->p4_);
-    typename Bound5UnwrapTraits::ForwardType x5 =
-        Bound5UnwrapTraits::Unwrap(storage->p5_);
-    typename Bound6UnwrapTraits::ForwardType x6 =
-        Bound6UnwrapTraits::Unwrap(storage->p6_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename Bound3UnwrapTraits::ForwardType,
-               typename Bound4UnwrapTraits::ForwardType,
-               typename Bound5UnwrapTraits::ForwardType,
-               typename Bound6UnwrapTraits::ForwardType,
-               typename CallbackParamTraits<X7>::ForwardType x7)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5),
-                   CallbackForward(x6), CallbackForward(x7));
-  }
-};
-
-// Arity 7 -> 0.
-template <typename StorageType, typename R,typename X1, typename X2,
-    typename X3, typename X4, typename X5, typename X6, typename X7>
-struct Invoker<7, StorageType, R(X1, X2, X3, X4, X5, X6, X7)> {
-  typedef R(RunType)(BindStateBase*);
-
-  typedef R(UnboundRunType)();
-
-  static R Run(BindStateBase* base) {
-    StorageType* storage = static_cast<StorageType*>(base);
-
-    // Local references to make debugger stepping easier. If in a debugger,
-    // you really want to warp ahead and step through the
-    // InvokeHelper<>::MakeItSo() call below.
-    typedef typename StorageType::Bound1UnwrapTraits Bound1UnwrapTraits;
-    typedef typename StorageType::Bound2UnwrapTraits Bound2UnwrapTraits;
-    typedef typename StorageType::Bound3UnwrapTraits Bound3UnwrapTraits;
-    typedef typename StorageType::Bound4UnwrapTraits Bound4UnwrapTraits;
-    typedef typename StorageType::Bound5UnwrapTraits Bound5UnwrapTraits;
-    typedef typename StorageType::Bound6UnwrapTraits Bound6UnwrapTraits;
-    typedef typename StorageType::Bound7UnwrapTraits Bound7UnwrapTraits;
-
-    typename Bound1UnwrapTraits::ForwardType x1 =
-        Bound1UnwrapTraits::Unwrap(storage->p1_);
-    typename Bound2UnwrapTraits::ForwardType x2 =
-        Bound2UnwrapTraits::Unwrap(storage->p2_);
-    typename Bound3UnwrapTraits::ForwardType x3 =
-        Bound3UnwrapTraits::Unwrap(storage->p3_);
-    typename Bound4UnwrapTraits::ForwardType x4 =
-        Bound4UnwrapTraits::Unwrap(storage->p4_);
-    typename Bound5UnwrapTraits::ForwardType x5 =
-        Bound5UnwrapTraits::Unwrap(storage->p5_);
-    typename Bound6UnwrapTraits::ForwardType x6 =
-        Bound6UnwrapTraits::Unwrap(storage->p6_);
-    typename Bound7UnwrapTraits::ForwardType x7 =
-        Bound7UnwrapTraits::Unwrap(storage->p7_);
-    return InvokeHelper<StorageType::IsWeakCall::value, R,
-           typename StorageType::RunnableType,
-           void(typename Bound1UnwrapTraits::ForwardType,
-               typename Bound2UnwrapTraits::ForwardType,
-               typename Bound3UnwrapTraits::ForwardType,
-               typename Bound4UnwrapTraits::ForwardType,
-               typename Bound5UnwrapTraits::ForwardType,
-               typename Bound6UnwrapTraits::ForwardType,
-               typename Bound7UnwrapTraits::ForwardType)>
-               ::MakeItSo(storage->runnable_, CallbackForward(x1),
-                   CallbackForward(x2), CallbackForward(x3),
-                   CallbackForward(x4), CallbackForward(x5),
-                   CallbackForward(x6), CallbackForward(x7));
+    return InvokeHelperType::MakeItSo(
+        storage->runnable_,
+        Unwrappers::Unwrap(get<bound_indices>(storage->bound_args_))...,
+        CallbackForward(unbound_args)...);
   }
 };
 
 
 // BindState<>
 //
 // This stores all the state passed into Bind() and is also where most
 // of the template resolution magic occurs.
 //
 // Runnable is the functor we are binding arguments to.
 // RunType is type of the Run() function that the Invoker<> should use.
 // Normally, this is the same as the RunType of the Runnable, but it can
 // be different if an adapter like IgnoreResult() has been used.
 //
-// BoundArgsType contains the storage type for all the bound arguments by
-// (ab)using a function type.
-template <typename Runnable, typename RunType, typename BoundArgsType>
+// BoundArgs contains the storage type for all the bound arguments.
+template <typename Runnable, typename RunType, typename... BoundArgs>
 struct BindState;
 
-template <typename Runnable, typename RunType>
-struct BindState<Runnable, RunType, void()> : public BindStateBase {
-  typedef Runnable RunnableType;
-  typedef false_type IsWeakCall;
-  typedef Invoker<0, BindState, RunType> InvokerType;
-  typedef typename InvokerType::UnboundRunType UnboundRunType;
-  explicit BindState(const Runnable& runnable)
-      : runnable_(runnable) {
-  }
-
-  virtual ~BindState() {  }
-
-  RunnableType runnable_;
-};
-
-template <typename Runnable, typename RunType, typename P1>
-struct BindState<Runnable, RunType, void(P1)> : public BindStateBase {
-  typedef Runnable RunnableType;
-  typedef IsWeakMethod<HasIsMethodTag<Runnable>::value, P1> IsWeakCall;
-  typedef Invoker<1, BindState, RunType> InvokerType;
-  typedef typename InvokerType::UnboundRunType UnboundRunType;
-
-  // Convenience typedefs for bound argument types.
-  typedef UnwrapTraits<P1> Bound1UnwrapTraits;
+template <typename Runnable,
+          typename R,
+          typename... Args,
+          typename... BoundArgs>
+struct BindState<Runnable, R(Args...), BoundArgs...> final
+    : public BindStateBase {
+ private:
+  using StorageType = BindState<Runnable, R(Args...), BoundArgs...>;
+  using RunnableType = Runnable;
 
-  BindState(const Runnable& runnable, const P1& p1)
-      : runnable_(runnable),
-        p1_(p1) {
-    MaybeRefcount<HasIsMethodTag<Runnable>::value, P1>::AddRef(p1_);
-  }
-
-  virtual ~BindState() {    MaybeRefcount<HasIsMethodTag<Runnable>::value,
-      P1>::Release(p1_);  }
-
-  RunnableType runnable_;
-  P1 p1_;
-};
-
-template <typename Runnable, typename RunType, typename P1, typename P2>
-struct BindState<Runnable, RunType, void(P1, P2)> : public BindStateBase {
-  typedef Runnable RunnableType;
-  typedef IsWeakMethod<HasIsMethodTag<Runnable>::value, P1> IsWeakCall;
-  typedef Invoker<2, BindState, RunType> InvokerType;
-  typedef typename InvokerType::UnboundRunType UnboundRunType;
-
-  // Convenience typedefs for bound argument types.
-  typedef UnwrapTraits<P1> Bound1UnwrapTraits;
-  typedef UnwrapTraits<P2> Bound2UnwrapTraits;
-
-  BindState(const Runnable& runnable, const P1& p1, const P2& p2)
-      : runnable_(runnable),
-        p1_(p1),
-        p2_(p2) {
-    MaybeRefcount<HasIsMethodTag<Runnable>::value, P1>::AddRef(p1_);
-  }
-
-  virtual ~BindState() {    MaybeRefcount<HasIsMethodTag<Runnable>::value,
-      P1>::Release(p1_);  }
+  // true_type if Runnable is a method invocation and the first bound argument
+  // is a WeakPtr.
+  using IsWeakCall =
+      IsWeakMethod<HasIsMethodTag<Runnable>::value, BoundArgs...>;
 
-  RunnableType runnable_;
-  P1 p1_;
-  P2 p2_;
-};
-
-template <typename Runnable, typename RunType, typename P1, typename P2,
-    typename P3>
-struct BindState<Runnable, RunType, void(P1, P2, P3)> : public BindStateBase {
-  typedef Runnable RunnableType;
-  typedef IsWeakMethod<HasIsMethodTag<Runnable>::value, P1> IsWeakCall;
-  typedef Invoker<3, BindState, RunType> InvokerType;
-  typedef typename InvokerType::UnboundRunType UnboundRunType;
+  using BoundIndices = MakeIndexSequence<sizeof...(BoundArgs)>;
+  using Unwrappers = TypeList<UnwrapTraits<BoundArgs>...>;
+  using UnboundForwardArgs = DropTypeListItem<
+      sizeof...(BoundArgs),
+      TypeList<typename CallbackParamTraits<Args>::ForwardType...>>;
+  using UnboundForwardRunType = MakeFunctionType<R, UnboundForwardArgs>;
 
-  // Convenience typedefs for bound argument types.
-  typedef UnwrapTraits<P1> Bound1UnwrapTraits;
-  typedef UnwrapTraits<P2> Bound2UnwrapTraits;
-  typedef UnwrapTraits<P3> Bound3UnwrapTraits;
-
-  BindState(const Runnable& runnable, const P1& p1, const P2& p2, const P3& p3)
-      : runnable_(runnable),
-        p1_(p1),
-        p2_(p2),
-        p3_(p3) {
-    MaybeRefcount<HasIsMethodTag<Runnable>::value, P1>::AddRef(p1_);
-  }
-
-  virtual ~BindState() {    MaybeRefcount<HasIsMethodTag<Runnable>::value,
-      P1>::Release(p1_);  }
+  using InvokeHelperArgs = ConcatTypeLists<
+      TypeList<typename UnwrapTraits<BoundArgs>::ForwardType...>,
+      UnboundForwardArgs>;
+  using InvokeHelperType =
+      InvokeHelper<IsWeakCall::value, R, Runnable, InvokeHelperArgs>;
 
-  RunnableType runnable_;
-  P1 p1_;
-  P2 p2_;
-  P3 p3_;
-};
-
-template <typename Runnable, typename RunType, typename P1, typename P2,
-    typename P3, typename P4>
-struct BindState<Runnable, RunType, void(P1, P2, P3,
-    P4)> : public BindStateBase {
-  typedef Runnable RunnableType;
-  typedef IsWeakMethod<HasIsMethodTag<Runnable>::value, P1> IsWeakCall;
-  typedef Invoker<4, BindState, RunType> InvokerType;
-  typedef typename InvokerType::UnboundRunType UnboundRunType;
+  using UnboundArgs = DropTypeListItem<sizeof...(BoundArgs), TypeList<Args...>>;
 
-  // Convenience typedefs for bound argument types.
-  typedef UnwrapTraits<P1> Bound1UnwrapTraits;
-  typedef UnwrapTraits<P2> Bound2UnwrapTraits;
-  typedef UnwrapTraits<P3> Bound3UnwrapTraits;
-  typedef UnwrapTraits<P4> Bound4UnwrapTraits;
+ public:
+  using InvokerType = Invoker<BoundIndices, StorageType, Unwrappers,
+                              InvokeHelperType, UnboundForwardRunType>;
+  using UnboundRunType = MakeFunctionType<R, UnboundArgs>;
 
-  BindState(const Runnable& runnable, const P1& p1, const P2& p2, const P3& p3,
-      const P4& p4)
-      : runnable_(runnable),
-        p1_(p1),
-        p2_(p2),
-        p3_(p3),
-        p4_(p4) {
-    MaybeRefcount<HasIsMethodTag<Runnable>::value, P1>::AddRef(p1_);
-  }
-
-  virtual ~BindState() {    MaybeRefcount<HasIsMethodTag<Runnable>::value,
-      P1>::Release(p1_);  }
+  BindState(const Runnable& runnable, const BoundArgs&... bound_args)
+      : BindStateBase(&Destroy),
+        runnable_(runnable),
+        ref_(bound_args...),
+        bound_args_(bound_args...) {}
 
   RunnableType runnable_;
-  P1 p1_;
-  P2 p2_;
-  P3 p3_;
-  P4 p4_;
-};
-
-template <typename Runnable, typename RunType, typename P1, typename P2,
-    typename P3, typename P4, typename P5>
-struct BindState<Runnable, RunType, void(P1, P2, P3, P4,
-    P5)> : public BindStateBase {
-  typedef Runnable RunnableType;
-  typedef IsWeakMethod<HasIsMethodTag<Runnable>::value, P1> IsWeakCall;
-  typedef Invoker<5, BindState, RunType> InvokerType;
-  typedef typename InvokerType::UnboundRunType UnboundRunType;
-
-  // Convenience typedefs for bound argument types.
-  typedef UnwrapTraits<P1> Bound1UnwrapTraits;
-  typedef UnwrapTraits<P2> Bound2UnwrapTraits;
-  typedef UnwrapTraits<P3> Bound3UnwrapTraits;
-  typedef UnwrapTraits<P4> Bound4UnwrapTraits;
-  typedef UnwrapTraits<P5> Bound5UnwrapTraits;
-
-  BindState(const Runnable& runnable, const P1& p1, const P2& p2, const P3& p3,
-      const P4& p4, const P5& p5)
-      : runnable_(runnable),
-        p1_(p1),
-        p2_(p2),
-        p3_(p3),
-        p4_(p4),
-        p5_(p5) {
-    MaybeRefcount<HasIsMethodTag<Runnable>::value, P1>::AddRef(p1_);
-  }
-
-  virtual ~BindState() {    MaybeRefcount<HasIsMethodTag<Runnable>::value,
-      P1>::Release(p1_);  }
-
-  RunnableType runnable_;
-  P1 p1_;
-  P2 p2_;
-  P3 p3_;
-  P4 p4_;
-  P5 p5_;
-};
-
-template <typename Runnable, typename RunType, typename P1, typename P2,
-    typename P3, typename P4, typename P5, typename P6>
-struct BindState<Runnable, RunType, void(P1, P2, P3, P4, P5,
-    P6)> : public BindStateBase {
-  typedef Runnable RunnableType;
-  typedef IsWeakMethod<HasIsMethodTag<Runnable>::value, P1> IsWeakCall;
-  typedef Invoker<6, BindState, RunType> InvokerType;
-  typedef typename InvokerType::UnboundRunType UnboundRunType;
-
-  // Convenience typedefs for bound argument types.
-  typedef UnwrapTraits<P1> Bound1UnwrapTraits;
-  typedef UnwrapTraits<P2> Bound2UnwrapTraits;
-  typedef UnwrapTraits<P3> Bound3UnwrapTraits;
-  typedef UnwrapTraits<P4> Bound4UnwrapTraits;
-  typedef UnwrapTraits<P5> Bound5UnwrapTraits;
-  typedef UnwrapTraits<P6> Bound6UnwrapTraits;
+  MaybeScopedRefPtr<HasIsMethodTag<Runnable>::value, BoundArgs...> ref_;
+  Tuple<BoundArgs...> bound_args_;
 
-  BindState(const Runnable& runnable, const P1& p1, const P2& p2, const P3& p3,
-      const P4& p4, const P5& p5, const P6& p6)
-      : runnable_(runnable),
-        p1_(p1),
-        p2_(p2),
-        p3_(p3),
-        p4_(p4),
-        p5_(p5),
-        p6_(p6) {
-    MaybeRefcount<HasIsMethodTag<Runnable>::value, P1>::AddRef(p1_);
-  }
-
-  virtual ~BindState() {    MaybeRefcount<HasIsMethodTag<Runnable>::value,
-      P1>::Release(p1_);  }
-
-  RunnableType runnable_;
-  P1 p1_;
-  P2 p2_;
-  P3 p3_;
-  P4 p4_;
-  P5 p5_;
-  P6 p6_;
-};
-
-template <typename Runnable, typename RunType, typename P1, typename P2,
-    typename P3, typename P4, typename P5, typename P6, typename P7>
-struct BindState<Runnable, RunType, void(P1, P2, P3, P4, P5, P6,
-    P7)> : public BindStateBase {
-  typedef Runnable RunnableType;
-  typedef IsWeakMethod<HasIsMethodTag<Runnable>::value, P1> IsWeakCall;
-  typedef Invoker<7, BindState, RunType> InvokerType;
-  typedef typename InvokerType::UnboundRunType UnboundRunType;
+ private:
+  ~BindState() {}
 
-  // Convenience typedefs for bound argument types.
-  typedef UnwrapTraits<P1> Bound1UnwrapTraits;
-  typedef UnwrapTraits<P2> Bound2UnwrapTraits;
-  typedef UnwrapTraits<P3> Bound3UnwrapTraits;
-  typedef UnwrapTraits<P4> Bound4UnwrapTraits;
-  typedef UnwrapTraits<P5> Bound5UnwrapTraits;
-  typedef UnwrapTraits<P6> Bound6UnwrapTraits;
-  typedef UnwrapTraits<P7> Bound7UnwrapTraits;
-
-  BindState(const Runnable& runnable, const P1& p1, const P2& p2, const P3& p3,
-      const P4& p4, const P5& p5, const P6& p6, const P7& p7)
-      : runnable_(runnable),
-        p1_(p1),
-        p2_(p2),
-        p3_(p3),
-        p4_(p4),
-        p5_(p5),
-        p6_(p6),
-        p7_(p7) {
-    MaybeRefcount<HasIsMethodTag<Runnable>::value, P1>::AddRef(p1_);
+  static void Destroy(BindStateBase* self) {
+    delete static_cast<BindState*>(self);
   }
-
-  virtual ~BindState() {    MaybeRefcount<HasIsMethodTag<Runnable>::value,
-      P1>::Release(p1_);  }
-
-  RunnableType runnable_;
-  P1 p1_;
-  P2 p2_;
-  P3 p3_;
-  P4 p4_;
-  P5 p5_;
-  P6 p6_;
-  P7 p7_;
 };
 
 }  // namespace internal
 }  // namespace base
 
 #endif  // BASE_BIND_INTERNAL_H_
--- a/security/sandbox/chromium/base/bind_internal_win.h
+++ b/security/sandbox/chromium/base/bind_internal_win.h
@@ -3,32 +3,36 @@
 // found in the LICENSE file.
 
 // Specializations of RunnableAdapter<> for Windows specific calling
 // conventions.  Please see base/bind_internal.h for more info.
 
 #ifndef BASE_BIND_INTERNAL_WIN_H_
 #define BASE_BIND_INTERNAL_WIN_H_
 
+#include "build/build_config.h"
+
 // In the x64 architecture in Windows, __fastcall, __stdcall, etc, are all
 // the same as __cdecl which would turn the following specializations into
 // multiple definitions.
 #if !defined(ARCH_CPU_X86_64)
 
 namespace base {
 namespace internal {
 
 template <typename Functor>
 class RunnableAdapter;
 
 // __stdcall Function.
 template <typename R, typename... Args>
 class RunnableAdapter<R(__stdcall *)(Args...)> {
  public:
-  typedef R (RunType)(Args...);
+  // MSVC 2013 doesn't support Type Alias of function types.
+  // Revisit this after we update it to newer version.
+  typedef R RunType(Args...);
 
   explicit RunnableAdapter(R(__stdcall *function)(Args...))
       : function_(function) {
   }
 
   R Run(typename CallbackParamTraits<Args>::ForwardType... args) {
     return function_(args...);
   }
@@ -36,17 +40,19 @@ class RunnableAdapter<R(__stdcall *)(Arg
  private:
   R (__stdcall *function_)(Args...);
 };
 
 // __fastcall Function.
 template <typename R, typename... Args>
 class RunnableAdapter<R(__fastcall *)(Args...)> {
  public:
-  typedef R (RunType)(Args...);
+  // MSVC 2013 doesn't support Type Alias of function types.
+  // Revisit this after we update it to newer version.
+  typedef R RunType(Args...);
 
   explicit RunnableAdapter(R(__fastcall *function)(Args...))
       : function_(function) {
   }
 
   R Run(typename CallbackParamTraits<Args>::ForwardType... args) {
     return function_(args...);
   }
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium/base/bit_cast.h
@@ -0,0 +1,71 @@
+// Copyright 2016 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef BASE_BIT_CAST_H_
+#define BASE_BIT_CAST_H_
+
+#include <string.h>
+
+// bit_cast<Dest,Source> is a template function that implements the equivalent
+// of "*reinterpret_cast<Dest*>(&source)".  We need this in very low-level
+// functions like the protobuf library and fast math support.
+//
+//   float f = 3.14159265358979;
+//   int i = bit_cast<int32_t>(f);
+//   // i = 0x40490fdb
+//
+// The classical address-casting method is:
+//
+//   // WRONG
+//   float f = 3.14159265358979;            // WRONG
+//   int i = * reinterpret_cast<int*>(&f);  // WRONG
+//
+// The address-casting method actually produces undefined behavior according to
+// the ISO C++98 specification, section 3.10 ("basic.lval"), paragraph 15.
+// (This did not substantially change in C++11.)  Roughly, this section says: if
+// an object in memory has one type, and a program accesses it with a different
+// type, then the result is undefined behavior for most values of "different
+// type".
+//
+// This is true for any cast syntax, either *(int*)&f or
+// *reinterpret_cast<int*>(&f).  And it is particularly true for conversions
+// between integral lvalues and floating-point lvalues.
+//
+// The purpose of this paragraph is to allow optimizing compilers to assume that
+// expressions with different types refer to different memory.  Compilers are
+// known to take advantage of this.  So a non-conforming program quietly
+// produces wildly incorrect output.
+//
+// The problem is not the use of reinterpret_cast.  The problem is type punning:
+// holding an object in memory of one type and reading its bits back using a
+// different type.
+//
+// The C++ standard is more subtle and complex than this, but that is the basic
+// idea.
+//
+// Anyways ...
+//
+// bit_cast<> calls memcpy() which is blessed by the standard, especially by the
+// example in section 3.9 .  Also, of course, bit_cast<> wraps up the nasty
+// logic in one place.
+//
+// Fortunately memcpy() is very fast.  In optimized mode, compilers replace
+// calls to memcpy() with inline object code when the size argument is a
+// compile-time constant.  On a 32-bit system, memcpy(d,s,4) compiles to one
+// load and one store, and memcpy(d,s,8) compiles to two loads and two stores.
+//
+// WARNING: if Dest or Source is a non-POD type, the result of the memcpy
+// is likely to surprise you.
+
+template <class Dest, class Source>
+inline Dest bit_cast(const Source& source) {
+  static_assert(sizeof(Dest) == sizeof(Source),
+                "bit_cast requires source and destination to be the same size");
+
+  Dest dest;
+  memcpy(&dest, &source, sizeof(dest));
+  return dest;
+}
+
+#endif  // BASE_BIT_CAST_H_
--- a/security/sandbox/chromium/base/callback.h
+++ b/security/sandbox/chromium/base/callback.h
@@ -1,13 +1,8 @@
-// This file was GENERATED by command:
-//     pump.py callback.h.pump
-// DO NOT EDIT BY HAND!!!
-
-
 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
 #ifndef BASE_CALLBACK_H_
 #define BASE_CALLBACK_H_
 
 #include "base/callback_forward.h"
@@ -26,17 +21,17 @@
 // performing partial application of functions.
 //
 // Partial application (or "currying") is the process of binding a subset of
 // a function's arguments to produce another function that takes fewer
 // arguments. This can be used to pass around a unit of delayed execution,
 // much like lexical closures are used in other languages. For example, it
 // is used in Chromium code to schedule tasks on different MessageLoops.
 //
-// A callback with no unbound input parameters (base::Callback<void(void)>)
+// A callback with no unbound input parameters (base::Callback<void()>)
 // is called a base::Closure. Note that this is NOT the same as what other
 // languages refer to as a closure -- it does not retain a reference to its
 // enclosing environment.
 //
 // MEMORY MANAGEMENT AND PASSING
 //
 // The Callback objects themselves should be passed by const-reference, and
 // stored by copy. They internally store their state via a refcounted class
@@ -48,31 +43,31 @@
 //
 // -----------------------------------------------------------------------------
 // Quick reference for basic stuff
 // -----------------------------------------------------------------------------
 //
 // BINDING A BARE FUNCTION
 //
 //   int Return5() { return 5; }
-//   base::Callback<int(void)> func_cb = base::Bind(&Return5);
+//   base::Callback<int()> func_cb = base::Bind(&Return5);
 //   LOG(INFO) << func_cb.Run();  // Prints 5.
 //
 // BINDING A CLASS METHOD
 //
 //   The first argument to bind is the member function to call, the second is
 //   the object on which to call it.
 //
 //   class Ref : public base::RefCountedThreadSafe<Ref> {
 //    public:
 //     int Foo() { return 3; }
 //     void PrintBye() { LOG(INFO) << "bye."; }
 //   };
 //   scoped_refptr<Ref> ref = new Ref();
-//   base::Callback<void(void)> ref_cb = base::Bind(&Ref::Foo, ref);
+//   base::Callback<void()> ref_cb = base::Bind(&Ref::Foo, ref);
 //   LOG(INFO) << ref_cb.Run();  // Prints out 3.
 //
 //   By default the object must support RefCounted or you will get a compiler
 //   error. If you're passing between threads, be sure it's
 //   RefCountedThreadSafe! See "Advanced binding of member functions" below if
 //   you don't want to use reference counting.
 //
 // RUNNING A CALLBACK
@@ -104,20 +99,20 @@
 // PASSING BOUND INPUT PARAMETERS
 //
 //   Bound parameters are specified when you create thee callback as arguments
 //   to Bind(). They will be passed to the function and the Run()ner of the
 //   callback doesn't see those values or even know that the function it's
 //   calling.
 //
 //   void MyFunc(int i, const std::string& str) {}
-//   base::Callback<void(void)> cb = base::Bind(&MyFunc, 23, "hello world");
+//   base::Callback<void()> cb = base::Bind(&MyFunc, 23, "hello world");
 //   cb.Run();
 //
-//   A callback with no unbound input parameters (base::Callback<void(void)>)
+//   A callback with no unbound input parameters (base::Callback<void()>)
 //   is called a base::Closure. So we could have also written:
 //
 //   base::Closure cb = base::Bind(&MyFunc, 23, "hello world");
 //
 //   When calling member functions, bound parameters just go after the object
 //   pointer.
 //
 //   base::Closure cb = base::Bind(&MyClass::MyFunc, this, 23, "hello world");
@@ -165,27 +160,27 @@
 //   "fire and forget" cases.
 //
 // IGNORING RETURN VALUES
 //
 //   Sometimes you want to call a function that returns a value in a callback
 //   that doesn't expect a return value.
 //
 //   int DoSomething(int arg) { cout << arg << endl; }
-//   base::Callback<void<int>) cb =
+//   base::Callback<void(int)> cb =
 //       base::Bind(base::IgnoreResult(&DoSomething));
 //
 //
 // -----------------------------------------------------------------------------
 // Quick reference for binding parameters to Bind()
 // -----------------------------------------------------------------------------
 //
 // Bound parameters are specified as arguments to Bind() and are passed to the
 // function. A callback with no parameters or no unbound parameters is called a
-// Closure (base::Callback<void(void)> and base::Closure are the same thing).
+// Closure (base::Callback<void()> and base::Closure are the same thing).
 //
 // PASSING PARAMETERS OWNED BY THE CALLBACK
 //
 //   void Foo(int* arg) { cout << *arg << endl; }
 //   int* pn = new int(1);
 //   base::Closure foo_callback = base::Bind(&foo, base::Owned(pn));
 //
 //   The parameter will be deleted when the callback is destroyed, even if it's
@@ -354,417 +349,57 @@ namespace base {
 // signature that the Callback is representing.
 //
 // After this, create template specializations for 0-7 parameters. Note that
 // even though the template typelist grows, the specialization still
 // only has one type: the function signature.
 //
 // If you are thinking of forward declaring Callback in your own header file,
 // please include "base/callback_forward.h" instead.
-template <typename Sig>
-class Callback;
 
 namespace internal {
-template <typename Runnable, typename RunType, typename BoundArgsType>
+template <typename Runnable, typename RunType, typename... BoundArgsType>
 struct BindState;
 }  // namespace internal
 
-template <typename R>
-class Callback<R(void)> : public internal::CallbackBase {
+template <typename R, typename... Args>
+class Callback<R(Args...)> : public internal::CallbackBase {
  public:
-  typedef R(RunType)();
-
-  Callback() : CallbackBase(NULL) { }
-
-  // Note that this constructor CANNOT be explicit, and that Bind() CANNOT
-  // return the exact Callback<> type.  See base/bind.h for details.
-  template <typename Runnable, typename BindRunType, typename BoundArgsType>
-  Callback(internal::BindState<Runnable, BindRunType,
-           BoundArgsType>* bind_state)
-      : CallbackBase(bind_state) {
-
-    // Force the assignment to a local variable of PolymorphicInvoke
-    // so the compiler will typecheck that the passed in Run() method has
-    // the correct type.
-    PolymorphicInvoke invoke_func =
-        &internal::BindState<Runnable, BindRunType, BoundArgsType>
-            ::InvokerType::Run;
-    polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
-  }
-
-  bool Equals(const Callback& other) const {
-    return CallbackBase::Equals(other);
-  }
+  // MSVC 2013 doesn't support Type Alias of function types.
+  // Revisit this after we update it to newer version.
+  typedef R RunType(Args...);
 
-  R Run() const {
-    PolymorphicInvoke f =
-        reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
-
-    return f(bind_state_.get());
-  }
-
- private:
-  typedef R(*PolymorphicInvoke)(
-      internal::BindStateBase*);
-
-};
+  Callback() : CallbackBase(nullptr) { }
 
-template <typename R, typename A1>
-class Callback<R(A1)> : public internal::CallbackBase {
- public:
-  typedef R(RunType)(A1);
-
-  Callback() : CallbackBase(NULL) { }
-
-  // Note that this constructor CANNOT be explicit, and that Bind() CANNOT
-  // return the exact Callback<> type.  See base/bind.h for details.
-  template <typename Runnable, typename BindRunType, typename BoundArgsType>
-  Callback(internal::BindState<Runnable, BindRunType,
-           BoundArgsType>* bind_state)
+  template <typename Runnable, typename BindRunType, typename... BoundArgsType>
+  explicit Callback(
+      internal::BindState<Runnable, BindRunType, BoundArgsType...>* bind_state)
       : CallbackBase(bind_state) {
-
     // Force the assignment to a local variable of PolymorphicInvoke
     // so the compiler will typecheck that the passed in Run() method has
     // the correct type.
     PolymorphicInvoke invoke_func =
-        &internal::BindState<Runnable, BindRunType, BoundArgsType>
-            ::InvokerType::Run;
-    polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
-  }
-
-  bool Equals(const Callback& other) const {
-    return CallbackBase::Equals(other);
-  }
-
-  R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1) const {
-    PolymorphicInvoke f =
-        reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
-
-    return f(bind_state_.get(), internal::CallbackForward(a1));
-  }
-
- private:
-  typedef R(*PolymorphicInvoke)(
-      internal::BindStateBase*,
-          typename internal::CallbackParamTraits<A1>::ForwardType);
-
-};
-
-template <typename R, typename A1, typename A2>
-class Callback<R(A1, A2)> : public internal::CallbackBase {
- public:
-  typedef R(RunType)(A1, A2);
-
-  Callback() : CallbackBase(NULL) { }
-
-  // Note that this constructor CANNOT be explicit, and that Bind() CANNOT
-  // return the exact Callback<> type.  See base/bind.h for details.
-  template <typename Runnable, typename BindRunType, typename BoundArgsType>
-  Callback(internal::BindState<Runnable, BindRunType,
-           BoundArgsType>* bind_state)
-      : CallbackBase(bind_state) {
-
-    // Force the assignment to a local variable of PolymorphicInvoke
-    // so the compiler will typecheck that the passed in Run() method has
-    // the correct type.
-    PolymorphicInvoke invoke_func =
-        &internal::BindState<Runnable, BindRunType, BoundArgsType>
-            ::InvokerType::Run;
-    polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
-  }
-
-  bool Equals(const Callback& other) const {
-    return CallbackBase::Equals(other);
-  }
-
-  R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1,
-        typename internal::CallbackParamTraits<A2>::ForwardType a2) const {
-    PolymorphicInvoke f =
-        reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
-
-    return f(bind_state_.get(), internal::CallbackForward(a1),
-             internal::CallbackForward(a2));
-  }
-
- private:
-  typedef R(*PolymorphicInvoke)(
-      internal::BindStateBase*,
-          typename internal::CallbackParamTraits<A1>::ForwardType,
-          typename internal::CallbackParamTraits<A2>::ForwardType);
-
-};
-
-template <typename R, typename A1, typename A2, typename A3>
-class Callback<R(A1, A2, A3)> : public internal::CallbackBase {
- public:
-  typedef R(RunType)(A1, A2, A3);
-
-  Callback() : CallbackBase(NULL) { }
-
-  // Note that this constructor CANNOT be explicit, and that Bind() CANNOT
-  // return the exact Callback<> type.  See base/bind.h for details.
-  template <typename Runnable, typename BindRunType, typename BoundArgsType>
-  Callback(internal::BindState<Runnable, BindRunType,
-           BoundArgsType>* bind_state)
-      : CallbackBase(bind_state) {
-
-    // Force the assignment to a local variable of PolymorphicInvoke
-    // so the compiler will typecheck that the passed in Run() method has
-    // the correct type.
-    PolymorphicInvoke invoke_func =
-        &internal::BindState<Runnable, BindRunType, BoundArgsType>
+        &internal::BindState<Runnable, BindRunType, BoundArgsType...>
             ::InvokerType::Run;
     polymorphic_invoke_ = reinterpret_cast<InvokeFuncStorage>(invoke_func);
   }
 
   bool Equals(const Callback& other) const {
     return CallbackBase::Equals(other);
   }
 
-  R Run(typename internal::CallbackParamTraits<A1>::ForwardType a1,
-        typename internal::Cal