Merge inbound to central, a=merge
authorWes Kocher <wkocher@mozilla.com>
Wed, 29 Mar 2017 15:41:57 -0700
changeset 350451 60d7a0496a3673450ddbc37ec387525148c32604
parent 350450 fc2eda92be4091d5ea0828f51fe4aaee41ed8319 (current diff)
parent 350391 0d83d5d9e3247db6ea37dfd56574a1c8172a0bb1 (diff)
child 350452 83d25c5fdde7aa894cc4cb27e0eac220e5ffc8ec
child 350523 a11e870ae60359e13822885930e06968484dc449
push id88627
push userkwierso@gmail.com
push dateWed, 29 Mar 2017 22:48:01 +0000
treeherdermozilla-inbound@83d25c5fdde7 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge
milestone55.0a1
first release with
nightly linux32
60d7a0496a36 / 55.0a1 / 20170330100130 / files
nightly linux64
60d7a0496a36 / 55.0a1 / 20170330100130 / files
nightly mac
60d7a0496a36 / 55.0a1 / 20170330030213 / files
nightly win32
60d7a0496a36 / 55.0a1 / 20170330030213 / files
nightly win64
60d7a0496a36 / 55.0a1 / 20170330030213 / files
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
releases
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Merge inbound to central, a=merge
dom/base/nsGlobalWindow.cpp
modules/libpref/init/all.js
security/sandbox/chromium-shim/base/MissingBasicTypes.h
security/sandbox/chromium/base/bind_internal_win.h
security/sandbox/chromium/base/memory/scoped_ptr.h
security/sandbox/chromium/base/move.h
security/sandbox/chromium/base/threading/platform_thread_linux.cc
security/sandbox/chromium/base/threading/thread_local_posix.cc
security/sandbox/chromium/base/threading/thread_local_win.cc
security/sandbox/chromium/sandbox/win/src/Wow64.cc
security/sandbox/chromium/sandbox/win/src/Wow64.h
security/sandbox/chromium/sandbox/win/src/Wow64_64.cc
security/sandbox/chromium/sandbox/win/src/app_container.cc
security/sandbox/chromium/sandbox/win/src/app_container.h
security/sandbox/chromium/sandbox/win/src/app_container_unittest.cc
--- 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 1265818 - deleted an exported header and added a new .idl to regenerate that same header; and this unfortunately produces an untracked generated header in your source dir whenever you build (probably due to a dangling symlink), unless you clobber
+Bug 1337331 - Required because of removed cc files like security/sandbox/chromium/base/threading/platform_thread_linux.cc
--- a/accessible/generic/DocAccessible.cpp
+++ b/accessible/generic/DocAccessible.cpp
@@ -2183,17 +2183,24 @@ DocAccessible::PutChildrenBack(nsTArray<
     child->SetRelocated(false);
 
     int32_t idxInParent = -1;
     Accessible* origContainer = GetContainerAccessible(child->GetContent());
     if (origContainer) {
       TreeWalker walker(origContainer);
       if (walker.Seek(child->GetContent())) {
         Accessible* prevChild = walker.Prev();
-        idxInParent = prevChild ? prevChild->IndexInParent() + 1 : 0;
+        if (prevChild) {
+          idxInParent = prevChild->IndexInParent() + 1;
+          MOZ_ASSERT(origContainer == prevChild->Parent(), "Broken tree");
+          origContainer = prevChild->Parent();
+        }
+        else {
+          idxInParent = 0;
+        }
       }
     }
     MoveChild(child, origContainer, idxInParent);
   }
 
   aChildren->RemoveElementsAt(aStartIdx, aChildren->Length() - aStartIdx);
 }
 
@@ -2240,16 +2247,21 @@ DocAccessible::MoveChild(Accessible* aCh
   curParent->RemoveChild(aChild);
   rmut.Done();
 
   // No insertion point for the child.
   if (aIdxInParent == -1) {
     return true;
   }
 
+  if (aIdxInParent > static_cast<int32_t>(aNewParent->ChildCount())) {
+    MOZ_ASSERT_UNREACHABLE("Wrong insertion point for a moving child");
+    return true;
+  }
+
   TreeMutation imut(aNewParent);
   aNewParent->InsertChildAt(aIdxInParent, aChild);
   imut.AfterInsertion(aChild);
   imut.Done();
 
 #ifdef A11Y_LOG
   logging::TreeInfo("move child: old parent tree after",
                     logging::eVerbose, curParent);
--- a/accessible/windows/msaa/Platform.cpp
+++ b/accessible/windows/msaa/Platform.cpp
@@ -81,17 +81,20 @@ a11y::ProxyCreated(ProxyAccessible* aPro
   aProxy->SetWrapper(reinterpret_cast<uintptr_t>(wrapper));
 }
 
 void
 a11y::ProxyDestroyed(ProxyAccessible* aProxy)
 {
   AccessibleWrap* wrapper =
     reinterpret_cast<AccessibleWrap*>(aProxy->GetWrapper());
-  MOZ_ASSERT(wrapper);
+
+  // If aProxy is a document that was created, but
+  // RecvPDocAccessibleConstructor failed then aProxy->GetWrapper() will be
+  // null.
   if (!wrapper)
     return;
 
   if (aProxy->IsDoc() && nsWinUtils::IsWindowEmulationStarted()) {
     aProxy->AsDoc()->SetEmulatedWindowHandle(nullptr);
   }
 
   wrapper->Shutdown();
--- a/browser/base/content/tab-content.js
+++ b/browser/base/content/tab-content.js
@@ -706,18 +706,18 @@ if (Services.appinfo.processType == Serv
 }
 
 var WebBrowserChrome = {
   onBeforeLinkTraversal(originalTarget, linkURI, linkNode, isAppTab) {
     return BrowserUtils.onBeforeLinkTraversal(originalTarget, linkURI, linkNode, isAppTab);
   },
 
   // Check whether this URI should load in the current process
-  shouldLoadURI(aDocShell, aURI, aReferrer, aTriggeringPrincipal) {
-    if (!E10SUtils.shouldLoadURI(aDocShell, aURI, aReferrer)) {
+  shouldLoadURI(aDocShell, aURI, aReferrer, aHasPostData, aTriggeringPrincipal) {
+    if (!E10SUtils.shouldLoadURI(aDocShell, aURI, aReferrer, aHasPostData)) {
       E10SUtils.redirectLoad(aDocShell, aURI, aReferrer, aTriggeringPrincipal, false);
       return false;
     }
 
     return true;
   },
 
   shouldLoadURIInThisProcess(aURI) {
--- a/browser/components/originattributes/test/browser/browser_firstPartyIsolation_aboutPages.js
+++ b/browser/components/originattributes/test/browser/browser_firstPartyIsolation_aboutPages.js
@@ -28,28 +28,28 @@ add_task(function* test_remote_window_op
                  "remote about:blank should have firstPartyDomain set");
   });
 
   win.close();
 });
 
 /**
  * For loading the initial about:blank in non-e10s mode, it will be loaded with
- * codebase principal. So we test if it has correct firstPartyDomain set.
+ * a null principal. So we test if it has correct firstPartyDomain set.
  */
 add_task(function* test_nonremote_window_open_aboutBlank() {
   let win = yield BrowserTestUtils.openNewBrowserWindow({remote: false});
   let browser = win.gBrowser.selectedBrowser;
 
   Assert.ok(!browser.isRemoteBrowser, "shouldn't be a remote browser");
 
   let attrs = { firstPartyDomain: "about.ef2a7dd5-93bc-417f-a698-142c3116864f.mozilla" };
   yield ContentTask.spawn(browser, attrs, function* (expectAttrs) {
-    Assert.ok(content.document.nodePrincipal.isCodebasePrincipal,
-              "The principal of non-remote about:blank should be a codebase principal.");
+    Assert.ok(!content.document.nodePrincipal.isCodebasePrincipal,
+              "The principal of non-remote about:blank should not be a codebase principal.");
     Assert.equal(content.document.nodePrincipal.originAttributes.firstPartyDomain,
                  expectAttrs.firstPartyDomain,
                  "non-remote about:blank should have firstPartyDomain set");
   });
 
   win.close();
 });
 
--- a/browser/components/preferences/permissions.js
+++ b/browser/components/preferences/permissions.js
@@ -90,18 +90,19 @@ var gPermissionManager = {
       // `localhost:8080` as having the scheme `localhost`, rather than being
       // an invalid URI. A canonical origin representation is required by the
       // permission manager for storage, so this won't prevent any valid
       // permissions from being entered by the user.
       let uri;
       try {
         uri = Services.io.newURI(input_url);
         principal = Services.scriptSecurityManager.createCodebasePrincipal(uri, {});
-        // If we have ended up with an unknown scheme, the following will throw.
-        principal.origin;
+        if (principal.origin.startsWith("moz-nullprincipal:")) {
+          throw "Null principal";
+        }
       } catch (ex) {
         uri = Services.io.newURI("http://" + input_url);
         principal = Services.scriptSecurityManager.createCodebasePrincipal(uri, {});
         // If we have ended up with an unknown scheme, the following will throw.
         principal.origin;
       }
     } catch (ex) {
       var message = this._bundle.getString("invalidURI");
--- a/browser/locales/jar.mn
+++ b/browser/locales/jar.mn
@@ -106,16 +106,17 @@
 #else
     locale/browser/searchplugins/               (.deps/generated_@AB_CD@/*.xml)
     locale/browser/searchplugins/list.json      (.deps/generated_@AB_CD@/list.json)
 #endif
     locale/browser/searchplugins/images/amazon.ico     (searchplugins/images/amazon.ico)
     locale/browser/searchplugins/images/wikipedia.ico  (searchplugins/images/wikipedia.ico)
     locale/browser/searchplugins/images/yahoo.ico      (searchplugins/images/yahoo.ico)
     locale/browser/searchplugins/images/yandex-en.ico  (searchplugins/images/yandex-en.ico)
+    locale/browser/searchplugins/images/yandex-ru.ico  (searchplugins/images/yandex-ru.ico)
 % locale browser-region @AB_CD@ %locale/browser-region/
     locale/browser-region/region.properties        (%chrome/browser-region/region.properties)
 # the following files are browser-specific overrides
     locale/browser/netError.dtd                (%chrome/overrides/netError.dtd)
     locale/browser/appstrings.properties       (%chrome/overrides/appstrings.properties)
     locale/browser/downloads/settingsChange.dtd  (%chrome/overrides/settingsChange.dtd)
 % override chrome://global/locale/netError.dtd chrome://browser/locale/netError.dtd
 % override chrome://global/locale/appstrings.properties chrome://browser/locale/appstrings.properties
new file mode 100644
index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..226fc0a0711cf5a048b631a3dfb292ec1c55027b
GIT binary patch
literal 2034
zc$@+92MzcD0096301yxW0096X08;`0044wc03aX$0096X0C@!f0C@rc0EtjeM-2)Z
z3IG5A4M|8uQUCw|5C8xG5C{eU001BJ|6u?C0vbs~K~y-6jgn7DR8bVhfA`G{TG_&J
z8pudpC}}}R2)U>rAquR85F<vbXi=M1;VwvMQ!S)HYB6F9$!%={`y-J>L7O02lwfF4
zqfG-5I{9YayI+gvo8IIizr$IabI<qPbI!d6=m5HbIyQ$HARkQ(7K_D_Hi1H+@C!H*
zB|AWUGTFEVMCkf5k1h_tkyhwU!yX4&pHxG`_OY?CL11T8<earu)>>K5Q@N0r-@jjW
zphuOruT&YoDRsu>xvqTI)$;Q43eX?zz(E2Di*RPAF(2RIUAcw!9l$iVfH7Djh{f2E
zN^Q$#vqQkHP#`7(1K`sKXzRcv(?MKztF8LhLx@Z!GXV7b6_5zrLQ@*Pe*?b~uo4L{
z1|X=hmQ<=~>*(m{8DMvf0DyY?FusqucL#%ka+zR6Fvei5k0dgg)2D!g@lc?O_Ab1u
zw~1f7gnjl9>gvJss$F0VlCTzlm;=PZC5AVtuOFqGp?xnpd^{l6)QG96$w$B&fMIv-
zw?Z$wYw~i}rLKhBrLU^Id@Oaw6|GrZTqpr&0XB|MTEX0(#2!5fjY-VUAJqkhn3%Zx
z1bDsi84Wlurg7%pV}~wai~(zdxz{b9Un-4^j64A5!wwAL3rLvU4g5pL@VdH#<yjF6
z4gtuG=bi$y(XV{@^WuVAT3ylqe12|j6*wOy$AOua*0uytPc6*)i2gtM=h5H~Zcl9I
zXNKMr00000NkvXXu0mjfiBL{Q4GJ0x0000DNk~Le0000W0000W2nGNE0CReJ^Z)<_
zKuJVFR9J<zmuqZPMHI(>Gk19xh|(^FT1<Q)2#Ep#BSeTqLPS)2P$8)V{Avt|35hgO
zY*Gxim7oY{tHxAQQHX+%76^$C5X7W>P=sL6lmhLp$fHo8?amxO%-!C*-MxjxdNwC_
zGmroO%$ak}%qX0U0VV^Z0FVBay+CVJrw5D%9s=?J-OuFsxF`A=FdrywXlQ7-cI}#x
zew2!eij6=i&cl(i6j;{P)n)sWTtp<1NL&Dx0gptHYhVDtfB`WDLQWMM{Qu)Oc(V)^
zO@(`h!(A#<O$zDi1Z#-L^GB{*x9$O;Aj%60SPo#V{UE1_BA}G}`^hHsTWg^Gtm`u%
zgNLF_H>A4Vm}AC`w-&S}nM}4978b4q62P~)JfM8d6l)!MDg`3QM;p-PFF^ZQWYie!
z%GZ(44j`ZILmn@62-?N4q*6Ub$K&x4RaI59fI^@s*BVy<E37q=p{Z`M-JN2)yTtx_
zNbLQiMaCmCvq<d0@7x%Z5^If^x7WD7@!GYe)yHaWZEg2?7Uc4P)81RJwA*^6;hWD<
z=M!K-o_i6d&V-b4Dxf<%Lt6$In}Ibt9v@y=SveaQ2SvRNP=JaEKjhLy_`L}fNMSKD
zYaZ5GtTBk^AtG2Z`K`5xNCr-6Y3Y+b*R<Ro$U(0ZaN!?R;tT-lrcp4q7==YC0n-iE
z_*s&U9fPu|%*;V3D9F#Nu6|>-9}C6V9uOCE8LB-u-6ycx!|E8KV+h*+D)3@~2L!~6
zAxdZAEnQmrgwHqihCBd*3>=6I&2ytWuc9tr2=XSaA|a<*mjQ|_tb&64Vb#^ubAYjF
zF9c~A5d`YyIBM)TXKk_-{yYxWPfsiUxWEACtmvAyq@-k_&p9K*146_v7DFaa0}EU_
zkJ_~@Xh+=ksNf6}ETV`)qhNG===$|lb8s1P>vcVVfSq50jJp#Q=r8Ngo7ckS%V1m@
zikM&rln!ltZoI`$mn`skr^kE`;F2bXSPMnP*q7Ggt$rS^w4*n^24C01J@+9)hM|u%
zIdBBD3SkL3i>&)-K*xd+5e8`G96NU*cEeV@s@3RYhtbW)q2+i8Q3WekVbW~e`udL>
zecpr7l`yR7V4FS%CQWfOhU8)AJ%e4o3Yj$B4OD(w^numZmb|)Z)yw;Fhf{Np2O_rs
zT(R*y)X~G}Jzu!ExczQY<y&CTVDvj4u_K3Yq0|QsP*+!%Ui|@po*0OnCj#1Y+uOJe
z+RuRnyPyOH4GDs+XM8kyBAL8WR#tWpXaoLA8_;(Qq|@xoNz~4I=a5@&!_HsaQ-akE
zTJT}*`@4L;{pq$K3nD$>)Z6hf`fMv`u#Y|q`EexW(l0zW3a7O#(eY||`7eZ4pElsS
zS)k7Ujo!80k&i6EJiN#coN(C<TbwPmwKcnau6^P5P#uUC)wmsf;;1uV?qkRu6Hp?E
z&JLekI4v!wIw~sGHsRg}8CUec15qJx=^|d^Hur)UJOVrKDL^5{1XV9%LN-QCP3<0^
z=ZD^X!8saXfp=gp-r=7>gPAfDJL5q>P@X$Ld(Tn|BxKa7(=8p9m6c7vX>vSJf;5Z}
zZ|l4MX%WLLT;dw7Md_F`0??tuNNbHT>EIMLZF+CF&+%g}d<Coq1|}1USMu_PWf$%U
z(OPE)pZF(Ws4g@&pX``0abgv43aHJA1GE6_{A$O~ot;;skFZ{9t-+d*T7#so^8PWs
zdCQhYpXd9ig(%$3WCj1v!xY@=Yoa<mpdC1gdzz2%+j?KR{)_Ga&P5sUFYJGWr;6fm
QN&o-=07*qoM6N<$g3@QE6951J
--- a/browser/locales/searchplugins/yandex-az.xml
+++ b/browser/locales/searchplugins/yandex-az.xml
@@ -1,17 +1,22 @@
 <!-- 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/. -->
 
 <SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
 <ShortName>Yandex</ShortName>
 <Description>İnternetdə axtarış üçün Yandexdən istifadə edin.</Description>
 <InputEncoding>UTF-8</InputEncoding>
-<Image width="16" height="16">data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAB50lEQVQ4T43SvWsacRgH8OcPCITSLRQ6BSRL1gxZTNZQsgYC3QKunVoMnTKFhBQSnDqIUa5gxNbBCgriC4pv50sJ1lIR5SROpRVbz+O4b5/flbvedekJH+557nvfH8chdbvdIFMYPAgBICdqt9uKpmnw8huNRuDnX8J5QKvVgmEYnqiqClmWwZ113kmger0OXdf/Wv6EIb0BTo+AgB94ceDKJ5MJuHPOMwlUqVSwWq1sevQaxqvn0O5l6HdvgaMdV75cLtFoNMC9Xd6JisWiedNiPNuB9l4yZ+1jEvBvuXJBURRwL8YzUT6fx2KxsGHrKdQPCXNW794Bvieu3CLegrsnlM1mMZ/PbfqeH6vToDkvb2+Bx49cuWU2m4G7bUqn0xiPx7ZpqYRf29v4cXyMxf4+tLU1V24ZDAbgbptSqRSGw6HL9OwM37n4bXPTvP6bC7lcDtw9oWQyiX6/b/vMH1XZ2MAoEMDXqytM+QBnLtRqNXAvxjNRPB5Hr9ez9Q8PMfD50OM/2P3FBb7wAc680+mIMri3yzuRJEloNpsmORTCJy7INzd/9stLc7dyIZPJgDvnPJNA0WgU1WrVkxJ/4FgsBu6s804CRSKRh0KhgHK5/F+JRAL8fJBnslA4HH7NHhg8CDnLwm8IYz560xw92AAAAABJRU5ErkJggg==</Image>
-<Url type="application/x-suggestions+json" method="GET" template="https://suggest.yandex.net/suggest-ff.cgi">
+<Image width="16" height="16">resource://search-plugins/images/yandex-ru.ico</Image>
+<Url type="application/x-suggestions+json" method="GET" template="https://suggest.yandex.ru/suggest-ff.cgi">
   <Param name="part" value="{searchTerms}"/>
 </Url>
 <Url type="text/html" method="GET" template="https://yandex.ru/yandsearch" resultdomain="yandex.ru">
-  <Param name="text" value="{searchTerms}"/>
+  <MozParam name="clid" condition="purpose" purpose="searchbar"   value="2186618"/>
+  <MozParam name="clid" condition="purpose" purpose="keyword"     value="2186621"/>
+  <MozParam name="clid" condition="purpose" purpose="contextmenu" value="2186623"/>
+  <MozParam name="clid" condition="purpose" purpose="homepage"    value="2186617"/>
+  <MozParam name="clid" condition="purpose" purpose="newtab"      value="2186620"/>
+  <Param    name="text" value="{searchTerms}"/>
 </Url>
 <SearchForm>https://www.yandex.ru/</SearchForm>
 </SearchPlugin>
--- a/browser/locales/searchplugins/yandex-by.xml
+++ b/browser/locales/searchplugins/yandex-by.xml
@@ -1,18 +1,18 @@
 <!-- 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/. -->
 
 <SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
 <ShortName>Яндекс</ShortName>
 <Description>Пошук з дапамогаю Яндекс</Description>
 <InputEncoding>UTF-8</InputEncoding>
-<Image width="16" height="16">data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAB50lEQVQ4T43SvWsacRgH8OcPCITSLRQ6BSRL1gxZTNZQsgYC3QKunVoMnTKFhBQSnDqIUa5gxNbBCgriC4pv50sJ1lIR5SROpRVbz+O4b5/flbvedekJH+557nvfH8chdbvdIFMYPAgBICdqt9uKpmnw8huNRuDnX8J5QKvVgmEYnqiqClmWwZ113kmger0OXdf/Wv6EIb0BTo+AgB94ceDKJ5MJuHPOMwlUqVSwWq1sevQaxqvn0O5l6HdvgaMdV75cLtFoNMC9Xd6JisWiedNiPNuB9l4yZ+1jEvBvuXJBURRwL8YzUT6fx2KxsGHrKdQPCXNW794Bvieu3CLegrsnlM1mMZ/PbfqeH6vToDkvb2+Bx49cuWU2m4G7bUqn0xiPx7ZpqYRf29v4cXyMxf4+tLU1V24ZDAbgbptSqRSGw6HL9OwM37n4bXPTvP6bC7lcDtw9oWQyiX6/b/vMH1XZ2MAoEMDXqytM+QBnLtRqNXAvxjNRPB5Hr9ez9Q8PMfD50OM/2P3FBb7wAc680+mIMri3yzuRJEloNpsmORTCJy7INzd/9stLc7dyIZPJgDvnPJNA0WgU1WrVkxJ/4FgsBu6s804CRSKRh0KhgHK5/F+JRAL8fJBnslA4HH7NHhg8CDnLwm8IYz560xw92AAAAABJRU5ErkJggg==</Image>
-<Url type="application/x-suggestions+json" method="GET" template="https://suggest.yandex.net/suggest-ff.cgi">
+<Image width="16" height="16">resource://search-plugins/images/yandex-ru.ico</Image>
+<Url type="application/x-suggestions+json" method="GET" template="https://suggest.yandex.by/suggest-ff.cgi">
   <Param name="part" value="{searchTerms}"/>
 </Url>
 <Url type="text/html" method="GET" template="https://yandex.by/yandsearch" resultdomain="yandex.by">
   <MozParam name="clid" condition="purpose" purpose="searchbar"   value="2186618"/>
   <MozParam name="clid" condition="purpose" purpose="keyword"     value="2186621"/>
   <MozParam name="clid" condition="purpose" purpose="contextmenu" value="2186623"/>
   <MozParam name="clid" condition="purpose" purpose="homepage"    value="2186617"/>
   <MozParam name="clid" condition="purpose" purpose="newtab"      value="2186620"/>
--- a/browser/locales/searchplugins/yandex-kk.xml
+++ b/browser/locales/searchplugins/yandex-kk.xml
@@ -1,18 +1,18 @@
 <!-- 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/. -->
 
 <SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
 <ShortName>Яндекс</ShortName>
 <Description>Воспользуйтесь Яндексом для поиска в Интернете.</Description>
 <InputEncoding>UTF-8</InputEncoding>
-<Image width="16" height="16">data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAB50lEQVQ4T43SvWsacRgH8OcPCITSLRQ6BSRL1gxZTNZQsgYC3QKunVoMnTKFhBQSnDqIUa5gxNbBCgriC4pv50sJ1lIR5SROpRVbz+O4b5/flbvedekJH+557nvfH8chdbvdIFMYPAgBICdqt9uKpmnw8huNRuDnX8J5QKvVgmEYnqiqClmWwZ113kmger0OXdf/Wv6EIb0BTo+AgB94ceDKJ5MJuHPOMwlUqVSwWq1sevQaxqvn0O5l6HdvgaMdV75cLtFoNMC9Xd6JisWiedNiPNuB9l4yZ+1jEvBvuXJBURRwL8YzUT6fx2KxsGHrKdQPCXNW794Bvieu3CLegrsnlM1mMZ/PbfqeH6vToDkvb2+Bx49cuWU2m4G7bUqn0xiPx7ZpqYRf29v4cXyMxf4+tLU1V24ZDAbgbptSqRSGw6HL9OwM37n4bXPTvP6bC7lcDtw9oWQyiX6/b/vMH1XZ2MAoEMDXqytM+QBnLtRqNXAvxjNRPB5Hr9ez9Q8PMfD50OM/2P3FBb7wAc680+mIMri3yzuRJEloNpsmORTCJy7INzd/9stLc7dyIZPJgDvnPJNA0WgU1WrVkxJ/4FgsBu6s804CRSKRh0KhgHK5/F+JRAL8fJBnslA4HH7NHhg8CDnLwm8IYz560xw92AAAAABJRU5ErkJggg==</Image>
-<Url type="application/x-suggestions+json" method="GET" template="https://suggest.yandex.net/suggest-ff.cgi">
+<Image width="16" height="16">resource://search-plugins/images/yandex-ru.ico</Image>
+<Url type="application/x-suggestions+json" method="GET" template="https://suggest.yandex.kz/suggest-ff.cgi">
   <Param name="part" value="{searchTerms}"/>
 </Url>
 <Url type="text/html" method="GET" template="https://yandex.kz/yandsearch" resultdomain="yandex.kz">
   <MozParam name="clid" condition="purpose" purpose="searchbar"   value="2186618"/>
   <MozParam name="clid" condition="purpose" purpose="keyword"     value="2186621"/>
   <MozParam name="clid" condition="purpose" purpose="contextmenu" value="2186623"/>
   <MozParam name="clid" condition="purpose" purpose="homepage"    value="2186617"/>
   <MozParam name="clid" condition="purpose" purpose="newtab"      value="2186620"/>
--- a/browser/locales/searchplugins/yandex-ru.xml
+++ b/browser/locales/searchplugins/yandex-ru.xml
@@ -1,18 +1,18 @@
 <!-- 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/. -->
 
 <SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
 <ShortName>Яндекс</ShortName>
 <Description>Воспользуйтесь Яндексом для поиска в Интернете.</Description>
 <InputEncoding>UTF-8</InputEncoding>
-<Image width="16" height="16">data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAB50lEQVQ4T43SvWsacRgH8OcPCITSLRQ6BSRL1gxZTNZQsgYC3QKunVoMnTKFhBQSnDqIUa5gxNbBCgriC4pv50sJ1lIR5SROpRVbz+O4b5/flbvedekJH+557nvfH8chdbvdIFMYPAgBICdqt9uKpmnw8huNRuDnX8J5QKvVgmEYnqiqClmWwZ113kmger0OXdf/Wv6EIb0BTo+AgB94ceDKJ5MJuHPOMwlUqVSwWq1sevQaxqvn0O5l6HdvgaMdV75cLtFoNMC9Xd6JisWiedNiPNuB9l4yZ+1jEvBvuXJBURRwL8YzUT6fx2KxsGHrKdQPCXNW794Bvieu3CLegrsnlM1mMZ/PbfqeH6vToDkvb2+Bx49cuWU2m4G7bUqn0xiPx7ZpqYRf29v4cXyMxf4+tLU1V24ZDAbgbptSqRSGw6HL9OwM37n4bXPTvP6bC7lcDtw9oWQyiX6/b/vMH1XZ2MAoEMDXqytM+QBnLtRqNXAvxjNRPB5Hr9ez9Q8PMfD50OM/2P3FBb7wAc680+mIMri3yzuRJEloNpsmORTCJy7INzd/9stLc7dyIZPJgDvnPJNA0WgU1WrVkxJ/4FgsBu6s804CRSKRh0KhgHK5/F+JRAL8fJBnslA4HH7NHhg8CDnLwm8IYz560xw92AAAAABJRU5ErkJggg==</Image>
-<Url type="application/x-suggestions+json" method="GET" template="https://suggest.yandex.net/suggest-ff.cgi">
+<Image width="16" height="16">resource://search-plugins/images/yandex-ru.ico</Image>
+<Url type="application/x-suggestions+json" method="GET" template="https://suggest.yandex.ru/suggest-ff.cgi">
   <Param name="part" value="{searchTerms}"/>
 </Url>
 <Url type="text/html" method="GET" template="https://yandex.ru/yandsearch" resultdomain="yandex.ru">
   <MozParam name="clid" condition="purpose" purpose="searchbar"   value="2186618"/>
   <MozParam name="clid" condition="purpose" purpose="keyword"     value="2186621"/>
   <MozParam name="clid" condition="purpose" purpose="contextmenu" value="2186623"/>
   <MozParam name="clid" condition="purpose" purpose="homepage"    value="2186617"/>
   <MozParam name="clid" condition="purpose" purpose="newtab"      value="2186620"/>
--- a/browser/locales/searchplugins/yandex-tr.xml
+++ b/browser/locales/searchplugins/yandex-tr.xml
@@ -1,22 +1,22 @@
 <!-- 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/. -->
 
 <SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
 <ShortName>Yandex</ShortName>
 <Description>Yandex Türkiye arama motoru</Description>
 <InputEncoding>UTF-8</InputEncoding>
-<Image width="16" height="16">data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAABILAAASCwAAAAAAAAAAAAAAAAAsAAAAUwAAAF8AAABfAAAAXwAAAF8AAABfAAAAXwAAAF8AAABfAAAAXwAAADjBwcEAwcHBAMHBwQDBwcEAAAAAUbq6uurExMT/xMTE/8TExP/ExMT/xMTE/8TExP/ExMT/xMTE/8TExP9ubm6QAAAALcTExADExMQAxMTEAAAAAFrHx8f/x8fH/8fHx/+7u8j/AADS/wAA0v+wsMj/x8fH/8fHx//Hx8f/vr6+7h4eHmQAAAAQx8fHAMfHxwAAAABXy8vL/8vLy//Ly8v/v7/M/wAA2/8AANv/s7PN/8vLy//Ly8v/y8vL/8vLy/+kpKS6AAAAM8vLywDLy8sAAAAAU9DQ0P/Q0ND/0NDQ/8TE0f8AAOX/AADl/7i40v/Q0ND/0NDQ/9DQ0P/Q0ND/0NDQ/2VlZXsAAAAk0NDQAAAAAE/U1NT/1NTU/9TU1P/IyNb/AADw/wAA8P+7u9f/1NTU/9TU1P/U1NT/1NTU/9TU1P/JycnkDw8PUwAAAAcAAABL2dnZ/9nZ2f/Z2dn/np7i/wAA+f8AAPn/goLm/9nZ2f/Z2dn/2dnZ/9nZ2f/Z2dn/2dnZ/6ioqKYAAAAqAAAASOLi4v/i4uL/4uLi/0hI9v8AAP//BQX+/yAg+//f3+L/4uLi/+Li4v/i4uL/4uLi/+Li4v/g4OD7AAAARgAAAETx8fH/8fHx/9jZ8v8LD///HiL+/3h6+P8IDP//lJX3//Hx8f/x8fH/8fHx//Hx8f/x8fH/7+/v+wAAAEIAAABA9vb2//b29v+Ah/v/Ex///3N6+//Z2vf/FiL//ys2/v/r7Pb/9vb2//b29v/29vb/9vb2/8jIyKMAAAAkAAAAPPn5+f/09Pn/NEf+/yA0///Gy/r/+fn5/1hn/f8gNP//jpj8//n5+f/5+fn/+fn5//Dw8OMXFxdBAAAABgAAADj7+/v/tb/8/y5K//9GX///+/v7//v7+/+zvfz/Lkr//zhS///l6Pv/+/v7//v7+/+Tk5NnAAAAGfv7+wAAAAA1/f39/3OM/v85Xf//mqz+//39/f/9/f3/9vf9/0do//85Xf//fpX+//39/f/c3NysAAAAH/39/QD9/f0AAAAAMv7+/v/+/v7//v7+//7+/v/+/v7//v7+//7+/v+VrP//QWn//0Fp///T3PrtPj4+PgAAAAn+/v4A/v7+AAAAACn39/fi////////////////////////////////////////////////tbW1cgAAABf///8A////AP///wAAAAAVAAAAKAAAAC4AAAAuAAAALgAAAC4AAAAuAAAALgAAAC4AAAAuAAAALgAAABv///8A////AP///wD///8AAA8AAAAHAAAAAwAAAAMAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAAMAAAADAAAABwAAAA8AAA==</Image>
-<Url type="application/x-suggestions+json" method="GET" template="http://suggest.yandex.com.tr/suggest-ff.cgi">
+<Image width="16" height="16">resource://search-plugins/images/yandex-en.ico</Image>
+<Url type="application/x-suggestions+json" method="GET" template="https://suggest.yandex.com.tr/suggest-ff.cgi">
   <Param name="part" value="{searchTerms}"/>
-  <Param name="uil" value="tr"/>
 </Url>
-<Url type="text/html" rel="searchform" method="GET" template="http://yandex.com.tr/yandsearch" resultdomain="yandex.com.tr">
+<Url type="text/html" method="GET" template="https://yandex.com.tr/yandsearch" resultdomain="yandex.com.tr">
   <MozParam name="clid" condition="purpose" purpose="searchbar"   value="2186618"/>
   <MozParam name="clid" condition="purpose" purpose="keyword"     value="2186621"/>
   <MozParam name="clid" condition="purpose" purpose="contextmenu" value="2186623"/>
   <MozParam name="clid" condition="purpose" purpose="homepage"    value="2186617"/>
   <MozParam name="clid" condition="purpose" purpose="newtab"      value="2186620"/>
-  <Param name="text" value="{searchTerms}"/>
+  <Param    name="text" value="{searchTerms}"/>
 </Url>
+<SearchForm>https://www.yandex.com.tr/</SearchForm>
 </SearchPlugin>
--- a/browser/locales/searchplugins/yandex-uk.xml
+++ b/browser/locales/searchplugins/yandex-uk.xml
@@ -1,16 +1,22 @@
 <!-- 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/. -->
 
 <SearchPlugin xmlns="http://www.mozilla.org/2006/browser/search/">
 <ShortName>Яндекс</ShortName>
 <Description>Пошук Яндексом.</Description>
 <InputEncoding>UTF-8</InputEncoding>
-<Image width="16" height="16">data:image/x-icon;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAB50lEQVQ4T43SvWsacRgH8OcPCITSLRQ6BSRL1gxZTNZQsgYC3QKunVoMnTKFhBQSnDqIUa5gxNbBCgriC4pv50sJ1lIR5SROpRVbz+O4b5/flbvedekJH+557nvfH8chdbvdIFMYPAgBICdqt9uKpmnw8huNRuDnX8J5QKvVgmEYnqiqClmWwZ113kmger0OXdf/Wv6EIb0BTo+AgB94ceDKJ5MJuHPOMwlUqVSwWq1sevQaxqvn0O5l6HdvgaMdV75cLtFoNMC9Xd6JisWiedNiPNuB9l4yZ+1jEvBvuXJBURRwL8YzUT6fx2KxsGHrKdQPCXNW794Bvieu3CLegrsnlM1mMZ/PbfqeH6vToDkvb2+Bx49cuWU2m4G7bUqn0xiPx7ZpqYRf29v4cXyMxf4+tLU1V24ZDAbgbptSqRSGw6HL9OwM37n4bXPTvP6bC7lcDtw9oWQyiX6/b/vMH1XZ2MAoEMDXqytM+QBnLtRqNXAvxjNRPB5Hr9ez9Q8PMfD50OM/2P3FBb7wAc680+mIMri3yzuRJEloNpsmORTCJy7INzd/9stLc7dyIZPJgDvnPJNA0WgU1WrVkxJ/4FgsBu6s804CRSKRh0KhgHK5/F+JRAL8fJBnslA4HH7NHhg8CDnLwm8IYz560xw92AAAAABJRU5ErkJggg==</Image>
-<Url type="application/x-suggestions+json" method="GET" template="http://suggest.yandex.net/suggest-ff.cgi?part={searchTerms}"/>
-<Url type="text/html" method="GET" template="http://www.yandex.ua/yandsearch" resultdomain="yandex.ua">
-  <Param name="text" value="{searchTerms}"/>
-  <Param name="from" value="fx3"/>
+<Image width="16" height="16">resource://search-plugins/images/yandex-ru.ico</Image>
+<Url type="application/x-suggestions+json" method="GET" template="https://suggest.yandex.ua/suggest-ff.cgi">
+  <Param name="part" value="{searchTerms}"/>
 </Url>
-<SearchForm>http://www.yandex.ua/</SearchForm>
+<Url type="text/html" method="GET" template="https://www.yandex.ua/yandsearch" resultdomain="yandex.ua">
+  <MozParam name="clid" condition="purpose" purpose="searchbar"   value="2186618"/>
+  <MozParam name="clid" condition="purpose" purpose="keyword"     value="2186621"/>
+  <MozParam name="clid" condition="purpose" purpose="contextmenu" value="2186623"/>
+  <MozParam name="clid" condition="purpose" purpose="homepage"    value="2186617"/>
+  <MozParam name="clid" condition="purpose" purpose="newtab"      value="2186620"/>
+  <Param    name="text" value="{searchTerms}"/>
+</Url>
+<SearchForm>https://www.yandex.ua/</SearchForm>
 </SearchPlugin>
--- a/caps/BasePrincipal.cpp
+++ b/caps/BasePrincipal.cpp
@@ -9,58 +9,60 @@
 #include "nsDocShell.h"
 #ifdef MOZ_CRASHREPORTER
 #include "nsExceptionHandler.h"
 #endif
 #include "nsIAddonPolicyService.h"
 #include "nsIContentSecurityPolicy.h"
 #include "nsIObjectInputStream.h"
 #include "nsIObjectOutputStream.h"
+#include "nsIStandardURL.h"
 
 #include "ContentPrincipal.h"
 #include "nsNetUtil.h"
 #include "nsIURIWithPrincipal.h"
 #include "NullPrincipal.h"
 #include "nsScriptSecurityManager.h"
 #include "nsServiceManagerUtils.h"
 
 #include "mozilla/dom/ChromeUtils.h"
 #include "mozilla/dom/CSPDictionariesBinding.h"
 #include "mozilla/dom/ToJSValue.h"
 
 namespace mozilla {
 
 BasePrincipal::BasePrincipal(PrincipalKind aKind)
   : mKind(aKind)
-  , mDomainSet(false)
+  , mHasExplicitDomain(false)
+  , mInitialized(false)
 {}
 
 BasePrincipal::~BasePrincipal()
 {}
 
 NS_IMETHODIMP
 BasePrincipal::GetOrigin(nsACString& aOrigin)
 {
+  MOZ_ASSERT(mInitialized);
+
   nsresult rv = GetOriginNoSuffix(aOrigin);
   NS_ENSURE_SUCCESS(rv, rv);
 
   nsAutoCString suffix;
   rv = GetOriginSuffix(suffix);
   NS_ENSURE_SUCCESS(rv, rv);
   aOrigin.Append(suffix);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 BasePrincipal::GetOriginNoSuffix(nsACString& aOrigin)
 {
-  if (mOriginNoSuffix) {
-    return mOriginNoSuffix->ToUTF8String(aOrigin);
-  }
-  return GetOriginInternal(aOrigin);
+  MOZ_ASSERT(mInitialized);
+  return mOriginNoSuffix->ToUTF8String(aOrigin);
 }
 
 bool
 BasePrincipal::Subsumes(nsIPrincipal* aOther, DocumentDomainConsideration aConsideration)
 {
   MOZ_ASSERT(aOther);
   MOZ_ASSERT_IF(Kind() == eCodebasePrincipal, mOriginSuffix);
 
@@ -362,18 +364,41 @@ BasePrincipal::AddonHasPermission(const 
 
   bool retval = false;
   nsresult rv = aps->AddonHasPermission(addonId, aPerm, &retval);
   NS_ENSURE_SUCCESS(rv, false);
   return retval;
 }
 
 already_AddRefed<BasePrincipal>
-BasePrincipal::CreateCodebasePrincipal(nsIURI* aURI, const OriginAttributes& aAttrs)
+BasePrincipal::CreateCodebasePrincipal(nsIURI* aURI,
+                                       const OriginAttributes& aAttrs)
 {
+  MOZ_ASSERT(aURI);
+
+  nsAutoCString originNoSuffix;
+  nsresult rv =
+    ContentPrincipal::GenerateOriginNoSuffixFromURI(aURI, originNoSuffix);
+  if (NS_WARN_IF(NS_FAILED(rv))) {
+    // If the generation of the origin fails, we still want to have a valid
+    // principal. Better to return a null principal here.
+    return NullPrincipal::Create(aAttrs);
+  }
+
+  return CreateCodebasePrincipal(aURI, aAttrs, originNoSuffix);
+}
+
+already_AddRefed<BasePrincipal>
+BasePrincipal::CreateCodebasePrincipal(nsIURI* aURI,
+                                       const OriginAttributes& aAttrs,
+                                       const nsACString& aOriginNoSuffix)
+{
+  MOZ_ASSERT(aURI);
+  MOZ_ASSERT(!aOriginNoSuffix.IsEmpty());
+
   // If the URI is supposed to inherit the security context of whoever loads it,
   // we shouldn't make a codebase principal for it.
   bool inheritsPrincipal;
   nsresult rv = NS_URIChainHasFlags(aURI, nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT,
                                     &inheritsPrincipal);
   if (NS_FAILED(rv) || inheritsPrincipal) {
     return NullPrincipal::Create(aAttrs);
   }
@@ -387,17 +412,17 @@ BasePrincipal::CreateCodebasePrincipal(n
       return NullPrincipal::Create(aAttrs);
     }
     RefPtr<BasePrincipal> concrete = Cast(principal);
     return concrete.forget();
   }
 
   // Mint a codebase principal.
   RefPtr<ContentPrincipal> codebase = new ContentPrincipal();
-  rv = codebase->Init(aURI, aAttrs);
+  rv = codebase->Init(aURI, aAttrs, aOriginNoSuffix);
   NS_ENSURE_SUCCESS(rv, nullptr);
   return codebase.forget();
 }
 
 already_AddRefed<BasePrincipal>
 BasePrincipal::CreateCodebasePrincipal(const nsACString& aOrigin)
 {
   MOZ_ASSERT(!StringBeginsWith(aOrigin, NS_LITERAL_CSTRING("[")),
@@ -451,29 +476,24 @@ BasePrincipal::AddonAllowsLoad(nsIURI* a
   NS_ENSURE_TRUE(aps, false);
 
   bool allowed = false;
   nsresult rv = aps->AddonMayLoadURI(addonId, aURI, aExplicit, &allowed);
   return NS_SUCCEEDED(rv) && allowed;
 }
 
 void
-BasePrincipal::FinishInit()
+BasePrincipal::FinishInit(const nsACString& aOriginNoSuffix,
+                          const OriginAttributes& aOriginAttributes)
 {
+  mInitialized = true;
+  mOriginAttributes = aOriginAttributes;
+
   // First compute the origin suffix since it's infallible.
   nsAutoCString originSuffix;
   mOriginAttributes.CreateSuffix(originSuffix);
   mOriginSuffix = NS_Atomize(originSuffix);
 
-  // Then compute the origin without the suffix.
-  nsAutoCString originNoSuffix;
-  nsresult rv = GetOriginInternal(originNoSuffix);
-  if (NS_FAILED(rv)) {
-    // If GetOriginInternal fails, we will get a null atom for mOriginNoSuffix,
-    // which we deal with anywhere mOriginNoSuffix is used.
-    // Once this is made infallible we can remove those null checks.
-    mOriginNoSuffix = nullptr;
-    return;
-  }
-  mOriginNoSuffix = NS_Atomize(originNoSuffix);
+  MOZ_ASSERT(!aOriginNoSuffix.IsEmpty());
+  mOriginNoSuffix = NS_Atomize(aOriginNoSuffix);
 }
 
 } // namespace mozilla
--- a/caps/BasePrincipal.h
+++ b/caps/BasePrincipal.h
@@ -70,19 +70,26 @@ public:
   NS_IMETHOD GetUserContextId(uint32_t* aUserContextId) final;
   NS_IMETHOD GetPrivateBrowsingId(uint32_t* aPrivateBrowsingId) final;
 
   virtual bool AddonHasPermission(const nsAString& aPerm);
 
   virtual bool IsCodebasePrincipal() const { return false; };
 
   static BasePrincipal* Cast(nsIPrincipal* aPrin) { return static_cast<BasePrincipal*>(aPrin); }
+
+  static already_AddRefed<BasePrincipal>
+  CreateCodebasePrincipal(const nsACString& aOrigin);
+
+  // These following method may not create a codebase principal in case it's
+  // not possible to generate a correct origin from the passed URI. If this
+  // happens, a NullPrincipal is returned.
+
   static already_AddRefed<BasePrincipal>
   CreateCodebasePrincipal(nsIURI* aURI, const OriginAttributes& aAttrs);
-  static already_AddRefed<BasePrincipal> CreateCodebasePrincipal(const nsACString& aOrigin);
 
   const OriginAttributes& OriginAttributesRef() final { return mOriginAttributes; }
   uint32_t AppId() const { return mOriginAttributes.mAppId; }
   uint32_t UserContextId() const { return mOriginAttributes.mUserContextId; }
   uint32_t PrivateBrowsingId() const { return mOriginAttributes.mPrivateBrowsingId; }
   bool IsInIsolatedMozBrowserElement() const { return mOriginAttributes.mInIsolatedMozBrowser; }
 
   PrincipalKind Kind() const { return mKind; }
@@ -99,39 +106,53 @@ public:
   inline bool FastEqualsConsideringDomain(nsIPrincipal* aOther);
   inline bool FastSubsumes(nsIPrincipal* aOther);
   inline bool FastSubsumesConsideringDomain(nsIPrincipal* aOther);
   inline bool FastSubsumesConsideringDomainIgnoringFPD(nsIPrincipal* aOther);
 
 protected:
   virtual ~BasePrincipal();
 
-  virtual nsresult GetOriginInternal(nsACString& aOrigin) = 0;
   // Note that this does not check OriginAttributes. Callers that depend on
   // those must call Subsumes instead.
   virtual bool SubsumesInternal(nsIPrincipal* aOther, DocumentDomainConsideration aConsider) = 0;
 
   // Internal, side-effect-free check to determine whether the concrete
   // principal would allow the load ignoring any common behavior implemented in
   // BasePrincipal::CheckMayLoad.
   virtual bool MayLoadInternal(nsIURI* aURI) = 0;
   friend class ::ExpandedPrincipal;
 
+  void
+  SetHasExplicitDomain()
+  {
+    mHasExplicitDomain = true;
+  }
+
   // This function should be called as the last step of the initialization of the
   // principal objects.  It's typically called as the last step from the Init()
   // method of the child classes.
-  void FinishInit();
+  void FinishInit(const nsACString& aOriginNoSuffix,
+                  const OriginAttributes& aOriginAttributes);
 
   nsCOMPtr<nsIContentSecurityPolicy> mCSP;
   nsCOMPtr<nsIContentSecurityPolicy> mPreloadCSP;
+
+private:
+  static already_AddRefed<BasePrincipal>
+  CreateCodebasePrincipal(nsIURI* aURI, const OriginAttributes& aAttrs,
+                          const nsACString& aOriginNoSuffix);
+
   nsCOMPtr<nsIAtom> mOriginNoSuffix;
   nsCOMPtr<nsIAtom> mOriginSuffix;
+
   OriginAttributes mOriginAttributes;
   PrincipalKind mKind;
-  bool mDomainSet;
+  bool mHasExplicitDomain;
+  bool mInitialized;
 };
 
 inline bool
 BasePrincipal::FastEquals(nsIPrincipal* aOther)
 {
   auto other = Cast(aOther);
   if (Kind() != other->Kind()) {
     // Principals of different kinds can't be equal.
@@ -142,75 +163,65 @@ BasePrincipal::FastEquals(nsIPrincipal* 
   // If the two principals are codebase principals, their origin attributes
   // (aka the origin suffix) must also match.
   // If the two principals are null principals, they're only equal if they're
   // the same object.
   if (Kind() == eNullPrincipal || Kind() == eSystemPrincipal) {
     return this == other;
   }
 
-  if (mOriginNoSuffix) {
-    if (Kind() == eCodebasePrincipal) {
-      return mOriginNoSuffix == other->mOriginNoSuffix &&
-             mOriginSuffix == other->mOriginSuffix;
-    }
-
-    MOZ_ASSERT(Kind() == eExpandedPrincipal);
-    return mOriginNoSuffix == other->mOriginNoSuffix;
+  if (Kind() == eCodebasePrincipal) {
+    return mOriginNoSuffix == other->mOriginNoSuffix &&
+           mOriginSuffix == other->mOriginSuffix;
   }
 
-  // If mOriginNoSuffix is null on one of our principals, we must fall back
-  // to the slow path.
-  return Subsumes(aOther, DontConsiderDocumentDomain) &&
-         other->Subsumes(this, DontConsiderDocumentDomain);
+  MOZ_ASSERT(Kind() == eExpandedPrincipal);
+  return mOriginNoSuffix == other->mOriginNoSuffix;
 }
 
 inline bool
 BasePrincipal::FastEqualsConsideringDomain(nsIPrincipal* aOther)
 {
   // If neither of the principals have document.domain set, we use the fast path
   // in Equals().  Otherwise, we fall back to the slow path below.
   auto other = Cast(aOther);
-  if (!mDomainSet && !other->mDomainSet) {
+  if (!mHasExplicitDomain && !other->mHasExplicitDomain) {
     return FastEquals(aOther);
   }
 
   return Subsumes(aOther, ConsiderDocumentDomain) &&
          other->Subsumes(this, ConsiderDocumentDomain);
 }
 
 inline bool
 BasePrincipal::FastSubsumes(nsIPrincipal* aOther)
 {
   // If two principals are equal, then they both subsume each other.
   // We deal with two special cases first:
   // Null principals only subsume each other if they are equal, and are only
   // equal if they're the same object.
-  // Also, if mOriginNoSuffix is null, FastEquals falls back to the slow path
-  // using Subsumes, so we don't want to use it in that case to avoid an
-  // infinite recursion.
   auto other = Cast(aOther);
   if (Kind() == eNullPrincipal && other->Kind() == eNullPrincipal) {
     return this == other;
   }
-  if (mOriginNoSuffix && FastEquals(aOther)) {
+  if (FastEquals(aOther)) {
     return true;
   }
 
   // Otherwise, fall back to the slow path.
   return Subsumes(aOther, DontConsiderDocumentDomain);
 }
 
 inline bool
 BasePrincipal::FastSubsumesConsideringDomain(nsIPrincipal* aOther)
 {
   // If neither of the principals have document.domain set, we hand off to
   // FastSubsumes() which has fast paths for some special cases. Otherwise, we fall
   // back to the slow path below.
-  if (!mDomainSet && !Cast(aOther)->mDomainSet) {
+  if (!mHasExplicitDomain && !Cast(aOther)->mHasExplicitDomain) {
     return FastSubsumes(aOther);
   }
 
   return Subsumes(aOther, ConsiderDocumentDomain);
 }
 
 inline bool
 BasePrincipal::FastSubsumesConsideringDomainIgnoringFPD(nsIPrincipal* aOther)
--- a/caps/ContentPrincipal.cpp
+++ b/caps/ContentPrincipal.cpp
@@ -77,85 +77,82 @@ ContentPrincipal::InitializeStatics()
                                "signed.applets.codebase_principal_support",
                                false);
 }
 
 ContentPrincipal::ContentPrincipal()
   : BasePrincipal(eCodebasePrincipal)
   , mCodebaseImmutable(false)
   , mDomainImmutable(false)
-  , mInitialized(false)
 {
 }
 
 ContentPrincipal::~ContentPrincipal()
 {
   // let's clear the principal within the csp to avoid a tangling pointer
   if (mCSP) {
     static_cast<nsCSPContext*>(mCSP.get())->clearLoadingPrincipal();
   }
 }
 
 nsresult
 ContentPrincipal::Init(nsIURI *aCodebase,
-                       const OriginAttributes& aOriginAttributes)
+                       const OriginAttributes& aOriginAttributes,
+                       const nsACString& aOriginNoSuffix)
 {
-  NS_ENSURE_STATE(!mInitialized);
   NS_ENSURE_ARG(aCodebase);
 
-  mInitialized = true;
-
   // Assert that the URI we get here isn't any of the schemes that we know we
   // should not get here.  These schemes always either inherit their principal
   // or fall back to a null principal.  These are schemes which return
   // URI_INHERITS_SECURITY_CONTEXT from their protocol handler's
   // GetProtocolFlags function.
   bool hasFlag;
   Unused << hasFlag; // silence possible compiler warnings.
   MOZ_DIAGNOSTIC_ASSERT(
       NS_SUCCEEDED(NS_URIChainHasFlags(aCodebase,
                                        nsIProtocolHandler::URI_INHERITS_SECURITY_CONTEXT,
                                        &hasFlag)) &&
       !hasFlag);
 
   mCodebase = NS_TryToMakeImmutable(aCodebase);
   mCodebaseImmutable = URIIsImmutable(mCodebase);
-  mOriginAttributes = aOriginAttributes;
 
-  FinishInit();
+  FinishInit(aOriginNoSuffix, aOriginAttributes);
 
   return NS_OK;
 }
 
 nsresult
 ContentPrincipal::GetScriptLocation(nsACString &aStr)
 {
   return mCodebase->GetSpec(aStr);
 }
 
-nsresult
-ContentPrincipal::GetOriginInternal(nsACString& aOrigin)
+/* static */ nsresult
+ContentPrincipal::GenerateOriginNoSuffixFromURI(nsIURI* aURI,
+                                                nsACString& aOriginNoSuffix)
 {
-  if (!mCodebase) {
+  if (!aURI) {
     return NS_ERROR_FAILURE;
   }
 
-  nsCOMPtr<nsIURI> origin = NS_GetInnermostURI(mCodebase);
+  nsCOMPtr<nsIURI> origin = NS_GetInnermostURI(aURI);
   if (!origin) {
     return NS_ERROR_FAILURE;
   }
 
   MOZ_ASSERT(!NS_IsAboutBlank(origin),
              "The inner URI for about:blank must be moz-safe-about:blank");
 
   if (!nsScriptSecurityManager::GetStrictFileOriginPolicy() &&
       NS_URIIsLocalFile(origin)) {
     // If strict file origin policy is not in effect, all local files are
     // considered to be same-origin, so return a known dummy origin here.
-    aOrigin.AssignLiteral("file://UNIVERSAL_FILE_URI_ORIGIN");
+    aOriginNoSuffix.AssignLiteral("file://UNIVERSAL_FILE_URI_ORIGIN");
     return NS_OK;
   }
 
   nsAutoCString hostPort;
 
   // chrome: URLs don't have a meaningful origin, so make
   // sure we just get the full spec for them.
   // XXX this should be removed in favor of the solution in
@@ -185,74 +182,74 @@ ContentPrincipal::GetOriginInternal(nsAC
   bool isBehaved;
   if ((NS_SUCCEEDED(origin->SchemeIs("about", &isBehaved)) && isBehaved) ||
       (NS_SUCCEEDED(origin->SchemeIs("moz-safe-about", &isBehaved)) && isBehaved &&
        // We generally consider two about:foo origins to be same-origin, but
        // about:blank is special since it can be generated from different sources.
        // We check for moz-safe-about:blank since origin is an innermost URI.
        !origin->GetSpecOrDefault().EqualsLiteral("moz-safe-about:blank")) ||
       (NS_SUCCEEDED(origin->SchemeIs("indexeddb", &isBehaved)) && isBehaved)) {
-    rv = origin->GetAsciiSpec(aOrigin);
+    rv = origin->GetAsciiSpec(aOriginNoSuffix);
     NS_ENSURE_SUCCESS(rv, rv);
     // These URIs could technically contain a '^', but they never should.
-    if (NS_WARN_IF(aOrigin.FindChar('^', 0) != -1)) {
-      aOrigin.Truncate();
+    if (NS_WARN_IF(aOriginNoSuffix.FindChar('^', 0) != -1)) {
+      aOriginNoSuffix.Truncate();
       return NS_ERROR_FAILURE;
     }
     return NS_OK;
   }
 
   if (NS_SUCCEEDED(rv) && !isChrome) {
-    rv = origin->GetScheme(aOrigin);
+    rv = origin->GetScheme(aOriginNoSuffix);
     NS_ENSURE_SUCCESS(rv, rv);
-    aOrigin.AppendLiteral("://");
-    aOrigin.Append(hostPort);
+    aOriginNoSuffix.AppendLiteral("://");
+    aOriginNoSuffix.Append(hostPort);
     return NS_OK;
   }
 
   // This URL can be a blobURL. In this case, we should use the 'parent'
   // principal instead.
   nsCOMPtr<nsIURIWithPrincipal> uriWithPrincipal = do_QueryInterface(origin);
   if (uriWithPrincipal) {
     nsCOMPtr<nsIPrincipal> uriPrincipal;
     rv = uriWithPrincipal->GetPrincipal(getter_AddRefs(uriPrincipal));
     NS_ENSURE_SUCCESS(rv, rv);
 
     if (uriPrincipal) {
-      return uriPrincipal->GetOriginNoSuffix(aOrigin);
+      return uriPrincipal->GetOriginNoSuffix(aOriginNoSuffix);
     }
   }
 
   // If we reached this branch, we can only create an origin if we have a
   // nsIStandardURL.  So, we query to a nsIStandardURL, and fail if we aren't
   // an instance of an nsIStandardURL nsIStandardURLs have the good property
   // of escaping the '^' character in their specs, which means that we can be
   // sure that the caret character (which is reserved for delimiting the end
   // of the spec, and the beginning of the origin attributes) is not present
   // in the origin string
   nsCOMPtr<nsIStandardURL> standardURL = do_QueryInterface(origin);
   if (!standardURL) {
     return NS_ERROR_FAILURE;
   }
 
-  rv = origin->GetAsciiSpec(aOrigin);
+  rv = origin->GetAsciiSpec(aOriginNoSuffix);
   NS_ENSURE_SUCCESS(rv, rv);
 
   // The origin, when taken from the spec, should not contain the ref part of
   // the URL.
 
-  int32_t pos = aOrigin.FindChar('?');
-  int32_t hashPos = aOrigin.FindChar('#');
+  int32_t pos = aOriginNoSuffix.FindChar('?');
+  int32_t hashPos = aOriginNoSuffix.FindChar('#');
 
   if (hashPos != kNotFound && (pos == kNotFound || hashPos < pos)) {
     pos = hashPos;
   }
 
   if (pos != kNotFound) {
-    aOrigin.Truncate(pos);
+    aOriginNoSuffix.Truncate(pos);
   }
 
   return NS_OK;
 }
 
 bool
 ContentPrincipal::SubsumesInternal(nsIPrincipal* aOther,
                                    BasePrincipal::DocumentDomainConsideration aConsideration)
@@ -367,17 +364,17 @@ ContentPrincipal::GetDomain(nsIURI** aDo
   return NS_EnsureSafeToReturn(mDomain, aDomain);
 }
 
 NS_IMETHODIMP
 ContentPrincipal::SetDomain(nsIURI* aDomain)
 {
   mDomain = NS_TryToMakeImmutable(aDomain);
   mDomainImmutable = URIIsImmutable(mDomain);
-  mDomainSet = true;
+  SetHasExplicitDomain();
 
   // Recompute all wrappers between compartments using this principal and other
   // non-chrome compartments.
   AutoSafeJSContext cx;
   JSPrincipals *principals = nsJSPrincipals::get(static_cast<nsIPrincipal*>(this));
   bool success = js::RecomputeWrappers(cx, js::ContentCompartmentsOnly(),
                                        js::CompartmentsWithPrincipals(principals));
   NS_ENSURE_TRUE(success, NS_ERROR_FAILURE);
@@ -478,17 +475,21 @@ ContentPrincipal::Read(nsIObjectInputStr
 
   OriginAttributes attrs;
   bool ok = attrs.PopulateFromSuffix(suffix);
   NS_ENSURE_TRUE(ok, NS_ERROR_FAILURE);
 
   rv = NS_ReadOptionalObject(aStream, true, getter_AddRefs(supports));
   NS_ENSURE_SUCCESS(rv, rv);
 
-  rv = Init(codebase, attrs);
+  nsAutoCString originNoSuffix;
+  rv = GenerateOriginNoSuffixFromURI(codebase, originNoSuffix);
+  NS_ENSURE_SUCCESS(rv, rv);
+
+  rv = Init(codebase, attrs, originNoSuffix);
   NS_ENSURE_SUCCESS(rv, rv);
 
   mCSP = do_QueryInterface(supports, &rv);
   // make sure setRequestContext is called after Init(),
   // to make sure  the principals URI been initalized.
   if (mCSP) {
     mCSP->SetRequestContext(nullptr, this);
   }
--- a/caps/ContentPrincipal.h
+++ b/caps/ContentPrincipal.h
@@ -22,37 +22,39 @@ public:
   NS_IMETHOD QueryInterface(REFNSIID aIID, void** aInstancePtr) override;
   NS_IMETHOD GetHashValue(uint32_t* aHashValue) override;
   NS_IMETHOD GetURI(nsIURI** aURI) override;
   NS_IMETHOD GetDomain(nsIURI** aDomain) override;
   NS_IMETHOD SetDomain(nsIURI* aDomain) override;
   NS_IMETHOD GetBaseDomain(nsACString& aBaseDomain) override;
   NS_IMETHOD GetAddonId(nsAString& aAddonId) override;
   bool IsCodebasePrincipal() const override { return true; }
-  nsresult GetOriginInternal(nsACString& aOrigin) override;
 
   ContentPrincipal();
 
   // Init() must be called before the principal is in a usable state.
   nsresult Init(nsIURI* aCodebase,
-                const mozilla::OriginAttributes& aOriginAttributes);
+                const mozilla::OriginAttributes& aOriginAttributes,
+                const nsACString& aOriginNoSuffix);
 
   virtual nsresult GetScriptLocation(nsACString& aStr) override;
 
   /**
    * Called at startup to setup static data, e.g. about:config pref-observers.
    */
   static void InitializeStatics();
 
+  static nsresult
+  GenerateOriginNoSuffixFromURI(nsIURI* aURI, nsACString& aOrigin);
+
   nsCOMPtr<nsIURI> mDomain;
   nsCOMPtr<nsIURI> mCodebase;
   // If mCodebaseImmutable is true, mCodebase is non-null and immutable
   bool mCodebaseImmutable;
   bool mDomainImmutable;
-  bool mInitialized;
 
 protected:
   virtual ~ContentPrincipal();
 
   bool SubsumesInternal(nsIPrincipal* aOther,
                         DocumentDomainConsideration aConsideration) override;
   bool MayLoadInternal(nsIURI* aURI) override;
 
--- a/caps/ExpandedPrincipal.cpp
+++ b/caps/ExpandedPrincipal.cpp
@@ -18,93 +18,87 @@ NS_IMPL_CI_INTERFACE_GETTER(ExpandedPrin
                             nsIPrincipal,
                             nsIExpandedPrincipal)
 
 struct OriginComparator
 {
   bool LessThan(nsIPrincipal* a, nsIPrincipal* b) const
   {
     nsAutoCString originA;
-    nsresult rv = a->GetOrigin(originA);
-    NS_ENSURE_SUCCESS(rv, false);
+    DebugOnly<nsresult> rv = a->GetOrigin(originA);
+    MOZ_ASSERT(NS_SUCCEEDED(rv));
     nsAutoCString originB;
     rv = b->GetOrigin(originB);
-    NS_ENSURE_SUCCESS(rv, false);
+    MOZ_ASSERT(NS_SUCCEEDED(rv));
     return originA < originB;
   }
 
   bool Equals(nsIPrincipal* a, nsIPrincipal* b) const
   {
     nsAutoCString originA;
-    nsresult rv = a->GetOrigin(originA);
-    NS_ENSURE_SUCCESS(rv, false);
+    DebugOnly<nsresult> rv = a->GetOrigin(originA);
+    MOZ_ASSERT(NS_SUCCEEDED(rv));
     nsAutoCString originB;
     rv = b->GetOrigin(originB);
-    NS_ENSURE_SUCCESS(rv, false);
+    MOZ_ASSERT(NS_SUCCEEDED(rv));
     return a == b;
   }
 };
 
-ExpandedPrincipal::ExpandedPrincipal(nsTArray<nsCOMPtr<nsIPrincipal>> &aWhiteList,
-                                     const OriginAttributes& aAttrs)
+ExpandedPrincipal::ExpandedPrincipal(nsTArray<nsCOMPtr<nsIPrincipal>> &aWhiteList)
   : BasePrincipal(eExpandedPrincipal)
 {
   // We force the principals to be sorted by origin so that ExpandedPrincipal
   // origins can have a canonical form.
   OriginComparator c;
   for (size_t i = 0; i < aWhiteList.Length(); ++i) {
     mPrincipals.InsertElementSorted(aWhiteList[i], c);
   }
-  mOriginAttributes = aAttrs;
 }
 
 ExpandedPrincipal::~ExpandedPrincipal()
 { }
 
 already_AddRefed<ExpandedPrincipal>
 ExpandedPrincipal::Create(nsTArray<nsCOMPtr<nsIPrincipal>>& aWhiteList,
                           const OriginAttributes& aAttrs)
 {
-  RefPtr<ExpandedPrincipal> ep = new ExpandedPrincipal(aWhiteList, aAttrs);
-  ep->FinishInit();
+  RefPtr<ExpandedPrincipal> ep = new ExpandedPrincipal(aWhiteList);
+
+  nsAutoCString origin;
+  origin.AssignLiteral("[Expanded Principal [");
+  for (size_t i = 0; i < ep->mPrincipals.Length(); ++i) {
+    if (i != 0) {
+      origin.AppendLiteral(", ");
+    }
+
+    nsAutoCString subOrigin;
+    DebugOnly<nsresult> rv = ep->mPrincipals.ElementAt(i)->GetOrigin(subOrigin);
+    MOZ_ASSERT(NS_SUCCEEDED(rv));
+    origin.Append(subOrigin);
+  }
+  origin.Append("]]");
+
+  ep->FinishInit(origin, aAttrs);
   return ep.forget();
 }
 
 NS_IMETHODIMP
 ExpandedPrincipal::GetDomain(nsIURI** aDomain)
 {
   *aDomain = nullptr;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 ExpandedPrincipal::SetDomain(nsIURI* aDomain)
 {
   return NS_OK;
 }
 
-nsresult
-ExpandedPrincipal::GetOriginInternal(nsACString& aOrigin)
-{
-  aOrigin.AssignLiteral("[Expanded Principal [");
-  for (size_t i = 0; i < mPrincipals.Length(); ++i) {
-    if (i != 0) {
-      aOrigin.AppendLiteral(", ");
-    }
-
-    nsAutoCString subOrigin;
-    nsresult rv = mPrincipals.ElementAt(i)->GetOrigin(subOrigin);
-    NS_ENSURE_SUCCESS(rv, rv);
-    aOrigin.Append(subOrigin);
-  }
-
-  aOrigin.Append("]]");
-  return NS_OK;
-}
-
 bool
 ExpandedPrincipal::SubsumesInternal(nsIPrincipal* aOther,
                                     BasePrincipal::DocumentDomainConsideration aConsideration)
 {
   // If aOther is an ExpandedPrincipal too, we break it down into its component
   // nsIPrincipals, and check subsumes on each one.
   nsCOMPtr<nsIExpandedPrincipal> expanded = do_QueryInterface(aOther);
   if (expanded) {
--- a/caps/ExpandedPrincipal.h
+++ b/caps/ExpandedPrincipal.h
@@ -10,19 +10,16 @@
 #include "nsJSPrincipals.h"
 #include "nsTArray.h"
 #include "nsNetUtil.h"
 #include "mozilla/BasePrincipal.h"
 
 class ExpandedPrincipal : public nsIExpandedPrincipal
                         , public mozilla::BasePrincipal
 {
-  ExpandedPrincipal(nsTArray<nsCOMPtr<nsIPrincipal>> &aWhiteList,
-                    const mozilla::OriginAttributes& aAttrs);
-
 public:
   static already_AddRefed<ExpandedPrincipal>
   Create(nsTArray<nsCOMPtr<nsIPrincipal>>& aWhiteList,
          const mozilla::OriginAttributes& aAttrs);
 
   NS_DECL_NSIEXPANDEDPRINCIPAL
   NS_DECL_NSISERIALIZABLE
 
@@ -32,19 +29,20 @@ public:
   NS_IMETHOD GetHashValue(uint32_t* aHashValue) override;
   NS_IMETHOD GetURI(nsIURI** aURI) override;
   NS_IMETHOD GetDomain(nsIURI** aDomain) override;
   NS_IMETHOD SetDomain(nsIURI* aDomain) override;
   NS_IMETHOD GetBaseDomain(nsACString& aBaseDomain) override;
   NS_IMETHOD GetAddonId(nsAString& aAddonId) override;
   virtual bool AddonHasPermission(const nsAString& aPerm) override;
   virtual nsresult GetScriptLocation(nsACString &aStr) override;
-  nsresult GetOriginInternal(nsACString& aOrigin) override;
 
 protected:
+  explicit ExpandedPrincipal(nsTArray<nsCOMPtr<nsIPrincipal>> &aWhiteList);
+
   virtual ~ExpandedPrincipal();
 
   bool SubsumesInternal(nsIPrincipal* aOther,
                         DocumentDomainConsideration aConsideration) override;
 
   bool MayLoadInternal(nsIURI* aURI) override;
 
 private:
--- a/caps/NullPrincipal.cpp
+++ b/caps/NullPrincipal.cpp
@@ -65,33 +65,35 @@ NullPrincipal::Create(const OriginAttrib
   MOZ_RELEASE_ASSERT(NS_SUCCEEDED(rv));
 
   return nullPrin.forget();
 }
 
 nsresult
 NullPrincipal::Init(const OriginAttributes& aOriginAttributes, nsIURI* aURI)
 {
-  mOriginAttributes = aOriginAttributes;
-
   if (aURI) {
     nsAutoCString scheme;
     nsresult rv = aURI->GetScheme(scheme);
     NS_ENSURE_SUCCESS(rv, rv);
 
     NS_ENSURE_TRUE(scheme.EqualsLiteral(NS_NULLPRINCIPAL_SCHEME),
                    NS_ERROR_NOT_AVAILABLE);
 
     mURI = aURI;
   } else {
     mURI = NullPrincipalURI::Create();
     NS_ENSURE_TRUE(mURI, NS_ERROR_NOT_AVAILABLE);
   }
 
-  FinishInit();
+  nsAutoCString originNoSuffix;
+  DebugOnly<nsresult> rv = mURI->GetSpec(originNoSuffix);
+  MOZ_ASSERT(NS_SUCCEEDED(rv));
+
+  FinishInit(originNoSuffix, aOriginAttributes);
 
   return NS_OK;
 }
 
 nsresult
 NullPrincipal::GetScriptLocation(nsACString &aStr)
 {
   return mURI->GetSpec(aStr);
@@ -138,22 +140,16 @@ NullPrincipal::GetDomain(nsIURI** aDomai
 NS_IMETHODIMP
 NullPrincipal::SetDomain(nsIURI* aDomain)
 {
   // I think the right thing to do here is to just throw...  Silently failing
   // seems counterproductive.
   return NS_ERROR_NOT_AVAILABLE;
 }
 
-nsresult
-NullPrincipal::GetOriginInternal(nsACString& aOrigin)
-{
-  return mURI->GetSpec(aOrigin);
-}
-
 bool
 NullPrincipal::MayLoadInternal(nsIURI* aURI)
 {
   // Also allow the load if we are the principal of the URI being checked.
   nsCOMPtr<nsIURIWithPrincipal> uriPrinc = do_QueryInterface(aURI);
   if (uriPrinc) {
     nsCOMPtr<nsIPrincipal> principal;
     uriPrinc->GetPrincipal(getter_AddRefs(principal));
--- a/caps/NullPrincipal.h
+++ b/caps/NullPrincipal.h
@@ -46,17 +46,16 @@ public:
   NS_IMETHOD QueryInterface(REFNSIID aIID, void** aInstancePtr) override;
   NS_IMETHOD GetHashValue(uint32_t* aHashValue) override;
   NS_IMETHOD SetCsp(nsIContentSecurityPolicy* aCsp) override;
   NS_IMETHOD GetURI(nsIURI** aURI) override;
   NS_IMETHOD GetDomain(nsIURI** aDomain) override;
   NS_IMETHOD SetDomain(nsIURI* aDomain) override;
   NS_IMETHOD GetBaseDomain(nsACString& aBaseDomain) override;
   NS_IMETHOD GetAddonId(nsAString& aAddonId) override;
-  nsresult GetOriginInternal(nsACString& aOrigin) override;
 
   static already_AddRefed<NullPrincipal> CreateWithInheritedAttributes(nsIPrincipal* aInheritFrom);
 
   // Create NullPrincipal with origin attributes from docshell.
   // If aIsFirstParty is true, and the pref 'privacy.firstparty.isolate' is also
   // enabled, the mFirstPartyDomain value of the origin attributes will be set
   // to NULL_PRINCIPAL_FIRST_PARTY_DOMAIN.
   static already_AddRefed<NullPrincipal>
--- a/caps/SystemPrincipal.cpp
+++ b/caps/SystemPrincipal.cpp
@@ -30,17 +30,18 @@ NS_IMPL_CI_INTERFACE_GETTER(SystemPrinci
                             nsISerializable)
 
 #define SYSTEM_PRINCIPAL_SPEC "[System Principal]"
 
 already_AddRefed<SystemPrincipal>
 SystemPrincipal::Create()
 {
   RefPtr<SystemPrincipal> sp = new SystemPrincipal();
-  sp->FinishInit();
+  sp->FinishInit(NS_LITERAL_CSTRING(SYSTEM_PRINCIPAL_SPEC),
+                 OriginAttributes());
   return sp.forget();
 }
 
 nsresult
 SystemPrincipal::GetScriptLocation(nsACString &aStr)
 {
     aStr.AssignLiteral(SYSTEM_PRINCIPAL_SPEC);
     return NS_OK;
@@ -59,23 +60,16 @@ SystemPrincipal::GetHashValue(uint32_t *
 
 NS_IMETHODIMP
 SystemPrincipal::GetURI(nsIURI** aURI)
 {
     *aURI = nullptr;
     return NS_OK;
 }
 
-nsresult
-SystemPrincipal::GetOriginInternal(nsACString& aOrigin)
-{
-    aOrigin.AssignLiteral(SYSTEM_PRINCIPAL_SPEC);
-    return NS_OK;
-}
-
 NS_IMETHODIMP
 SystemPrincipal::GetCsp(nsIContentSecurityPolicy** aCsp)
 {
   *aCsp = nullptr;
   return NS_OK;
 }
 
 NS_IMETHODIMP
--- a/caps/SystemPrincipal.h
+++ b/caps/SystemPrincipal.h
@@ -38,17 +38,16 @@ public:
   NS_IMETHOD SetDomain(nsIURI* aDomain) override;
   NS_IMETHOD GetCsp(nsIContentSecurityPolicy** aCsp) override;
   NS_IMETHOD SetCsp(nsIContentSecurityPolicy* aCsp) override;
   NS_IMETHOD EnsureCSP(nsIDOMDocument* aDocument, nsIContentSecurityPolicy** aCSP) override;
   NS_IMETHOD GetPreloadCsp(nsIContentSecurityPolicy** aPreloadCSP) override;
   NS_IMETHOD EnsurePreloadCSP(nsIDOMDocument* aDocument, nsIContentSecurityPolicy** aCSP) override;
   NS_IMETHOD GetBaseDomain(nsACString& aBaseDomain) override;
   NS_IMETHOD GetAddonId(nsAString& aAddonId) override;
-  nsresult GetOriginInternal(nsACString& aOrigin) override;
 
   virtual nsresult GetScriptLocation(nsACString &aStr) override;
 
 protected:
   virtual ~SystemPrincipal(void) {}
 
   bool SubsumesInternal(nsIPrincipal *aOther,
                         DocumentDomainConsideration aConsideration) override
--- a/caps/tests/unit/test_origin.js
+++ b/caps/tests/unit/test_origin.js
@@ -295,17 +295,10 @@ function run_test() {
     Services.prefs.setBoolPref("security.fileuri.strict_origin_policy", t[0]);
     var filePrin = ssm.createCodebasePrincipal(fileURI, {});
     do_check_eq(filePrin.origin, t[1]);
   });
   Services.prefs.clearUserPref("security.fileuri.strict_origin_policy");
 
   var aboutBlankURI = makeURI('about:blank');
   var aboutBlankPrin = ssm.createCodebasePrincipal(aboutBlankURI, {});
-  var thrown = false;
-  try {
-    aboutBlankPrin.origin;
-  } catch (e) {
-    thrown = true;
-  }
-  do_check_true(thrown);
-
+  do_check_true(/^moz-nullprincipal:\{([0-9]|[a-z]|\-){36}\}$/.test(aboutBlankPrin.origin));
 }
--- a/devtools/client/shared/test/helper_inplace_editor.js
+++ b/devtools/client/shared/test/helper_inplace_editor.js
@@ -47,17 +47,17 @@ function createSpan(doc) {
   info("Creating a new span element");
   let div = doc.createElementNS(HTML_NS, "div");
   let span = doc.createElementNS(HTML_NS, "span");
   span.setAttribute("tabindex", "0");
   span.style.fontSize = "11px";
   span.style.display = "inline-block";
   span.style.width = "100px";
   span.style.border = "1px solid red";
-  span.style.fontFamily = "Courier New";
+  span.style.fontFamily = "monospace";
 
   div.style.height = "100%";
   div.style.position = "absolute";
   div.appendChild(span);
 
   let parent = doc.querySelector("window") || doc.body;
   parent.appendChild(div);
   return span;
--- a/dom/base/DocGroup.cpp
+++ b/dom/base/DocGroup.cpp
@@ -28,16 +28,17 @@ DocGroup::GetKey(nsIPrincipal* aPrincipa
   }
 
   return rv;
 }
 
 void
 DocGroup::RemoveDocument(nsIDocument* aDocument)
 {
+  MOZ_ASSERT(NS_IsMainThread());
   MOZ_ASSERT(mDocuments.Contains(aDocument));
   mDocuments.RemoveElement(aDocument);
 }
 
 DocGroup::DocGroup(TabGroup* aTabGroup, const nsACString& aKey)
   : mKey(aKey), mTabGroup(aTabGroup)
 {
   // This method does not add itself to mTabGroup->mDocGroups as the caller does it for us.
--- a/dom/base/DocGroup.h
+++ b/dom/base/DocGroup.h
@@ -55,31 +55,34 @@ public:
     return aKey == mKey;
   }
   TabGroup* GetTabGroup()
   {
     return mTabGroup;
   }
   mozilla::dom::CustomElementReactionsStack* CustomElementReactionsStack()
   {
+    MOZ_ASSERT(NS_IsMainThread());
     if (!mReactionsStack) {
       mReactionsStack = new mozilla::dom::CustomElementReactionsStack();
     }
 
     return mReactionsStack;
   }
   void RemoveDocument(nsIDocument* aWindow);
 
   // Iterators for iterating over every document within the DocGroup
   Iterator begin()
   {
+    MOZ_ASSERT(NS_IsMainThread());
     return mDocuments.begin();
   }
   Iterator end()
   {
+    MOZ_ASSERT(NS_IsMainThread());
     return mDocuments.end();
   }
 
   virtual nsresult Dispatch(const char* aName,
                             TaskCategory aCategory,
                             already_AddRefed<nsIRunnable>&& aRunnable) override;
 
   virtual nsIEventTarget* EventTargetFor(TaskCategory aCategory) const override;
--- a/dom/base/TabGroup.cpp
+++ b/dom/base/TabGroup.cpp
@@ -121,16 +121,17 @@ TabGroup::GetDocGroup(const nsACString& 
 {
   RefPtr<DocGroup> docGroup(mDocGroups.GetEntry(aKey)->mDocGroup);
   return docGroup.forget();
 }
 
 already_AddRefed<DocGroup>
 TabGroup::AddDocument(const nsACString& aKey, nsIDocument* aDocument)
 {
+  MOZ_ASSERT(NS_IsMainThread());
   HashEntry* entry = mDocGroups.PutEntry(aKey);
   RefPtr<DocGroup> docGroup;
   if (entry->mDocGroup) {
     docGroup = entry->mDocGroup;
   } else {
     docGroup = new DocGroup(this, aKey);
     entry->mDocGroup = docGroup;
   }
@@ -141,29 +142,31 @@ TabGroup::AddDocument(const nsACString& 
   docGroup->mDocuments.AppendElement(aDocument);
 
   return docGroup.forget();
 }
 
 /* static */ already_AddRefed<TabGroup>
 TabGroup::Join(nsPIDOMWindowOuter* aWindow, TabGroup* aTabGroup)
 {
+  MOZ_ASSERT(NS_IsMainThread());
   RefPtr<TabGroup> tabGroup = aTabGroup;
   if (!tabGroup) {
     tabGroup = new TabGroup();
   }
   MOZ_RELEASE_ASSERT(!tabGroup->mLastWindowLeft);
   MOZ_ASSERT(!tabGroup->mWindows.Contains(aWindow));
   tabGroup->mWindows.AppendElement(aWindow);
   return tabGroup.forget();
 }
 
 void
 TabGroup::Leave(nsPIDOMWindowOuter* aWindow)
 {
+  MOZ_ASSERT(NS_IsMainThread());
   MOZ_ASSERT(mWindows.Contains(aWindow));
   mWindows.RemoveElement(aWindow);
 
   // The Chrome TabGroup doesn't have cyclical references through mEventTargets
   // to itself, meaning that we don't have to worry about nulling mEventTargets
   // out after the last window leaves.
   if (!mIsChrome && mWindows.IsEmpty()) {
     mLastWindowLeft = true;
@@ -172,16 +175,17 @@ TabGroup::Leave(nsPIDOMWindowOuter* aWin
 }
 
 nsresult
 TabGroup::FindItemWithName(const nsAString& aName,
                            nsIDocShellTreeItem* aRequestor,
                            nsIDocShellTreeItem* aOriginalRequestor,
                            nsIDocShellTreeItem** aFoundItem)
 {
+  MOZ_ASSERT(NS_IsMainThread());
   NS_ENSURE_ARG_POINTER(aFoundItem);
   *aFoundItem = nullptr;
 
   MOZ_ASSERT(!aName.LowerCaseEqualsLiteral("_blank") &&
              !aName.LowerCaseEqualsLiteral("_top") &&
              !aName.LowerCaseEqualsLiteral("_parent") &&
              !aName.LowerCaseEqualsLiteral("_self"));
 
@@ -209,16 +213,17 @@ TabGroup::FindItemWithName(const nsAStri
   }
 
   return NS_OK;
 }
 
 nsTArray<nsPIDOMWindowOuter*>
 TabGroup::GetTopLevelWindows()
 {
+  MOZ_ASSERT(NS_IsMainThread());
   nsTArray<nsPIDOMWindowOuter*> array;
 
   for (nsPIDOMWindowOuter* outerWindow : mWindows) {
     if (outerWindow->GetDocShell() &&
         !outerWindow->GetScriptableParentOrNull()) {
       array.AppendElement(outerWindow);
     }
   }
--- a/dom/base/WebSocket.cpp
+++ b/dom/base/WebSocket.cpp
@@ -1629,23 +1629,22 @@ WebSocketImpl::Init(JSContext* aCx,
       nsCOMPtr<nsIGlobalObject> globalObject(GetEntryGlobal());
       if (globalObject) {
         principal = globalObject->PrincipalOrNull();
       }
 
       nsCOMPtr<nsPIDOMWindowInner> innerWindow;
 
       while (true) {
-        bool isNullPrincipal = true;
         if (principal) {
+          bool isNullPrincipal = true;
           isNullPrincipal = principal->GetIsNullPrincipal();
-        }
-
-        if (!isNullPrincipal) {
-          break;
+          if (isNullPrincipal || nsContentUtils::IsSystemPrincipal(principal)) {
+            break;
+          }
         }
 
         if (!innerWindow) {
           innerWindow = do_QueryInterface(globalObject);
           if (NS_WARN_IF(!innerWindow)) {
             return NS_ERROR_DOM_SECURITY_ERR;
           }
         }
--- a/dom/base/nsFrameMessageManager.cpp
+++ b/dom/base/nsFrameMessageManager.cpp
@@ -653,23 +653,35 @@ nsFrameMessageManager::SendMessage(const
 
   JS::Rooted<JSObject*> objects(aCx);
   if (aArgc >= 3 && aObjects.isObject()) {
     objects = &aObjects.toObject();
   }
 
   nsTArray<StructuredCloneData> retval;
 
+  TimeStamp start = TimeStamp::Now();
   sSendingSyncMessage |= aIsSync;
   bool ok = mCallback->DoSendBlockingMessage(aCx, aMessageName, data, objects,
                                              aPrincipal, &retval, aIsSync);
   if (aIsSync) {
     sSendingSyncMessage = false;
   }
 
+  uint32_t latencyMs = round((TimeStamp::Now() - start).ToMilliseconds());
+  if (latencyMs >= kMinTelemetrySyncMessageManagerLatencyMs) {
+    NS_ConvertUTF16toUTF8 messageName(aMessageName);
+    // NOTE: We need to strip digit characters from the message name in order to
+    // avoid a large number of buckets due to generated names from addons (such
+    // as "ublock:sb:{N}"). See bug 1348113 comment 10.
+    messageName.StripChars("0123456789");
+    Telemetry::Accumulate(Telemetry::IPC_SYNC_MESSAGE_MANAGER_LATENCY_MS,
+                          messageName, latencyMs);
+  }
+
   if (!ok) {
     return NS_OK;
   }
 
   uint32_t len = retval.Length();
   JS::Rooted<JSObject*> dataArray(aCx, JS_NewArrayObject(aCx, len));
   NS_ENSURE_TRUE(dataArray, NS_ERROR_OUT_OF_MEMORY);
 
--- a/dom/base/nsFrameMessageManager.h
+++ b/dom/base/nsFrameMessageManager.h
@@ -39,16 +39,20 @@ namespace dom {
 
 class nsIContentParent;
 class nsIContentChild;
 class ClonedMessageData;
 class MessageManagerReporter;
 
 namespace ipc {
 
+// Note: we round the time we spend to the nearest millisecond. So a min value
+// of 1 ms actually captures from 500us and above.
+static const uint32_t kMinTelemetrySyncMessageManagerLatencyMs = 1;
+
 enum MessageManagerFlags {
   MM_CHILD = 0,
   MM_CHROME = 1,
   MM_GLOBAL = 2,
   MM_PROCESSMANAGER = 4,
   MM_BROADCASTER = 8,
   MM_OWNSCALLBACK = 16
 };
--- a/dom/base/nsGlobalWindow.cpp
+++ b/dom/base/nsGlobalWindow.cpp
@@ -2546,22 +2546,21 @@ nsGlobalWindow::SetInitialPrincipalToSub
     if (!mDoc->IsInitialDocument())
       return;
     // (b) already has the correct principal.
     if (mDoc->NodePrincipal() == newWindowPrincipal)
       return;
 
 #ifdef DEBUG
     // If we have a document loaded at this point, it had better be about:blank.
-    // Otherwise, something is really weird.
-    nsCOMPtr<nsIURI> uri;
-    mDoc->NodePrincipal()->GetURI(getter_AddRefs(uri));
-    NS_ASSERTION(uri && NS_IsAboutBlank(uri) &&
-                 NS_IsAboutBlank(mDoc->GetDocumentURI()),
-                 "Unexpected original document");
+    // Otherwise, something is really weird. An about:blank page has a
+    // NullPrincipal.
+    bool isNullPrincipal;
+    MOZ_ASSERT(NS_SUCCEEDED(mDoc->NodePrincipal()->GetIsNullPrincipal(&isNullPrincipal)) &&
+               isNullPrincipal);
 #endif
   }
 
   GetDocShell()->CreateAboutBlankContentViewer(newWindowPrincipal);
   mDoc->SetIsInitialDocument(true);
 
   nsCOMPtr<nsIPresShell> shell = GetDocShell()->GetPresShell();
 
--- a/dom/events/DataTransfer.cpp
+++ b/dom/events/DataTransfer.cpp
@@ -941,17 +941,24 @@ DataTransfer::GetTransferable(uint32_t a
   }
   transferable->Init(aLoadContext);
 
   nsCOMPtr<nsIStorageStream> storageStream;
   nsCOMPtr<nsIBinaryOutputStream> stream;
 
   bool added = false;
   bool handlingCustomFormats = true;
-  uint32_t totalCustomLength = 0;
+
+  // When writing the custom data, we need to ensure that there is sufficient
+  // space for a (uint32_t) data ending type, and the null byte character at
+  // the end of the nsCString. We claim that space upfront and store it in
+  // baseLength. This value will be set to zero if a write error occurs
+  // indicating that the data and length are no longer valid.
+  const uint32_t baseLength = sizeof(uint32_t) + 1;
+  uint32_t totalCustomLength = baseLength;
 
   const char* knownFormats[] = {
     kTextMime, kHTMLMime, kNativeHTMLMime, kRTFMime,
     kURLMime, kURLDataMime, kURLDescriptionMime, kURLPrivateMime,
     kPNGImageMime, kJPEGImageMime, kGIFImageMime, kNativeImageMime,
     kFileMime, kFilePromiseMime, kFilePromiseURLMime,
     kFilePromiseDestFilename, kFilePromiseDirectoryMime,
     kMozTextInternal, kHTMLContext, kHTMLInfo };
@@ -1003,18 +1010,19 @@ DataTransfer::GetTransferable(uint32_t a
 
       if (handlingCustomFormats) {
         if (!ConvertFromVariant(variant, getter_AddRefs(convertedData),
                                 &lengthInBytes)) {
           continue;
         }
 
         // When handling custom types, add the data to the stream if this is a
-        // custom type.
-        if (isCustomFormat) {
+        // custom type. If totalCustomLength is 0, then a write error occurred
+        // on a previous item, so ignore any others.
+        if (isCustomFormat && totalCustomLength > 0) {
           // If it isn't a string, just ignore it. The dataTransfer is cached in
           // the drag sesion during drag-and-drop, so non-strings will be
           // available when dragging locally.
           nsCOMPtr<nsISupportsString> str(do_QueryInterface(convertedData));
           if (str) {
             nsAutoString data;
             str->GetData(data);
 
@@ -1024,69 +1032,102 @@ DataTransfer::GetTransferable(uint32_t a
 
               nsCOMPtr<nsIOutputStream> outputStream;
               storageStream->GetOutputStream(0, getter_AddRefs(outputStream));
 
               stream = do_CreateInstance("@mozilla.org/binaryoutputstream;1");
               stream->SetOutputStream(outputStream);
             }
 
-            int32_t formatLength = type.Length() * sizeof(nsString::char_type);
-
-            stream->Write32(eCustomClipboardTypeId_String);
-            stream->Write32(formatLength);
-            stream->WriteBytes((const char *)type.get(),
-                               formatLength);
-            stream->Write32(lengthInBytes);
-            stream->WriteBytes((const char *)data.get(), lengthInBytes);
+            CheckedInt<uint32_t> formatLength =
+              CheckedInt<uint32_t>(type.Length()) * sizeof(nsString::char_type);
 
             // The total size of the stream is the format length, the data
-            // length, two integers to hold the lengths and one integer for the
-            // string flag.
-            totalCustomLength +=
-              formatLength + lengthInBytes + (sizeof(uint32_t) * 3);
+            // length, two integers to hold the lengths and one integer for
+            // the string flag. Guard against large data by ignoring any that
+            // don't fit.
+            CheckedInt<uint32_t> newSize = formatLength + totalCustomLength +
+                                           lengthInBytes + (sizeof(uint32_t) * 3);
+            if (newSize.isValid()) {
+              // If a write error occurs, set totalCustomLength to 0 so that
+              // further processing gets ignored.
+              nsresult rv = stream->Write32(eCustomClipboardTypeId_String);
+              if (NS_WARN_IF(NS_FAILED(rv))) {
+                totalCustomLength = 0;
+                continue;
+              }
+              rv = stream->Write32(formatLength.value());
+              if (NS_WARN_IF(NS_FAILED(rv))) {
+                totalCustomLength = 0;
+                continue;
+              }
+              rv = stream->WriteBytes((const char *)type.get(), formatLength.value());
+              if (NS_WARN_IF(NS_FAILED(rv))) {
+                totalCustomLength = 0;
+                continue;
+              }
+              rv = stream->Write32(lengthInBytes);
+              if (NS_WARN_IF(NS_FAILED(rv))) {
+                totalCustomLength = 0;
+                continue;
+              }
+              rv = stream->WriteBytes((const char *)data.get(), lengthInBytes);
+              if (NS_WARN_IF(NS_FAILED(rv))) {
+                totalCustomLength = 0;
+                continue;
+              }
+
+              totalCustomLength = newSize.value();
+            }
           }
         }
       } else if (isCustomFormat && stream) {
         // This is the second pass of the loop (handlingCustomFormats is false).
         // When encountering the first custom format, append all of the stream
-        // at this position.
-
-        // Write out a terminator.
-        totalCustomLength += sizeof(uint32_t);
-        stream->Write32(eCustomClipboardTypeId_None);
+        // at this position. If totalCustomLength is 0 indicating a write error
+        // occurred, or no data has been added to it, don't output anything,
+        if (totalCustomLength > baseLength) {
+          // Write out an end of data terminator.
+          nsresult rv = stream->Write32(eCustomClipboardTypeId_None);
+          if (NS_SUCCEEDED(rv)) {
+            nsCOMPtr<nsIInputStream> inputStream;
+            storageStream->NewInputStream(0, getter_AddRefs(inputStream));
 
-        nsCOMPtr<nsIInputStream> inputStream;
-        storageStream->NewInputStream(0, getter_AddRefs(inputStream));
+            RefPtr<nsStringBuffer> stringBuffer =
+              nsStringBuffer::Alloc(totalCustomLength);
 
-        RefPtr<nsStringBuffer> stringBuffer =
-          nsStringBuffer::Alloc(totalCustomLength + 1);
+            // Subtract off the null terminator when reading.
+            totalCustomLength--;
 
-        // Read the data from the string and add a null-terminator as ToString
-        // needs it.
-        uint32_t amountRead;
-        inputStream->Read(static_cast<char*>(stringBuffer->Data()),
-                          totalCustomLength, &amountRead);
-        static_cast<char*>(stringBuffer->Data())[amountRead] = 0;
+            // Read the data from the stream and add a null-terminator as
+            // ToString needs it.
+            uint32_t amountRead;
+            rv = inputStream->Read(static_cast<char*>(stringBuffer->Data()),
+                              totalCustomLength, &amountRead);
+            if (NS_SUCCEEDED(rv)) {
+              static_cast<char*>(stringBuffer->Data())[amountRead] = 0;
 
-        nsCString str;
-        stringBuffer->ToString(totalCustomLength, str);
-        nsCOMPtr<nsISupportsCString>
-          strSupports(do_CreateInstance(NS_SUPPORTS_CSTRING_CONTRACTID));
-        strSupports->SetData(str);
+              nsCString str;
+              stringBuffer->ToString(totalCustomLength, str);
+              nsCOMPtr<nsISupportsCString>
+                strSupports(do_CreateInstance(NS_SUPPORTS_CSTRING_CONTRACTID));
+              strSupports->SetData(str);
 
-        nsresult rv = transferable->SetTransferData(kCustomTypesMime,
-                                                    strSupports,
-                                                    totalCustomLength);
-        if (NS_FAILED(rv)) {
-          return nullptr;
+              nsresult rv = transferable->SetTransferData(kCustomTypesMime,
+                                                          strSupports,
+                                                          totalCustomLength);
+              if (NS_FAILED(rv)) {
+                return nullptr;
+              }
+
+              added = true;
+            }
+          }
         }
 
-        added = true;
-
         // Clear the stream so it doesn't get used again.
         stream = nullptr;
       } else {
         // This is the second pass of the loop and a known type is encountered.
         // Add it as is.
         if (!ConvertFromVariant(variant, getter_AddRefs(convertedData),
                                 &lengthInBytes)) {
           continue;
--- a/dom/events/test/test_continuous_wheel_events.html
+++ b/dom/events/test/test_continuous_wheel_events.html
@@ -4,17 +4,17 @@
   <title>Test for D3E WheelEvent</title>
   <script type="application/javascript" src="/tests/SimpleTest/SimpleTest.js"></script>
   <script type="application/javascript" src="/tests/SimpleTest/EventUtils.js"></script>
   <script type="application/javascript" src="/tests/SimpleTest/paint_listener.js"></script>
   <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>
 </head>
 <body>
 <p id="display"></p>
-<div id="scrollable" style="font-family:'Courier New'; font-size: 18px; line-height: 1; overflow: auto; width: 200px; height: 200px;">
+<div id="scrollable" style="font-family:monospace; font-size: 18px; line-height: 1; overflow: auto; width: 200px; height: 200px;">
   <div id="scrolled" style="font-size: 64px; width: 5000px; height: 5000px;">
     Tere is a lot of text. Tere is a lot of text. Tere is a lot of text. Tere is a lot of text. Tere is a lot of text.<br>
     Tere is a lot of text. Tere is a lot of text. Tere is a lot of text. Tere is a lot of text. Tere is a lot of text.<br>
     Tere is a lot of text. Tere is a lot of text. Tere is a lot of text. Tere is a lot of text. Tere is a lot of text.<br>
     Tere is a lot of text. Tere is a lot of text. Tere is a lot of text. Tere is a lot of text. Tere is a lot of text.<br>
     Tere is a lot of text. Tere is a lot of text. Tere is a lot of text. Tere is a lot of text. Tere is a lot of text.<br>
     Tere is a lot of text. Tere is a lot of text. Tere is a lot of text. Tere is a lot of text. Tere is a lot of text.<br>
     Tere is a lot of text. Tere is a lot of text. Tere is a lot of text. Tere is a lot of text. Tere is a lot of text.<br>
@@ -39,17 +39,16 @@
     Tere is a lot of text. Tere is a lot of text. Tere is a lot of text. Tere is a lot of text. Tere is a lot of text.<br>
   </div>
 </div>
 <div id="content" style="display: none">
 
 </div>
 <pre id="test">
 <script type="application/javascript">
-"use strict";
 
 SimpleTest.waitForExplicitFinish();
 SimpleTest.waitForFocus(runTests, window);
 
 var gScrollableElement = document.getElementById("scrollable");
 var gScrolledElement = document.getElementById("scrolled");
 
 var gLineHeight = 0;
--- a/dom/security/test/unit/test_isOriginPotentiallyTrustworthy.js
+++ b/dom/security/test/unit/test_isOriginPotentiallyTrustworthy.js
@@ -25,21 +25,19 @@ prefs.setCharPref("dom.securecontext.whi
 add_task(function* test_isOriginPotentiallyTrustworthy() {
   for (let [uriSpec, expectedResult] of [
     ["http://example.com/", false],
     ["https://example.com/", true],
     ["http://localhost/", true],
     ["http://127.0.0.1/", true],
     ["file:///", true],
     ["resource:///", true],
-    ["app://", true],
     ["moz-extension://", true],
     ["wss://example.com/", true],
     ["about:config", false],
-    ["urn:generic", false],
     ["http://example.net/", true],
     ["ws://example.org/", true],
     ["chrome://example.net/content/messenger.xul", false],
   ]) {
     let uri = NetUtil.newURI(uriSpec);
     let principal = gScriptSecurityManager.getCodebasePrincipal(uri);
     Assert.equal(gContentSecurityManager.isOriginPotentiallyTrustworthy(principal),
                  expectedResult);
--- a/dom/tests/mochitest/chrome/queryCaretRectWin.html
+++ b/dom/tests/mochitest/chrome/queryCaretRectWin.html
@@ -15,17 +15,17 @@
 -->
 
 <style>
   #text {
   position: absolute;
   left: 0em;
   top: 0em;
   font-size: 10pt;
-  font-family: 'Courier New';
+  font-family: monospace;
   line-height: 20px;
   letter-spacing: 0px;
   margin-top:-1px; /* nix the text area border */
   overflow: hidden;
   width:800px;
   height:400px;
   }
   #div-hor {
--- a/dom/tests/mochitest/chrome/selectAtPoint.html
+++ b/dom/tests/mochitest/chrome/selectAtPoint.html
@@ -1,18 +1,16 @@
 <!DOCTYPE HTML>
 <html>
 <head>
 <title>nsIDOMWindowUtils::selectAtPoint test</title>
 <script type="text/javascript" src="chrome://mochikit/content/tests/SimpleTest/SimpleTest.js"></script>
 <link rel="stylesheet" type="text/css" href="chrome://mochikit/content/tests/SimpleTest/test.css">
 
-<script>
-  "use strict";
-
+<script type="application/javascript">
   var SimpleTest = window.opener.SimpleTest;
   var Ci = Components.interfaces;
 
   function ok() { window.opener.ok.apply(window.opener, arguments); }
   function done() { window.opener.done.apply(window.opener, arguments); }
 
   function dumpLn() {
     for (let idx = 0; idx < arguments.length; idx++)
@@ -124,17 +122,23 @@
 
     // Separate character blocks in a word 't(te)s(ts)election1'
     targetPoint = { xPos: rect.left + (charDims.width + (charDims.width / 2)),
                     yPos: rect.top + (charDims.height / 2) };
     setStart(dwu, targetPoint.xPos, targetPoint.yPos, Ci.nsIDOMWindowUtils.SELECT_CHARACTER);
     targetPoint = { xPos: rect.left + ((charDims.width * 4) + (charDims.width / 2)),
                     yPos: rect.top + (charDims.height / 2) };
     setEnd(dwu, targetPoint.xPos, targetPoint.yPos, Ci.nsIDOMWindowUtils.SELECT_CHARACTER);
+    if (isLinux || isMac) {
+      // XXX I think this is a bug, the right hand selection is 4.5 characters over with a
+      // monspaced font. what we want: t(te)s(ts)election1 what we get: t(te)st(se)lection1
+      checkSelection(document, "split selection", "tese");
+    } else if (isWindows) {
       checkSelection(document, "split selection", "tets");
+    }
 
     // Trying to select where there's no text, should fail but not throw
     let result = dwu.selectAtPoint(rect.left - 20, rect.top - 20, Ci.nsIDOMWindowUtils.SELECT_CHARACTER, false);
     ok(result == false, "couldn't select?");
 
     // Second div in the main page
 
     div = document.getElementById("div2");
@@ -219,17 +223,17 @@
   }
 
   window.addEventListener("MozAfterPaint", onPaint);
 </script>
 
 <style type="text/css">
 
 body {
-  font-family: 'Courier New';
+  font-family: monospace;
   margin-left: 40px;
   margin-top: 40px;
   padding: 0;
 }
 
 #div1 {
   border: 1px solid red;
   width: 400px;
@@ -258,17 +262,17 @@ body {
 </style>
 </head>
 <body id="body" onload="onPageLoad();">
 
 <div id="div1">ttestselection1 Lorem ipsum dolor sit amet, at duo debet graeci, vivendum vulputate per ut. Ne labore incorrupte vix. Cu copiosae postulant tincidunt ius, in illud appetere contentiones eos. Ei munere officiis assentior pro, nibh decore ius at.</div>
 
 <br />
 
-<iframe id="frame1" src="data:text/html,<html><body style='margin: 0; padding: 0; font-family: \'Courier New\';' onload='window.parent.onFrameLoad();'><div id='sel2'>ttestselection2 Lorem ipsum dolor sit amet, at duo debet graeci, vivendum vulputate per ut.</div><br/><br/></body></html>"></iframe>
+<iframe id="frame1" src="data:text/html,<html><body style='margin: 0; padding: 0; font-family: monospace;' onload='window.parent.onFrameLoad();'><div id='sel2'>ttestselection2 Lorem ipsum dolor sit amet, at duo debet graeci, vivendum vulputate per ut.</div><br/><br/></body></html>"></iframe>
 
 <br/>
 
 <div id="div2">Lorem ipsum dolor sit amet, at duo debet graeci, vivendum vulputate per ut. Ne labore incorrupte vix. Cu copiosae postulant tincidunt ius, in illud appetere contentiones eos.</div>
 
 <br />
 
 <span id="measure">t</span>
--- a/editor/composer/nsEditorSpellCheck.cpp
+++ b/editor/composer/nsEditorSpellCheck.cpp
@@ -321,16 +321,21 @@ private:
 };
 
 NS_IMETHODIMP
 nsEditorSpellCheck::InitSpellChecker(nsIEditor* aEditor, bool aEnableSelectionChecking, nsIEditorSpellCheckCallback* aCallback)
 {
   NS_ENSURE_TRUE(aEditor, NS_ERROR_NULL_POINTER);
   mEditor = aEditor;
 
+  nsCOMPtr<nsIDOMDocument> domDoc;
+  mEditor->GetDocument(getter_AddRefs(domDoc));
+  nsCOMPtr<nsIDocument> doc = do_QueryInterface(domDoc);
+  NS_ENSURE_STATE(doc);
+
   nsresult rv;
 
   // We can spell check with any editor type
   nsCOMPtr<nsITextServicesDocument>tsDoc =
      do_CreateInstance("@mozilla.org/textservices/textservicesdocument;1", &rv);
   NS_ENSURE_SUCCESS(rv, rv);
 
   NS_ENSURE_TRUE(tsDoc, NS_ERROR_NULL_POINTER);
@@ -396,18 +401,18 @@ nsEditorSpellCheck::InitSpellChecker(nsI
   // do not fail if UpdateCurrentDictionary fails because this method may
   // succeed later.
   rv = UpdateCurrentDictionary(aCallback);
   if (NS_FAILED(rv) && aCallback) {
     // However, if it does fail, we still need to call the callback since we
     // discard the failure.  Do it asynchronously so that the caller is always
     // guaranteed async behavior.
     RefPtr<CallbackCaller> caller = new CallbackCaller(aCallback);
-    NS_ENSURE_STATE(caller);
-    rv = NS_DispatchToMainThread(caller);
+    rv = doc->Dispatch("nsEditorSpellCheck::CallbackCaller",
+                       TaskCategory::Other, caller.forget());
     NS_ENSURE_SUCCESS(rv, rv);
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 nsEditorSpellCheck::GetNextMisspelledWord(char16_t **aNextMisspelledWord)
--- a/editor/libeditor/EditorBase.cpp
+++ b/editor/libeditor/EditorBase.cpp
@@ -729,17 +729,18 @@ EditorBase::DoTransaction(nsITransaction
     // get the selection and start a batch change
     RefPtr<Selection> selection = GetSelection();
     NS_ENSURE_TRUE(selection, NS_ERROR_NULL_POINTER);
 
     selection->StartBatchChanges();
 
     nsresult rv;
     if (mTxnMgr) {
-      rv = mTxnMgr->DoTransaction(aTxn);
+      RefPtr<nsTransactionManager> txnMgr = mTxnMgr;
+      rv = txnMgr->DoTransaction(aTxn);
     } else {
       rv = aTxn->DoTransaction();
     }
     if (NS_SUCCEEDED(rv)) {
       DoAfterDoTransaction(aTxn);
     }
 
     // no need to check rv here, don't lose result of operation
@@ -804,18 +805,19 @@ EditorBase::Undo(uint32_t aCount)
   NS_ENSURE_TRUE(hasTransaction, NS_OK);
 
   AutoRules beginRulesSniffing(this, EditAction::undo, nsIEditor::eNone);
 
   if (!mTxnMgr) {
     return NS_OK;
   }
 
+  RefPtr<nsTransactionManager> txnMgr = mTxnMgr;
   for (uint32_t i = 0; i < aCount; ++i) {
-    nsresult rv = mTxnMgr->UndoTransaction();
+    nsresult rv = txnMgr->UndoTransaction();
     NS_ENSURE_SUCCESS(rv, rv);
 
     DoAfterUndoTransaction();
   }
 
   return NS_OK;
 }
 
@@ -843,18 +845,19 @@ EditorBase::Redo(uint32_t aCount)
   NS_ENSURE_TRUE(hasTransaction, NS_OK);
 
   AutoRules beginRulesSniffing(this, EditAction::redo, nsIEditor::eNone);
 
   if (!mTxnMgr) {
     return NS_OK;
   }
 
+  RefPtr<nsTransactionManager> txnMgr = mTxnMgr;
   for (uint32_t i = 0; i < aCount; ++i) {
-    nsresult rv = mTxnMgr->RedoTransaction();
+    nsresult rv = txnMgr->RedoTransaction();
     NS_ENSURE_SUCCESS(rv, rv);
 
     DoAfterRedoTransaction();
   }
 
   return NS_OK;
 }
 
@@ -875,27 +878,29 @@ EditorBase::CanRedo(bool* aIsEnabled, bo
 }
 
 NS_IMETHODIMP
 EditorBase::BeginTransaction()
 {
   BeginUpdateViewBatch();
 
   if (mTxnMgr) {
-    mTxnMgr->BeginBatch(nullptr);
+    RefPtr<nsTransactionManager> txnMgr = mTxnMgr;
+    txnMgr->BeginBatch(nullptr);
   }
 
   return NS_OK;
 }
 
 NS_IMETHODIMP
 EditorBase::EndTransaction()
 {
   if (mTxnMgr) {
-    mTxnMgr->EndBatch(false);
+    RefPtr<nsTransactionManager> txnMgr = mTxnMgr;
+    txnMgr->EndBatch(false);
   }
 
   EndUpdateViewBatch();
 
   return NS_OK;
 }
 
 
--- a/gfx/skia/skia/src/ports/SkFontHost_cairo.cpp
+++ b/gfx/skia/skia/src/ports/SkFontHost_cairo.cpp
@@ -126,17 +126,18 @@ private:
     void resolvePattern(FcPattern* pattern);
 #endif
 
     cairo_scaled_font_t* fScaledFont;
     FT_Int32 fLoadGlyphFlags;
     FT_LcdFilter fLcdFilter;
     SkScalar fScaleX;
     SkScalar fScaleY;
-    FT_Matrix fShapeMatrix;
+    SkMatrix fShapeMatrix;
+    FT_Matrix fShapeMatrixFT;
     bool fHaveShape;
 };
 
 class CairoLockedFTFace {
 public:
     CairoLockedFTFace(cairo_scaled_font_t* scaledFont)
         : fScaledFont(scaledFont)
         , fFace(cairo_ft_scaled_font_lock_face(scaledFont))
@@ -587,22 +588,23 @@ bool SkScalerContext_CairoFT::computeSha
         fHaveShape = !m.isScaleTranslate();
     }
 
     fScaleX = SkDoubleToScalar(major);
     fScaleY = SkDoubleToScalar(minor);
 
     if (fHaveShape) {
         // Normalize the transform and convert to fixed-point.
-        double invScaleX = 65536.0 / major;
-        double invScaleY = 65536.0 / minor;
-        fShapeMatrix.xx = (FT_Fixed)(scaleX * invScaleX);
-        fShapeMatrix.yx = -(FT_Fixed)(skewY * invScaleX);
-        fShapeMatrix.xy = -(FT_Fixed)(skewX * invScaleY);
-        fShapeMatrix.yy = (FT_Fixed)(scaleY * invScaleY);
+        fShapeMatrix = m;
+        fShapeMatrix.preScale(SkDoubleToScalar(1.0 / major), SkDoubleToScalar(1.0 / minor));
+
+        fShapeMatrixFT.xx = SkScalarToFixed(fShapeMatrix.getScaleX());
+        fShapeMatrixFT.yx = SkScalarToFixed(-fShapeMatrix.getSkewY());
+        fShapeMatrixFT.xy = SkScalarToFixed(-fShapeMatrix.getSkewX());
+        fShapeMatrixFT.yy = SkScalarToFixed(fShapeMatrix.getScaleY());
     }
     return true;
 }
 
 unsigned SkScalerContext_CairoFT::generateGlyphCount()
 {
     CairoLockedFTFace faceLock(fScaledFont);
     return faceLock.getFace()->num_glyphs;
@@ -632,17 +634,17 @@ void SkScalerContext_CairoFT::prepareGly
 
 void SkScalerContext_CairoFT::fixVerticalLayoutBearing(FT_GlyphSlot glyph)
 {
     FT_Vector vector;
     vector.x = glyph->metrics.vertBearingX - glyph->metrics.horiBearingX;
     vector.y = -glyph->metrics.vertBearingY - glyph->metrics.horiBearingY;
     if (glyph->format == FT_GLYPH_FORMAT_OUTLINE) {
         if (fHaveShape) {
-            FT_Vector_Transform(&vector, &fShapeMatrix);
+            FT_Vector_Transform(&vector, &fShapeMatrixFT);
         }
         FT_Outline_Translate(&glyph->outline, vector.x, vector.y);
     } else if (glyph->format == FT_GLYPH_FORMAT_BITMAP) {
         glyph->bitmap_left += SkFDot6Floor(vector.x);
         glyph->bitmap_top  += SkFDot6Floor(vector.y);
     }
 }
 
@@ -697,27 +699,30 @@ void SkScalerContext_CairoFT::generateMe
             glyph->fMaskFormat = SkMask::kARGB32_Format;
         }
 
         if (isLCD(fRec)) {
             fRec.fMaskFormat = SkMask::kA8_Format;
         }
 
         if (fHaveShape) {
+            // Ensure filtering is preserved when the bitmap is transformed.
+            // Otherwise, the result will look horrifically aliased.
+            if (fRec.fMaskFormat == SkMask::kBW_Format) {
+                fRec.fMaskFormat = SkMask::kA8_Format;
+            }
+
             // Apply the shape matrix to the glyph's bounding box.
-            SkMatrix matrix;
-            fRec.getSingleMatrix(&matrix);
-            matrix.preScale(SkScalarInvert(fScaleX), SkScalarInvert(fScaleY));
             SkRect srcRect = SkRect::MakeXYWH(
                 SkIntToScalar(face->glyph->bitmap_left),
                 -SkIntToScalar(face->glyph->bitmap_top),
                 SkIntToScalar(face->glyph->bitmap.width),
                 SkIntToScalar(face->glyph->bitmap.rows));
             SkRect destRect;
-            matrix.mapRect(&destRect, srcRect);
+            fShapeMatrix.mapRect(&destRect, srcRect);
             SkIRect glyphRect = destRect.roundOut();
             glyph->fWidth  = SkToU16(glyphRect.width());
             glyph->fHeight = SkToU16(glyphRect.height());
             glyph->fTop    = SkToS16(SkScalarRoundToInt(destRect.fTop));
             glyph->fLeft   = SkToS16(SkScalarRoundToInt(destRect.fLeft));
         } else {
             glyph->fWidth  = SkToU16(face->glyph->bitmap.width);
             glyph->fHeight = SkToU16(face->glyph->bitmap.rows);
@@ -760,18 +765,17 @@ void SkScalerContext_CairoFT::generateIm
         gSetLcdFilter;
     if (useLcdFilter) {
         gSetLcdFilter(face->glyph->library, fLcdFilter);
     }
 
     SkMatrix matrix;
     if (face->glyph->format == FT_GLYPH_FORMAT_BITMAP &&
         fHaveShape) {
-        matrix.setScale(SkIntToScalar(glyph.fWidth) / SkIntToScalar(face->glyph->bitmap.width),
-                        SkIntToScalar(glyph.fHeight) / SkIntToScalar(face->glyph->bitmap.rows));
+        matrix = fShapeMatrix;
     } else {
         matrix.setIdentity();
     }
     generateGlyphImage(face, glyph, matrix);
 
     if (useLcdFilter) {
         gSetLcdFilter(face->glyph->library, FT_LCD_FILTER_NONE);
     }
--- a/gfx/thebes/gfxFcPlatformFontList.cpp
+++ b/gfx/thebes/gfxFcPlatformFontList.cpp
@@ -791,44 +791,70 @@ PreparePattern(FcPattern* aPattern, bool
         }
 #endif // MOZ_X11
 #endif // MOZ_WIDGET_GTK
     }
 
     FcDefaultSubstitute(aPattern);
 }
 
+static inline gfxFloat
+SizeForStyle(gfxFontconfigFontEntry* aEntry, const gfxFontStyle& aStyle)
+{
+    return aStyle.sizeAdjust >= 0.0 ?
+                aStyle.GetAdjustedSize(aEntry->GetAspect()) :
+                aStyle.size;
+}
+
+static double
+ChooseFontSize(gfxFontconfigFontEntry* aEntry,
+               const gfxFontStyle& aStyle)
+{
+    double requestedSize = SizeForStyle(aEntry, aStyle);
+    double bestDist = -1.0;
+    double bestSize = requestedSize;
+    double size;
+    int v = 0;
+    while (FcPatternGetDouble(aEntry->GetPattern(),
+                              FC_PIXEL_SIZE, v, &size) == FcResultMatch) {
+        ++v;
+        double dist = fabs(size - requestedSize);
+        if (bestDist < 0.0 || dist < bestDist) {
+            bestDist = dist;
+            bestSize = size;
+        }
+    }
+    return bestSize;
+}
+
 gfxFont*
 gfxFontconfigFontEntry::CreateFontInstance(const gfxFontStyle *aFontStyle,
                                            bool aNeedsBold)
 {
     nsAutoRef<FcPattern> pattern(FcPatternCreate());
     if (!pattern) {
         NS_WARNING("Failed to create Fontconfig pattern for font instance");
         return nullptr;
     }
-    FcPatternAddDouble(pattern, FC_PIXEL_SIZE, aFontStyle->size);
+
+    double size = ChooseFontSize(this, *aFontStyle);
+    FcPatternAddDouble(pattern, FC_PIXEL_SIZE, size);
 
     PreparePattern(pattern, aFontStyle->printerFont);
     nsAutoRef<FcPattern> renderPattern
         (FcFontRenderPrepare(nullptr, pattern, mFontPattern));
     if (!renderPattern) {
         NS_WARNING("Failed to prepare Fontconfig pattern for font instance");
         return nullptr;
     }
 
-    double adjustedSize = aFontStyle->size;
-    if (aFontStyle->sizeAdjust >= 0.0) {
-        adjustedSize = aFontStyle->GetAdjustedSize(GetAspect());
-    }
-
     cairo_scaled_font_t* scaledFont =
-        CreateScaledFont(renderPattern, adjustedSize, aFontStyle, aNeedsBold);
+        CreateScaledFont(renderPattern, size, aFontStyle, aNeedsBold);
     gfxFont* newFont =
-        new gfxFontconfigFont(scaledFont, renderPattern, adjustedSize,
+        new gfxFontconfigFont(scaledFont, renderPattern, size,
                               this, aFontStyle, aNeedsBold);
     cairo_scaled_font_destroy(scaledFont);
 
     return newFont;
 }
 
 nsresult
 gfxFontconfigFontEntry::CopyFontTable(uint32_t aTableTag,
@@ -926,20 +952,126 @@ gfxFontconfigFontFamily::FindStyleVariat
 }
 
 void
 gfxFontconfigFontFamily::AddFontPattern(FcPattern* aFontPattern)
 {
     NS_ASSERTION(!mHasStyles,
                  "font patterns must not be added to already enumerated families");
 
+    FcBool scalable;
+    if (FcPatternGetBool(aFontPattern, FC_SCALABLE, 0, &scalable) != FcResultMatch ||
+        !scalable) {
+        mHasNonScalableFaces = true;
+    }
+
     nsCountedRef<FcPattern> pattern(aFontPattern);
     mFontPatterns.AppendElement(pattern);
 }
 
+static const double kRejectDistance = 10000.0;
+
+// Calculate a distance score representing the size disparity between the
+// requested style's size and the font entry's size.
+static double
+SizeDistance(gfxFontconfigFontEntry* aEntry, const gfxFontStyle& aStyle)
+{
+    double requestedSize = SizeForStyle(aEntry, aStyle);
+    double bestDist = -1.0;
+    double size;
+    int v = 0;
+    while (FcPatternGetDouble(aEntry->GetPattern(),
+                              FC_PIXEL_SIZE, v, &size) == FcResultMatch) {
+        ++v;
+        double dist = fabs(size - requestedSize);
+        if (bestDist < 0.0 || dist < bestDist) {
+            bestDist = dist;
+        }
+    }
+    if (bestDist < 0.0) {
+        // No size means scalable
+        return -1.0;
+    } else if (5.0 * bestDist < requestedSize) {
+        // fontconfig prefers a matching family or lang to pixelsize of bitmap
+        // fonts. CSS suggests a tolerance of 20% on pixelsize.
+        return bestDist;
+    } else {
+        // Reject any non-scalable fonts that are not within tolerance.
+        return kRejectDistance;
+    }
+}
+
+void
+gfxFontconfigFontFamily::FindAllFontsForStyle(const gfxFontStyle& aFontStyle,
+                                              nsTArray<gfxFontEntry*>& aFontEntryList,
+                                              bool& aNeedsSyntheticBold)
+{
+    gfxFontFamily::FindAllFontsForStyle(aFontStyle,
+                                        aFontEntryList,
+                                        aNeedsSyntheticBold);
+
+    if (!mHasNonScalableFaces) {
+        return;
+    }
+
+    // Iterate over the the available fonts while compacting any groups
+    // of unscalable fonts with matching styles into a single entry
+    // corresponding to the closest available size. If the closest
+    // available size is rejected for being outside tolernace, then the
+    // entire group will be skipped.
+    size_t skipped = 0;
+    gfxFontconfigFontEntry* bestEntry = nullptr;
+    double bestDist = -1.0;
+    for (size_t i = 0; i < aFontEntryList.Length(); i++) {
+        gfxFontconfigFontEntry* entry =
+            static_cast<gfxFontconfigFontEntry*>(aFontEntryList[i]);
+        double dist = SizeDistance(entry, aFontStyle);
+        // If the entry is scalable or has a style that does not match
+        // the group of unscalable fonts, then start a new group.
+        if (dist < 0.0 ||
+            !bestEntry ||
+            bestEntry->Stretch() != entry->Stretch() ||
+            bestEntry->Weight() != entry->Weight() ||
+            bestEntry->mStyle != entry->mStyle) {
+            // If the best entry in this group is still outside the tolerance,
+            // then skip the entire group.
+            if (bestDist >= kRejectDistance) {
+                skipped++;
+            }
+            // Remove any compacted entries from the previous group.
+            if (skipped) {
+                i -= skipped;
+                aFontEntryList.RemoveElementsAt(i, skipped);
+                skipped = 0;
+            }
+            // Mark the start of the new group.
+            bestEntry = entry;
+            bestDist = dist;
+        } else {
+            // If this entry more closely matches the requested size than the
+            // current best in the group, then take this entry instead.
+            if (dist < bestDist) {
+                aFontEntryList[i-1-skipped] = entry;
+                bestEntry = entry;
+                bestDist = dist;
+            }
+            skipped++;
+        }
+    }
+    // If the best entry in this group is still outside the tolerance,
+    // then skip the entire group.
+    if (bestDist >= kRejectDistance) {
+        skipped++;
+    }
+    // Remove any compacted entries from the current group.
+    if (skipped) {
+        aFontEntryList.TruncateLength(aFontEntryList.Length() - skipped);
+    }
+}
+
 gfxFontconfigFont::gfxFontconfigFont(cairo_scaled_font_t *aScaledFont,
                                      FcPattern *aPattern,
                                      gfxFloat aAdjustedSize,
                                      gfxFontEntry *aFontEntry,
                                      const gfxFontStyle *aFontStyle,
                                      bool aNeedsBold) :
     gfxFontconfigFontBase(aScaledFont, aPattern, aFontEntry, aFontStyle)
 {
@@ -1001,23 +1133,16 @@ gfxFcPlatformFontList::AddFontSetFamilie
     }
 
     FcChar8* lastFamilyName = (FcChar8*)"";
     RefPtr<gfxFontconfigFontFamily> fontFamily;
     nsAutoString familyName;
     for (int f = 0; f < aFontSet->nfont; f++) {
         FcPattern* font = aFontSet->fonts[f];
 
-        // not scalable? skip...
-        FcBool scalable;
-        if (FcPatternGetBool(font, FC_SCALABLE, 0, &scalable) != FcResultMatch ||
-            !scalable) {
-            continue;
-        }
-
         // get canonical name
         uint32_t cIndex = FindCanonicalNameIndex(font, FC_FAMILYLANG);
         FcChar8* canonical = nullptr;
         FcPatternGetString(font, FC_FAMILY, cIndex, &canonical);
         if (!canonical) {
             continue;
         }
 
@@ -1121,19 +1246,16 @@ GetSystemFontList(nsTArray<nsString>& aL
     // add the lang to the pattern
     nsAutoCString fcLang;
     gfxFcPlatformFontList* pfl = gfxFcPlatformFontList::PlatformFontList();
     pfl->GetSampleLangForGroup(aLangGroup, fcLang);
     if (!fcLang.IsEmpty()) {
         FcPatternAddString(pat, FC_LANG, ToFcChar8Ptr(fcLang.get()));
     }
 
-    // ignore size-specific fonts
-    FcPatternAddBool(pat, FC_SCALABLE, FcTrue);
-
     nsAutoRef<FcFontSet> fs(FcFontList(nullptr, pat, os));
     if (!fs) {
         return;
     }
 
     for (int i = 0; i < fs->nfont; i++) {
         char *family;
 
@@ -1371,19 +1493,16 @@ gfxFcPlatformFontList::GetStandardFamily
         return true;
     }
 
     nsAutoRef<FcObjectSet> os(FcObjectSetBuild(FC_FAMILY, nullptr));
     if (!os) {
         return true;
     }
 
-    // ignore size-specific fonts
-    FcPatternAddBool(pat, FC_SCALABLE, FcTrue);
-
     // add the family name to the pattern
     NS_ConvertUTF16toUTF8 familyName(aFontName);
     FcPatternAddString(pat, FC_FAMILY, ToFcChar8Ptr(familyName.get()));
 
     nsAutoRef<FcFontSet> givenFS(FcFontList(nullptr, pat, os));
     if (!givenFS) {
         return true;
     }
@@ -1610,23 +1729,16 @@ gfxFcPlatformFontList::FindGenericFamili
     // -- select the fonts to be used for the generic
     prefFonts = new PrefFontList; // can be empty but in practice won't happen
     uint32_t limit = gfxPlatformGtk::GetPlatform()->MaxGenericSubstitions();
     bool foundFontWithLang = false;
     for (int i = 0; i < faces->nfont; i++) {
         FcPattern* font = faces->fonts[i];
         FcChar8* mappedGeneric = nullptr;
 
-        // not scalable? skip...
-        FcBool scalable;
-        if (FcPatternGetBool(font, FC_SCALABLE, 0, &scalable) != FcResultMatch ||
-            !scalable) {
-            continue;
-        }
-
         FcPatternGetString(font, FC_FAMILY, 0, &mappedGeneric);
         if (mappedGeneric) {
             NS_ConvertUTF8toUTF16 mappedGenericName(ToCharPtr(mappedGeneric));
             AutoTArray<gfxFontFamily*,1> genericFamilies;
             if (gfxPlatformFontList::FindAndAddFamilies(mappedGenericName,
                                                         &genericFamilies)) {
                 MOZ_ASSERT(genericFamilies.Length() == 1,
                            "expected a single family");
--- a/gfx/thebes/gfxFcPlatformFontList.h
+++ b/gfx/thebes/gfxFcPlatformFontList.h
@@ -119,16 +119,18 @@ public:
     nsresult ReadCMAP(FontInfoData *aFontInfoData = nullptr) override;
     bool TestCharacterMap(uint32_t aCh) override;
 
     hb_blob_t* GetFontTable(uint32_t aTableTag) override;
 
     void ForgetHBFace() override;
     void ReleaseGrFace(gr_face* aFace) override;
 
+    double GetAspect();
+
 protected:
     virtual ~gfxFontconfigFontEntry();
 
     gfxFont *CreateFontInstance(const gfxFontStyle *aFontStyle,
                                 bool aNeedsBold) override;
 
     // helper method for creating cairo font from pattern
     cairo_scaled_font_t*
@@ -140,18 +142,16 @@ protected:
     // override to pull data from FTFace
     virtual nsresult
     CopyFontTable(uint32_t aTableTag,
                   nsTArray<uint8_t>& aBuffer) override;
 
     // if HB or GR faces are gone, close down the FT_Face
     void MaybeReleaseFTFace();
 
-    double GetAspect();
-
     // pattern for a single face of a family
     nsCountedRef<FcPattern> mFontPattern;
 
     // user font data, when needed
     RefPtr<FTUserFontData> mUserFontData;
 
     // FTFace - initialized when needed
     FT_Face   mFTFace;
@@ -169,36 +169,43 @@ protected:
     // data font
     const uint8_t* mFontData;
 };
 
 class gfxFontconfigFontFamily : public gfxFontFamily {
 public:
     explicit gfxFontconfigFontFamily(const nsAString& aName) :
         gfxFontFamily(aName),
-        mContainsAppFonts(false)
+        mContainsAppFonts(false),
+        mHasNonScalableFaces(false)
     { }
 
     void FindStyleVariations(FontInfoData *aFontInfoData = nullptr) override;
 
     // Families are constructed initially with just references to patterns.
     // When necessary, these are enumerated within FindStyleVariations.
     void AddFontPattern(FcPattern* aFontPattern);
 
     void SetFamilyContainsAppFonts(bool aContainsAppFonts)
     {
         mContainsAppFonts = aContainsAppFonts;
     }
 
+    void
+    FindAllFontsForStyle(const gfxFontStyle& aFontStyle,
+                         nsTArray<gfxFontEntry*>& aFontEntryList,
+                         bool& aNeedsSyntheticBold) override;
+
 protected:
     virtual ~gfxFontconfigFontFamily() { }
 
     nsTArray<nsCountedRef<FcPattern> > mFontPatterns;
 
     bool      mContainsAppFonts;
+    bool      mHasNonScalableFaces;
 };
 
 class gfxFontconfigFont : public gfxFontconfigFontBase {
 public:
     gfxFontconfigFont(cairo_scaled_font_t *aScaledFont,
                       FcPattern *aPattern,
                       gfxFloat aAdjustedSize,
                       gfxFontEntry *aFontEntry,
--- a/gfx/thebes/gfxFontEntry.h
+++ b/gfx/thebes/gfxFontEntry.h
@@ -633,17 +633,17 @@ public:
     // choose a specific face to match a style using CSS font matching
     // rules (weight matching occurs here).  may return a face that doesn't
     // precisely match (e.g. normal face when no italic face exists).
     // aNeedsSyntheticBold is set to true when synthetic bolding is
     // needed, false otherwise
     gfxFontEntry *FindFontForStyle(const gfxFontStyle& aFontStyle, 
                                    bool& aNeedsSyntheticBold);
 
-    void
+    virtual void
     FindAllFontsForStyle(const gfxFontStyle& aFontStyle,
                          nsTArray<gfxFontEntry*>& aFontEntryList,
                          bool& aNeedsSyntheticBold);
 
     // checks for a matching font within the family
     // used as part of the font fallback process
     void FindFontForChar(GlobalFontMatch *aMatchData);
 
--- a/ipc/glue/BackgroundUtils.cpp
+++ b/ipc/glue/BackgroundUtils.cpp
@@ -84,18 +84,17 @@ PrincipalInfoToPrincipal(const Principal
         return nullptr;
       }
 
       OriginAttributes attrs;
       if (info.attrs().mAppId != nsIScriptSecurityManager::UNKNOWN_APP_ID) {
         attrs = info.attrs();
       }
       principal = BasePrincipal::CreateCodebasePrincipal(uri, attrs);
-      rv = principal ? NS_OK : NS_ERROR_FAILURE;
-      if (NS_WARN_IF(NS_FAILED(rv))) {
+      if (NS_WARN_IF(!principal)) {
         return nullptr;
       }
 
       // When the principal is serialized, the origin is extract from it. This
       // can fail, and in case, here we will havea Tvoid_t. If we have a string,
       // it must match with what the_new_principal.getOrigin returns.
       if (info.originNoSuffix().type() == ContentPrincipalInfoOriginNoSuffix::TnsCString) {
         nsAutoCString originNoSuffix;
--- a/ipc/glue/PBackgroundSharedTypes.ipdlh
+++ b/ipc/glue/PBackgroundSharedTypes.ipdlh
@@ -13,19 +13,23 @@ union ContentPrincipalInfoOriginNoSuffix
   nsCString;
   void_t;
 };
 
 struct ContentPrincipalInfo
 {
   OriginAttributes attrs;
 
-  // nsIPrincipal.originNoSuffix can fail. In case this happens, this value
-  // will be set to void_t. So far, this is used only for dom/media.
-  // It will be removed in bug 1347817.
+  // Origin is not simply a part of the spec. Based on the scheme of the URI
+  // spec, we generate different kind of origins: for instance any file: URL
+  // shares the same origin, about: URLs have the full spec as origin and so
+  // on.
+  // Another important reason why we have this attribute is that
+  // ContentPrincipalInfo is used out of the main-thread. Having this value
+  // here allows us to retrive the origin without creating a full nsIPrincipal.
   ContentPrincipalInfoOriginNoSuffix originNoSuffix;
 
   nsCString spec;
 };
 
 struct SystemPrincipalInfo
 { };
 
--- a/js/src/jit-test/tests/wasm/profiling.js
+++ b/js/src/jit-test/tests/wasm/profiling.js
@@ -1,23 +1,27 @@
-// Single-step profiling currently only works in the ARM simulator
-if (!getBuildConfiguration()["arm-simulator"])
+try {
+    enableSingleStepProfiling();
+    disableSingleStepProfiling();
+} catch(e) {
+    // Single step profiling not supported here.
     quit();
+}
 
 const Module = WebAssembly.Module;
 const Instance = WebAssembly.Instance;
 const Table = WebAssembly.Table;
 
 function normalize(stack)
 {
     var wasmFrameTypes = [
-        {re:/^entry trampoline \(in asm.js\)$/,             sub:">"},
-        {re:/^wasm-function\[(\d+)\] \(.*\)$/,              sub:"$1"},
-        {re:/^(fast|slow) FFI trampoline \(in asm.js\)$/,   sub:"<"},
-        {re:/ \(in asm.js\)$/,                              sub:""}
+        {re:/^entry trampoline \(in wasm\)$/,             sub:">"},
+        {re:/^wasm-function\[(\d+)\] \(.*\)$/,            sub:"$1"},
+        {re:/^(fast|slow) FFI trampoline \(in wasm\)$/,   sub:"<"},
+        {re:/ \(in wasm\)$/,                              sub:""}
     ];
 
     var framesIn = stack.split(',');
     var framesOut = [];
     for (let frame of framesIn) {
         for (let {re, sub} of wasmFrameTypes) {
             if (re.test(frame)) {
                 framesOut.push(frame.replace(re, sub));
--- a/js/src/jit/MoveResolver.h
+++ b/js/src/jit/MoveResolver.h
@@ -278,17 +278,16 @@ class MoveResolver
             MOZ_ASSERT(!cycleEnd_);
             cycleEnd_ = true;
             cycleEndSlot_ = cycleSlot;
         }
     };
 
     typedef InlineList<MoveResolver::PendingMove>::iterator PendingMoveIterator;
 
-  private:
     js::Vector<MoveOp, 16, SystemAllocPolicy> orderedMoves_;
     int numCycles_;
     int curCycles_;
     TempObjectPool<PendingMove> movePool_;
 
     InlineList<PendingMove> pending_;
 
     PendingMove* findBlockingMove(const PendingMove* last);
--- a/js/src/jit/RegisterSets.h
+++ b/js/src/jit/RegisterSets.h
@@ -1354,18 +1354,24 @@ class ABIArg
     Register evenGpr() const {
         MOZ_ASSERT(isGeneralRegPair());
         return Register::FromCode(u.gpr_);
     }
     Register oddGpr() const {
         MOZ_ASSERT(isGeneralRegPair());
         return Register::FromCode(u.gpr_ + 1);
     }
-    FloatRegister fpu() const { MOZ_ASSERT(kind() == FPU); return FloatRegister::FromCode(u.fpu_); }
-    uint32_t offsetFromArgBase() const { MOZ_ASSERT(kind() == Stack); return u.offset_; }
+    FloatRegister fpu() const {
+        MOZ_ASSERT(kind() == FPU);
+        return FloatRegister::FromCode(u.fpu_);
+    }
+    uint32_t offsetFromArgBase() const {
+        MOZ_ASSERT(kind() == Stack);
+        return u.offset_;
+    }
 
     bool argInRegister() const { return kind() != Stack; }
     AnyRegister reg() const { return kind_ == GPR ? AnyRegister(gpr()) : AnyRegister(fpu()); }
 
     bool operator==(const ABIArg& rhs) const {
         if (kind_ != rhs.kind_)
             return false;
 
--- a/js/src/jit/arm/MacroAssembler-arm.cpp
+++ b/js/src/jit/arm/MacroAssembler-arm.cpp
@@ -5227,34 +5227,31 @@ MacroAssembler::callWithABIPre(uint32_t*
 }
 
 void
 MacroAssembler::callWithABIPost(uint32_t stackAdjust, MoveOp::Type result)
 {
     if (secondScratchReg_ != lr)
         ma_mov(secondScratchReg_, lr);
 
-    switch (result) {
-      case MoveOp::DOUBLE:
-        if (!UseHardFpABI()) {
+    if (!UseHardFpABI()) {
+        switch (result) {
+          case MoveOp::DOUBLE:
             // Move double from r0/r1 to ReturnFloatReg.
             ma_vxfer(r0, r1, ReturnDoubleReg);
-        }
-        break;
-      case MoveOp::FLOAT32:
-        if (!UseHardFpABI()) {
+            break;
+          case MoveOp::FLOAT32:
             // Move float32 from r0 to ReturnFloatReg.
-            ma_vxfer(r0, ReturnFloat32Reg.singleOverlay());
+            ma_vxfer(r0, ReturnFloat32Reg);
+            break;
+          case MoveOp::GENERAL:
+            break;
+          default:
+            MOZ_CRASH("unexpected callWithABI result");
         }
-        break;
-      case MoveOp::GENERAL:
-        break;
-
-      default:
-        MOZ_CRASH("unexpected callWithABI result");
     }
 
     freeStack(stackAdjust);
 
     if (dynamicAlignment_) {
         // While the x86 supports pop esp, on ARM that isn't well defined, so
         // just do it manually.
         as_dtr(IsLoad, 32, Offset, sp, DTRAddr(sp, DtrOffImm(0)));
--- a/js/src/jit/x86/Assembler-x86.cpp
+++ b/js/src/jit/x86/Assembler-x86.cpp
@@ -22,19 +22,16 @@ ABIArgGenerator::next(MIRType type)
     switch (type) {
       case MIRType::Int32:
       case MIRType::Float32:
       case MIRType::Pointer:
         current_ = ABIArg(stackOffset_);
         stackOffset_ += sizeof(uint32_t);
         break;
       case MIRType::Double:
-        current_ = ABIArg(stackOffset_);
-        stackOffset_ += sizeof(uint64_t);
-        break;
       case MIRType::Int64:
         current_ = ABIArg(stackOffset_);
         stackOffset_ += sizeof(uint64_t);
         break;
       case MIRType::Int8x16:
       case MIRType::Int16x8:
       case MIRType::Int32x4:
       case MIRType::Float32x4:
@@ -53,21 +50,18 @@ ABIArgGenerator::next(MIRType type)
     }
     return current_;
 }
 
 void
 Assembler::executableCopy(uint8_t* buffer, bool flushICache)
 {
     AssemblerX86Shared::executableCopy(buffer);
-
-    for (size_t i = 0; i < jumps_.length(); i++) {
-        RelativePatch& rp = jumps_[i];
+    for (RelativePatch& rp : jumps_)
         X86Encoding::SetRel32(buffer + rp.offset, rp.target);
-    }
 }
 
 class RelocationIterator
 {
     CompactBufferReader reader_;
     uint32_t offset_;
 
   public:
--- a/js/src/wasm/WasmFrameIterator.cpp
+++ b/js/src/wasm/WasmFrameIterator.cpp
@@ -73,17 +73,22 @@ FrameIterator::FrameIterator(WasmActivat
 {
     // When execution is interrupted, the embedding may capture a stack trace.
     // Since we've lost all the register state, we can't unwind the full stack
     // like ProfilingFrameIterator does. However, we can recover the interrupted
     // function via the resumePC and at least print that frame.
     if (void* resumePC = activation->resumePC()) {
         code_ = activation->compartment()->wasm.lookupCode(resumePC);
         codeRange_ = code_->lookupRange(resumePC);
-        MOZ_ASSERT(codeRange_->kind() == CodeRange::Function);
+        if (codeRange_->kind() != CodeRange::Function) {
+            // We might be in a stub inserted between functions, in which case
+            // we don't have a frame.
+            codeRange_ = nullptr;
+            missingFrameMessage_ = true;
+        }
         MOZ_ASSERT(!done());
         return;
     }
 
     fp_ = activation->exitFP();
 
     if (!fp_) {
         MOZ_ASSERT(done());
@@ -757,43 +762,43 @@ ProfilingFrameIterator::label() const
 {
     MOZ_ASSERT(!done());
 
     // Use the same string for both time inside and under so that the two
     // entries will be coalesced by the profiler.
     //
     // NB: these labels are parsed for location by
     //     devtools/client/performance/modules/logic/frame-utils.js
-    const char* importJitDescription = "fast FFI trampoline (in asm.js)";
-    const char* importInterpDescription = "slow FFI trampoline (in asm.js)";
-    const char* trapDescription = "trap handling (in asm.js)";
-    const char* debugTrapDescription = "debug trap handling (in asm.js)";
+    static const char* importJitDescription = "fast FFI trampoline (in wasm)";
+    static const char* importInterpDescription = "slow FFI trampoline (in wasm)";
+    static const char* trapDescription = "trap handling (in wasm)";
+    static const char* debugTrapDescription = "debug trap handling (in wasm)";
 
     switch (exitReason_) {
       case ExitReason::None:
         break;
       case ExitReason::ImportJit:
         return importJitDescription;
       case ExitReason::ImportInterp:
         return importInterpDescription;
       case ExitReason::Trap:
         return trapDescription;
       case ExitReason::DebugTrap:
         return debugTrapDescription;
     }
 
     switch (codeRange_->kind()) {
       case CodeRange::Function:         return code_->profilingLabel(codeRange_->funcIndex());
-      case CodeRange::Entry:            return "entry trampoline (in asm.js)";
+      case CodeRange::Entry:            return "entry trampoline (in wasm)";
       case CodeRange::ImportJitExit:    return importJitDescription;
       case CodeRange::ImportInterpExit: return importInterpDescription;
       case CodeRange::TrapExit:         return trapDescription;
       case CodeRange::DebugTrap:        return debugTrapDescription;
-      case CodeRange::Inline:           return "inline stub (in asm.js)";
-      case CodeRange::FarJumpIsland:    return "interstitial (in asm.js)";
+      case CodeRange::Inline:           return "inline stub (in wasm)";
+      case CodeRange::FarJumpIsland:    return "interstitial (in wasm)";
       case CodeRange::Throw:            MOZ_FALLTHROUGH;
       case CodeRange::Interrupt:        MOZ_CRASH("does not have a frame");
     }
 
     MOZ_CRASH("bad code range kind");
 }
 
 void
--- a/js/src/wasm/WasmGenerator.cpp
+++ b/js/src/wasm/WasmGenerator.cpp
@@ -644,17 +644,17 @@ ModuleGenerator::finishCodegen()
 
     // Code-generation is complete!
 
     masm_.finish();
     return !masm_.oom();
 }
 
 bool
-ModuleGenerator::finishLinkData(Bytes& code)
+ModuleGenerator::finishLinkData()
 {
     // Inflate the global bytes up to page size so that the total bytes are a
     // page size (as required by the allocator functions).
     linkData_.globalDataLength = AlignBytes(linkData_.globalDataLength, gc::SystemPageSize());
 
     // Add links to absolute addresses identified symbolically.
     for (size_t i = 0; i < masm_.numSymbolicAccesses(); i++) {
         SymbolicAccess src = masm_.symbolicAccess(i);
@@ -1176,17 +1176,17 @@ ModuleGenerator::finish(const ShareableB
 #ifdef DEBUG
     uint32_t lastOffset = 0;
     for (uint32_t debugTrapFarJumpOffset : metadata_->debugTrapFarJumpOffsets) {
         MOZ_ASSERT(debugTrapFarJumpOffset >= lastOffset);
         lastOffset = debugTrapFarJumpOffset;
     }
 #endif
 
-    if (!finishLinkData(code))
+    if (!finishLinkData())
         return nullptr;
 
     return SharedModule(js_new<Module>(Move(assumptions_),
                                        Move(code),
                                        Move(linkData_),
                                        Move(env_->imports),
                                        Move(env_->exports),
                                        Move(env_->dataSegments),
--- a/js/src/wasm/WasmGenerator.h
+++ b/js/src/wasm/WasmGenerator.h
@@ -258,17 +258,17 @@ class MOZ_STACK_CLASS ModuleGenerator
     const CodeRange& funcCodeRange(uint32_t funcIndex) const;
     uint32_t numFuncImports() const;
     MOZ_MUST_USE bool patchCallSites();
     MOZ_MUST_USE bool patchFarJumps(const TrapExitOffsetArray& trapExits, const Offsets& debugTrapStub);
     MOZ_MUST_USE bool finishTask(CompileTask* task);
     MOZ_MUST_USE bool finishOutstandingTask();
     MOZ_MUST_USE bool finishFuncExports();
     MOZ_MUST_USE bool finishCodegen();
-    MOZ_MUST_USE bool finishLinkData(Bytes& code);
+    MOZ_MUST_USE bool finishLinkData();
     MOZ_MUST_USE bool addFuncImport(const Sig& sig, uint32_t globalDataOffset);
     MOZ_MUST_USE bool allocateGlobalBytes(uint32_t bytes, uint32_t align, uint32_t* globalDataOff);
     MOZ_MUST_USE bool allocateGlobal(GlobalDesc* global);
 
     MOZ_MUST_USE bool launchBatchCompile();
 
     MOZ_MUST_USE bool initAsmJS(Metadata* asmJSMetadata);
     MOZ_MUST_USE bool initWasm(const CompileArgs& args);
--- a/js/src/wasm/WasmStubs.cpp
+++ b/js/src/wasm/WasmStubs.cpp
@@ -506,17 +506,17 @@ wasm::GenerateImportFunction(jit::MacroA
 // signature of the import and calls into an appropriate callImport C++
 // function, having boxed all the ABI arguments into a homogeneous Value array.
 CallableOffsets
 wasm::GenerateImportInterpExit(MacroAssembler& masm, const FuncImport& fi, uint32_t funcImportIndex,
                                Label* throwLabel)
 {
     masm.setFramePushed(0);
 
-    // Argument types for Module::callImport_*:
+    // Argument types for Instance::callImport_*:
     static const MIRType typeArray[] = { MIRType::Pointer,   // Instance*
                                          MIRType::Pointer,   // funcImportIndex
                                          MIRType::Int32,     // argc
                                          MIRType::Pointer }; // argv
     MIRTypeVector invokeArgTypes;
     MOZ_ALWAYS_TRUE(invokeArgTypes.append(typeArray, ArrayLength(typeArray)));
 
     // At the point of the call, the stack layout shall be (sp grows to the left):
@@ -530,17 +530,17 @@ wasm::GenerateImportInterpExit(MacroAsse
     CallableOffsets offsets;
     GenerateExitPrologue(masm, framePushed, ExitReason::ImportInterp, &offsets);
 
     // Fill the argument array.
     unsigned offsetToCallerStackArgs = sizeof(Frame) + masm.framePushed();
     Register scratch = ABINonArgReturnReg0;
     FillArgumentArray(masm, fi.sig().args(), argOffset, offsetToCallerStackArgs, scratch, ToValue(false));
 
-    // Prepare the arguments for the call to Module::callImport_*.
+    // Prepare the arguments for the call to Instance::callImport_*.
     ABIArgMIRTypeIter i(invokeArgTypes);
 
     // argument 0: Instance*
     Address instancePtr(WasmTlsReg, offsetof(TlsData, instance));
     if (i->kind() == ABIArg::GPR) {
         masm.loadPtr(instancePtr, i->gpr());
     } else {
         masm.loadPtr(instancePtr, scratch);
--- a/js/xpconnect/src/XPCJSContext.cpp
+++ b/js/xpconnect/src/XPCJSContext.cpp
@@ -1630,17 +1630,17 @@ XPCJSContext::~XPCJSContext()
     // Tell the profiler that the context is gone
     profiler_clear_js_context();
 #endif
 
     Preferences::UnregisterPrefixCallback(ReloadPrefsCallback,
                                           JS_OPTIONS_DOT_STR, this);
 
 #ifdef FUZZING
-    Preferences::UnRegisterCallback(ReloadPrefsCallback, "fuzzing.enabled", this);
+    Preferences::UnregisterCallback(ReloadPrefsCallback, "fuzzing.enabled", this);
 #endif
 }
 
 // If |*anonymizeID| is non-zero and this is a user compartment, the name will
 // be anonymized.
 static void
 GetCompartmentName(JSCompartment* c, nsCString& name, int* anonymizeID,
                    bool replaceSlashes)
--- a/layout/generic/crashtests/crashtests.list
+++ b/layout/generic/crashtests/crashtests.list
@@ -20,17 +20,17 @@ load 309322-1.html # bug 1338007
 load 309322-2.html # bug 1338007
 load 309322-3.html
 load 309322-4.html
 load 310556-1.xhtml
 load 321224.xul
 load 322780-1.xul
 load 323381-1.html
 load 323381-2.html
-asserts-if(gtkWidget,1) asserts-if(Android&&asyncPan,1) asserts-if(stylo,0) asserts-if(winWidget,1) load 323386-1.html # Bug 718883
+asserts-if(gtkWidget,1) asserts-if(Android&&asyncPan,1) asserts-if(stylo,0) load 323386-1.html # Bug 718883
 load 323389-1.html
 load 323389-2.html
 load 323493-1.html
 load 323495-1.html
 load 324318-1.html
 load 328946-1.html
 load 331284-1.xhtml
 load 331292.html
--- a/layout/generic/nsFrame.cpp
+++ b/layout/generic/nsFrame.cpp
@@ -1305,21 +1305,26 @@ nsIFrame::GetMarginRectRelativeToSelf() 
 }
 
 bool
 nsIFrame::IsTransformed() const
 {
   return ((mState & NS_FRAME_MAY_BE_TRANSFORMED) &&
           (StyleDisplay()->HasTransform(this) ||
            IsSVGTransformed() ||
-           (mContent &&
-            nsLayoutUtils::HasAnimationOfProperty(this,
-                                                  eCSSProperty_transform) &&
-            IsFrameOfType(eSupportsCSSTransforms) &&
-            mContent->GetPrimaryFrame() == this)));
+           HasAnimationOfTransform()));
+}
+
+bool
+nsIFrame::HasAnimationOfTransform() const
+{
+  return mContent &&
+    nsLayoutUtils::HasAnimationOfProperty(this, eCSSProperty_transform) &&
+    IsFrameOfType(eSupportsCSSTransforms) &&
+    mContent->GetPrimaryFrame() == this;
 }
 
 bool
 nsIFrame::HasOpacityInternal(float aThreshold) const
 {
   MOZ_ASSERT(0.0 <= aThreshold && aThreshold <= 1.0, "Invalid argument");
   return StyleEffects()->mOpacity < aThreshold ||
          (StyleDisplay()->mWillChangeBitField & NS_STYLE_WILL_CHANGE_OPACITY) ||
--- a/layout/generic/nsIFrame.h
+++ b/layout/generic/nsIFrame.h
@@ -1637,16 +1637,21 @@ public:
    * Returns true if this frame is transformed (e.g. has CSS or SVG transforms)
    * or if its parent is an SVG frame that has children-only transforms (e.g.
    * an SVG viewBox attribute) or if its transform-style is preserve-3d or
    * the frame has transform animations.
    */
   bool IsTransformed() const;
 
   /**
+   * True if this frame has any animation of transform in effect.
+   */
+  bool HasAnimationOfTransform() const;
+
+  /**
    * Returns true if the frame is translucent or the frame has opacity
    * animations for the purposes of creating a stacking context.
    */
   bool HasOpacity() const
   {
     return HasOpacityInternal(1.0f);
   }
   /**
--- a/layout/painting/FrameLayerBuilder.cpp
+++ b/layout/painting/FrameLayerBuilder.cpp
@@ -1540,16 +1540,21 @@ public:
   RefPtr<ImageLayer> mImageLayer;
 
   // The region for which display item visibility for this layer has already
   // been calculated. Used to reduce the number of calls to
   // RecomputeVisibilityForItems if it is known in advance that a larger
   // region will be painted during a transaction than in a single call to
   // DrawPaintedLayer, for example when progressive paint is enabled.
   nsIntRegion mVisibilityComputedRegion;
+
+  /**
+   * This is set when the painted layer has no component alpha.
+   */
+  bool mDisabledAlpha;
 };
 
 /*
  * User data for layers which will be used as masks.
  */
 struct MaskLayerUserData : public LayerUserData
 {
   MaskLayerUserData()
@@ -2390,16 +2395,18 @@ ContainerState::CreatePaintedLayer(Paint
   // Create a new painted layer
   RefPtr<PaintedLayer> layer = mManager->CreatePaintedLayerWithHint(creationHint);
   if (!layer) {
     return nullptr;
   }
 
   // Mark this layer as being used for painting display items
   PaintedDisplayItemLayerUserData* userData = new PaintedDisplayItemLayerUserData();
+  userData->mDisabledAlpha =
+    mParameters.mDisableSubpixelAntialiasingInDescendants;
   layer->SetUserData(&gPaintedDisplayItemLayerUserData, userData);
   ResetScrollPositionForLayerPixelAlignment(aData->mAnimatedGeometryRoot);
 
   PreparePaintedLayerForUse(layer, userData, aData->mAnimatedGeometryRoot,
                             aData->mReferenceFrame,
                             aData->mAnimatedGeometryRootOffset, true);
 
   return layer.forget();
@@ -2488,21 +2495,30 @@ ContainerState::PreparePaintedLayerForUs
                        RoundToMatchResidual(scaledOffset.y, aData->mAnimatedGeometryRootPosition.y));
   aData->mTranslation = pixOffset;
   pixOffset += mParameters.mOffset;
   Matrix matrix = Matrix::Translation(pixOffset.x, pixOffset.y);
   aLayer->SetBaseTransform(Matrix4x4::From2D(matrix));
 
   aData->mVisibilityComputedRegion.SetEmpty();
 
-  // FIXME: Temporary workaround for bug 681192 and bug 724786.
-#ifndef MOZ_WIDGET_ANDROID
   // Calculate exact position of the top-left of the active scrolled root.
   // This might not be 0,0 due to the snapping in ScaleToNearestPixels.
   gfxPoint animatedGeometryRootTopLeft = scaledOffset - ThebesPoint(matrix.GetTranslation()) + mParameters.mOffset;
+  const bool disableAlpha =
+    mParameters.mDisableSubpixelAntialiasingInDescendants;
+  if (aData->mDisabledAlpha != disableAlpha) {
+    aData->mAnimatedGeometryRootPosition = animatedGeometryRootTopLeft;
+    InvalidateEntirePaintedLayer(aLayer, aAnimatedGeometryRoot, "change of subpixel-AA");
+    aData->mDisabledAlpha = disableAlpha;
+    return;
+  }
+
+  // FIXME: Temporary workaround for bug 681192 and bug 724786.
+#ifndef MOZ_WIDGET_ANDROID
   // If it has changed, then we need to invalidate the entire layer since the
   // pixels in the layer buffer have the content at a (subpixel) offset
   // from what we need.
   if (!animatedGeometryRootTopLeft.WithinEpsilonOf(aData->mAnimatedGeometryRootPosition, SUBPIXEL_OFFSET_EPSILON)) {
     aData->mAnimatedGeometryRootPosition = animatedGeometryRootTopLeft;
     InvalidateEntirePaintedLayer(aLayer, aAnimatedGeometryRoot, "subpixel offset");
   } else if (didResetScrollPositionForLayerPixelAlignment) {
     aData->mAnimatedGeometryRootPosition = animatedGeometryRootTopLeft;
@@ -5520,17 +5536,20 @@ ChooseScaleAndSetTransform(FrameLayerBui
     if (ActiveLayerTracker::IsStyleAnimated(aDisplayListBuilder, aContainerFrame,
                                             eCSSProperty_transform)) {
       aOutgoingScale.mInActiveTransformedSubtree = true;
     }
   }
   if ((aLayerBuilder->IsBuildingRetainedLayers() &&
        (!canDraw2D || transform2d.HasNonIntegerTranslation())) ||
       aContainerFrame->Extend3DContext() ||
-      aContainerFrame->Combines3DTransformWithAncestors()) {
+      aContainerFrame->Combines3DTransformWithAncestors() ||
+      // For async transform animation, the value would be changed at
+      // any time, integer translation is not always true.
+      aContainerFrame->HasAnimationOfTransform()) {
     aOutgoingScale.mDisableSubpixelAntialiasingInDescendants = true;
   }
   return true;
 }
 
 already_AddRefed<ContainerLayer>
 FrameLayerBuilder::BuildContainerLayerFor(nsDisplayListBuilder* aBuilder,
                                           LayerManager* aManager,
--- a/layout/printing/nsPagePrintTimer.cpp
+++ b/layout/printing/nsPagePrintTimer.cpp
@@ -5,50 +5,47 @@
 
 #include "nsPagePrintTimer.h"
 
 #include "mozilla/Unused.h"
 #include "nsIContentViewer.h"
 #include "nsIServiceManager.h"
 #include "nsPrintEngine.h"
 
-using namespace mozilla;
-
 NS_IMPL_ISUPPORTS_INHERITED(nsPagePrintTimer, mozilla::Runnable, nsITimerCallback)
 
 nsPagePrintTimer::~nsPagePrintTimer()
 {
   // "Destroy" the document viewer; this normally doesn't actually
   // destroy it because of the IncrementDestroyRefCount call below
   // XXX This is messy; the document viewer should use a single approach
   // to keep itself alive during printing
   nsCOMPtr<nsIContentViewer> cv(do_QueryInterface(mDocViewerPrint));
   if (cv) {
     cv->Destroy();
   }
 }
 
-nsresult
+nsresult 
 nsPagePrintTimer::StartTimer(bool aUseDelay)
 {
   nsresult result;
   mTimer = do_CreateInstance("@mozilla.org/timer;1", &result);
   if (NS_FAILED(result)) {
     NS_WARNING("unable to start the timer");
   } else {
     uint32_t delay = 0;
     if (aUseDelay) {
       if (mFiringCount < 10) {
         // Longer delay for the few first pages.
         delay = mDelay + ((10 - mFiringCount) * 100);
       } else {
         delay = mDelay;
       }
     }
-    mTimer->SetTarget(mDocument->EventTargetFor(TaskCategory::Other));
     mTimer->InitWithCallback(this, delay, nsITimer::TYPE_ONE_SHOT);
   }
   return result;
 }
 
 nsresult
 nsPagePrintTimer::StartWatchDogTimer()
 {
@@ -57,17 +54,16 @@ nsPagePrintTimer::StartWatchDogTimer()
     mWatchDogTimer->Cancel();
   }
   mWatchDogTimer = do_CreateInstance("@mozilla.org/timer;1", &result);
   if (NS_FAILED(result)) {
     NS_WARNING("unable to start the timer");
   } else {
     // Instead of just doing one timer for a long period do multiple so we
     // can check if the user cancelled the printing.
-    mWatchDogTimer->SetTarget(mDocument->EventTargetFor(TaskCategory::Other));
     mWatchDogTimer->InitWithCallback(this, WATCH_DOG_INTERVAL,
                                      nsITimer::TYPE_ONE_SHOT);
   }
   return result;
 }
 
 void
 nsPagePrintTimer::StopWatchDogTimer()
@@ -157,18 +153,17 @@ nsPagePrintTimer::Notify(nsITimer *timer
   if (mDocViewerPrint) {
     bool donePrePrint = true;
     if (mPrintEngine) {
       donePrePrint = mPrintEngine->PrePrintPage();
     }
 
     if (donePrePrint && !mWaitingForRemotePrint) {
       StopWatchDogTimer();
-      // Pass nullptr here since name already was set in constructor.
-      mDocument->Dispatch(nullptr, TaskCategory::Other, do_AddRef(this));
+      NS_DispatchToMainThread(this);
     } else {
       // Start the watch dog if we're waiting for preprint to ensure that if any
       // mozPrintCallbacks take to long we error out.
       StartWatchDogTimer();
     }
 
   }
   return NS_OK;
@@ -188,32 +183,30 @@ nsPagePrintTimer::WaitForRemotePrint()
 
 void
 nsPagePrintTimer::RemotePrintFinished()
 {
   if (!mWaitingForRemotePrint) {
     return;
   }
 
-  mWaitingForRemotePrint->SetTarget(
-    mDocument->EventTargetFor(mozilla::TaskCategory::Other));
   mozilla::Unused <<
     mWaitingForRemotePrint->InitWithCallback(this, 0, nsITimer::TYPE_ONE_SHOT);
 }
 
-nsresult
+nsresult 
 nsPagePrintTimer::Start(nsPrintObject* aPO)
 {
   mPrintObj = aPO;
   mDone = false;
   return StartTimer(false);
 }
 
 
-void
+void  
 nsPagePrintTimer::Stop()
 {
   if (mTimer) {
     mTimer->Cancel();
     mTimer = nullptr;
   }
   StopWatchDogTimer();
 }
--- a/layout/printing/nsPagePrintTimer.h
+++ b/layout/printing/nsPagePrintTimer.h
@@ -9,43 +9,38 @@
 #include "nsITimer.h"
 
 #include "nsIDocumentViewerPrint.h"
 #include "nsPrintObject.h"
 #include "mozilla/Attributes.h"
 #include "nsThreadUtils.h"
 
 class nsPrintEngine;
-class nsIDocument;
 
 //---------------------------------------------------
 //-- Page Timer Class
 //---------------------------------------------------
 class nsPagePrintTimer final : public mozilla::Runnable,
                                public nsITimerCallback
 {
 public:
 
   NS_DECL_ISUPPORTS_INHERITED
 
   nsPagePrintTimer(nsPrintEngine* aPrintEngine,
                    nsIDocumentViewerPrint* aDocViewerPrint,
-                   nsIDocument* aDocument,
                    uint32_t aDelay)
-    : Runnable("nsPagePrintTimer")
-    , mPrintEngine(aPrintEngine)
+    : mPrintEngine(aPrintEngine)
     , mDocViewerPrint(aDocViewerPrint)
-    , mDocument(aDocument)
     , mDelay(aDelay)
     , mFiringCount(0)
     , mPrintObj(nullptr)
     , mWatchDogCount(0)
     , mDone(false)
   {
-    MOZ_ASSERT(aDocument);
     mDocViewerPrint->IncrementDestroyRefCount();
   }
 
   NS_DECL_NSITIMERCALLBACK
 
   nsresult Start(nsPrintObject* aPO);
 
   NS_IMETHOD Run() override;
@@ -62,17 +57,16 @@ private:
 
   nsresult StartTimer(bool aUseDelay);
   nsresult StartWatchDogTimer();
   void     StopWatchDogTimer();
   void     Fail();
 
   nsPrintEngine*             mPrintEngine;
   nsCOMPtr<nsIDocumentViewerPrint> mDocViewerPrint;
-  nsCOMPtr<nsIDocument>      mDocument;
   nsCOMPtr<nsITimer>         mTimer;
   nsCOMPtr<nsITimer>         mWatchDogTimer;
   nsCOMPtr<nsITimer>         mWaitingForRemotePrint;
   uint32_t                   mDelay;
   uint32_t                   mFiringCount;
   nsPrintObject *            mPrintObj;
   uint32_t                   mWatchDogCount;
   bool                       mDone;
--- a/layout/printing/nsPrintEngine.cpp
+++ b/layout/printing/nsPrintEngine.cpp
@@ -3490,25 +3490,21 @@ nsPrintEngine::FinishPrintPreview()
 
 /*=============== Timer Related Code ======================*/
 nsresult
 nsPrintEngine::StartPagePrintTimer(const UniquePtr<nsPrintObject>& aPO)
 {
   if (!mPagePrintTimer) {
     // Get the delay time in between the printing of each page
     // this gives the user more time to press cancel
-    if (!mDocument) {
-      MOZ_LOG(gPrintingLog, LogLevel::Error,("Error! mDocument is NULL"));
-      return NS_ERROR_FAILURE;
-    }
     int32_t printPageDelay = 50;
     mPrt->mPrintSettings->GetPrintPageDelay(&printPageDelay);
 
     RefPtr<nsPagePrintTimer> timer =
-      new nsPagePrintTimer(this, mDocViewerPrint, mDocument, printPageDelay);
+      new nsPagePrintTimer(this, mDocViewerPrint, printPageDelay);
     timer.forget(&mPagePrintTimer);
 
     nsCOMPtr<nsIPrintSession> printSession;
     nsresult rv = mPrt->mPrintSettings->GetPrintSession(getter_AddRefs(printSession));
     if (NS_SUCCEEDED(rv) && printSession) {
       RefPtr<mozilla::layout::RemotePrintJobChild> remotePrintJob;
       printSession->GetRemotePrintJob(getter_AddRefs(remotePrintJob));
       if (NS_SUCCEEDED(rv) && remotePrintJob) {
@@ -3555,22 +3551,19 @@ public:
 private:
   nsCOMPtr<nsIDocumentViewerPrint> mDocViewerPrint;
 };
 
 //-----------------------------------------------------------
 void
 nsPrintEngine::FirePrintCompletionEvent()
 {
-  MOZ_ASSERT(NS_IsMainThread());
   nsCOMPtr<nsIRunnable> event = new nsPrintCompletionEvent(mDocViewerPrint);
-  if (NS_FAILED(mDocument->Dispatch("nsPrintCompletionEvent",
-                                    TaskCategory::Other, event.forget()))) {
+  if (NS_FAILED(NS_DispatchToCurrentThread(event)))
     NS_WARNING("failed to dispatch print completion event");
-  }
 }
 
 void
 nsPrintEngine::DisconnectPagePrintTimer()
 {
   if (mPagePrintTimer) {
     mPagePrintTimer->Disconnect();
     NS_RELEASE(mPagePrintTimer);
--- a/layout/reftests/bidi/reftest.list
+++ b/layout/reftests/bidi/reftest.list
@@ -163,12 +163,12 @@ fuzzy-if(xulRuntime.widgetToolkit=="gtk3
 fuzzy-if(Android,254,557) == brackets-2a-rtl.html brackets-2a-rtl-ref.html
 == brackets-2b-ltr.html brackets-2b-ltr-ref.html
 == brackets-2b-rtl.html brackets-2b-rtl-ref.html
 == brackets-2c-ltr.html brackets-2c-ltr-ref.html
 fuzzy-if(Android,254,231) == brackets-2c-rtl.html brackets-2c-rtl-ref.html
 == brackets-3a-ltr.html brackets-3a-ltr-ref.html
 == brackets-3a-rtl.html brackets-3a-rtl-ref.html
 == brackets-3b-ltr.html brackets-3b-ltr-ref.html
-fuzzy-if(winWidget&&layersGPUAccelerated,49,233) fuzzy-if(winWidget&&!layersGPUAccelerated,56,75) == brackets-3b-rtl.html brackets-3b-rtl-ref.html
+== brackets-3b-rtl.html brackets-3b-rtl-ref.html
 == 1217833-1.html 1217833-1-ref.html
 == 1217833-2.html 1217833-2-ref.html
 == 1231175-1.html 1231175-1-ref.html
--- a/layout/reftests/css-break/reftest.list
+++ b/layout/reftests/css-break/reftest.list
@@ -1,13 +1,13 @@
 default-preferences pref(layout.css.box-decoration-break.enabled,true)
 
 == box-decoration-break-1.html box-decoration-break-1-ref.html
 fuzzy(1,20) fuzzy-if(skiaContent,1,700) == box-decoration-break-with-inset-box-shadow-1.html box-decoration-break-with-inset-box-shadow-1-ref.html
-fuzzy(16,460) fuzzy-if(Android,10,3673) fuzzy-if(skiaContent,32,254) fuzzy-if(winWidget,32,152) == box-decoration-break-with-outset-box-shadow-1.html box-decoration-break-with-outset-box-shadow-1-ref.html
+fuzzy(16,460) fuzzy-if(Android,10,3673) fuzzy-if(skiaContent,32,254) == box-decoration-break-with-outset-box-shadow-1.html box-decoration-break-with-outset-box-shadow-1-ref.html
 random-if(!gtkWidget) HTTP(..) == box-decoration-break-border-image.html box-decoration-break-border-image-ref.html
 == box-decoration-break-block-border-padding.html box-decoration-break-block-border-padding-ref.html
 == box-decoration-break-block-margin.html box-decoration-break-block-margin-ref.html
 fuzzy-if(!Android,1,62) fuzzy-if(Android,8,6627) == box-decoration-break-first-letter.html box-decoration-break-first-letter-ref.html #Bug 1313773
 == box-decoration-break-with-bidi.html box-decoration-break-with-bidi-ref.html
 == box-decoration-break-bug-1235152.html box-decoration-break-bug-1235152-ref.html
 == box-decoration-break-bug-1249913.html box-decoration-break-bug-1249913-ref.html
 == vertical-wm-001.html vertical-wm-001-ref.html
--- a/layout/reftests/forms/input/text/reftest.list
+++ b/layout/reftests/forms/input/text/reftest.list
@@ -1,10 +1,10 @@
 == bounds-1.html bounds-1-ref.html
-fuzzy-if(asyncPan&&!layersGPUAccelerated,140,111) fuzzy-if(winWidget&&layersGPUAccelerated,98,108) fuzzy-if(winWidget&&!layersGPUAccelerated,140,108) == size-1.html size-1-ref.html
+fuzzy-if(asyncPan&&!layersGPUAccelerated,140,111) == size-1.html size-1-ref.html
 == size-2.html size-2-ref.html
 HTTP(..) == baseline-1.html baseline-1-ref.html
 HTTP(..) == centering-1.xul centering-1-ref.xul
 == dynamic-height-1.xul dynamic-height-1-ref.xul
 fuzzy-if(skiaContent,1,500) needs-focus == select.html select-ref.html
 == intrinsic-size.html intrinsic-size-ref.html
 == line-height-0.5.html line-height-1.0.html
 != line-height-1.5.html line-height-1.0.html
--- a/layout/reftests/svg/svg-integration/reftest.list
+++ b/layout/reftests/svg/svg-integration/reftest.list
@@ -24,17 +24,17 @@ fuzzy-if(Android,255,30) == clipPath-htm
 == dynamic-conditions-outer-svg-02.xhtml ../pass.svg
 == dynamic-conditions-outer-svg-03.xhtml ../pass.svg
 == dynamic-conditions-outer-svg-04.xhtml ../pass.svg
 == filter-html-01.xhtml filter-html-01-ref.svg
 random-if(Android) == filter-html-01-extref.xhtml filter-html-01-ref.svg # Android: bug 1198380
 == filter-html-zoomed-01.xhtml filter-html-01-ref.svg
 == mask-html-01.xhtml mask-html-01-ref.svg
 == mask-html-01-extref-01.xhtml mask-html-01-ref.svg
-== mask-html-01-extref-02.xhtml mask-html-01-ref.svg
+random == mask-html-01-extref-02.xhtml mask-html-01-ref.svg # random due to bug 877661
 == mask-html-zoomed-01.xhtml mask-html-01-ref.svg
 == mask-html-xbl-bound-01.html mask-html-01-ref.svg
 == mask-transformed-html-01.xhtml ../pass.svg
 == mask-transformed-html-02.xhtml ../pass.svg
 fuzzy-if(skiaContent,1,5) == patterned-svg-under-transformed-html-01.xhtml ../pass.svg
 == patterned-svg-under-transformed-html-02.xhtml ../pass.svg
 
 fuzzy(1,5000) == mask-clipPath-opacity-01a.xhtml mask-clipPath-opacity-01-ref.xhtml
--- a/layout/reftests/w3c-css/submitted/writing-modes-3/reftest-stylo.list
+++ b/layout/reftests/w3c-css/submitted/writing-modes-3/reftest-stylo.list
@@ -1,13 +1,13 @@
 # DO NOT EDIT! This is a auto-generated temporary list for Stylo testing
 default-preferences pref(layout.css.text-combine-upright.enabled,true)
 
-== text-combine-upright-break-inside-001.html text-combine-upright-break-inside-001.html
-== text-combine-upright-break-inside-001a.html text-combine-upright-break-inside-001a.html
+fails == text-combine-upright-break-inside-001.html text-combine-upright-break-inside-001.html
+fails == text-combine-upright-break-inside-001a.html text-combine-upright-break-inside-001a.html
 fails == text-combine-upright-compression-001.html text-combine-upright-compression-001.html
 fails == text-combine-upright-compression-002.html text-combine-upright-compression-002.html
 fails == text-combine-upright-compression-003.html text-combine-upright-compression-003.html
 fails == text-combine-upright-compression-004.html text-combine-upright-compression-004.html
 fails == text-combine-upright-compression-005.html text-combine-upright-compression-005.html
 fails == text-combine-upright-compression-005a.html text-combine-upright-compression-005a.html
 fails == text-combine-upright-compression-006.html text-combine-upright-compression-006.html
 fails == text-combine-upright-compression-006a.html text-combine-upright-compression-006a.html
--- a/layout/xul/nsXULPopupManager.cpp
+++ b/layout/xul/nsXULPopupManager.cpp
@@ -1178,16 +1178,19 @@ nsXULPopupManager::HidePopupCallback(nsI
   // behaviour.
   nsEventStatus status = nsEventStatus_eIgnore;
   WidgetMouseEvent event(true, eXULPopupHidden, nullptr,
                          WidgetMouseEvent::eReal);
   EventDispatcher::Dispatch(aPopup, aPopupFrame->PresContext(),
                             &event, nullptr, &status);
   ENSURE_TRUE(weakFrame.IsAlive());
 
+  // Force any popups that might be anchored on elements within this popup to update.
+  UpdatePopupPositions(aPopupFrame->PresContext()->RefreshDriver());
+
   // if there are more popups to close, look for the next one
   if (aNextPopup && aPopup != aLastPopup) {
     nsMenuChainItem* foundMenu = nullptr;
     nsMenuChainItem* item = mPopups;
     while (item) {
       if (item->Content() == aNextPopup) {
         foundMenu = item;
         break;
--- a/mfbt/AlreadyAddRefed.h
+++ b/mfbt/AlreadyAddRefed.h
@@ -22,16 +22,24 @@ struct unused_t;
 /**
  * already_AddRefed cooperates with reference counting smart pointers to enable
  * you to assign in a pointer _without_ |AddRef|ing it.  You might want to use
  * this as a return type from a function that returns an already |AddRef|ed
  * pointer.
  *
  * TODO Move already_AddRefed to namespace mozilla.  This has not yet been done
  * because of the sheer number of usages of already_AddRefed.
+ *
+ * When should you use already_AddRefed<>?
+ * * Ensure a consumer takes ownership of a reference
+ * * Pass ownership without calling AddRef/Release (sometimes required in
+ *   off-main-thread code)
+ * * The ref pointer type you're using doesn't support move construction
+ *
+ * Otherwise, use Move(RefPtr/nsCOMPtr/etc).
  */
 template<class T>
 struct MOZ_MUST_USE_TYPE MOZ_NON_AUTOABLE already_AddRefed
 {
   /*
    * We want to allow returning nullptr from functions returning
    * already_AddRefed<T>, for simplicity.  But we also don't want to allow
    * returning raw T*, instead preferring creation of already_AddRefed<T> from
--- a/mobile/android/base/AndroidManifest.xml.in
+++ b/mobile/android/base/AndroidManifest.xml.in
@@ -312,16 +312,22 @@
 
 #ifdef MOZ_ANDROID_CUSTOM_TABS
         <activity android:name="org.mozilla.gecko.customtabs.CustomTabsActivity"
             android:theme="@style/GeckoCustomTabs" />
 #endif
         <activity android:name="org.mozilla.gecko.webapps.WebAppActivity"
             android:theme="@style/Theme.AppCompat.NoActionBar" />
 
+        <!-- Declare a predefined number of WebApp<num> activities. These are
+             used so that each web app can launch in its own activity. -->
+#define FRAGMENT WebAppManifestFragment.xml.frag.in
+#include WebAppFragmentRepeater.inc
+
+
         <!-- Service to handle requests from overlays. -->
         <service android:name="org.mozilla.gecko.overlays.service.OverlayActionService" />
 
         <!--
           Ensure that passwords provider runs in its own process. (Bug 718760.)
           Process name is per-application to avoid loading CPs from multiple
           Fennec versions into the same process. (Bug 749727.)
           Process name is a mangled version to avoid a Talos bug. (Bug 750548.)
new file mode 100644
--- /dev/null
+++ b/mobile/android/base/WebAppFragmentRepeater.inc
@@ -0,0 +1,32 @@
+#define APPNUM 0
+#include @FRAGMENT@
+
+#define APPNUM 1
+#include @FRAGMENT@
+
+#define APPNUM 2
+#include @FRAGMENT@
+
+#define APPNUM 3
+#include @FRAGMENT@
+
+#define APPNUM 4
+#include @FRAGMENT@
+
+#define APPNUM 5
+#include @FRAGMENT@
+
+#define APPNUM 6
+#include @FRAGMENT@
+
+#define APPNUM 7
+#include @FRAGMENT@
+
+#define APPNUM 8
+#include @FRAGMENT@
+
+#define APPNUM 9
+#include @FRAGMENT@
+
+#undef APPNUM
+#undef FRAGMENT
new file mode 100644
--- /dev/null
+++ b/mobile/android/base/WebAppManifestFragment.xml.frag.in
@@ -0,0 +1,9 @@
+        <activity android:name="org.mozilla.gecko.webapps.WebApps$WebApp@APPNUM@"
+                  android:label="WebApp"
+                  android:configChanges="keyboard|keyboardHidden|mcc|mnc|orientation|screenSize|locale|layoutDirection|smallestScreenSize|screenLayout"
+                  android:windowSoftInputMode="stateUnspecified|adjustResize"
+                  android:theme="@style/Gecko.App"
+                  android:taskAffinity="org.mozilla.gecko.webapps.WebApps@APPNUM@"
+                  android:launchMode="singleTask"
+                  android:exported="true"
+        />
--- a/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java
+++ b/mobile/android/base/java/org/mozilla/gecko/GeckoApp.java
@@ -2237,19 +2237,17 @@ public abstract class GeckoApp
             return;
         }
 
         foregrounded = true;
 
         GeckoAppShell.setGeckoInterface(this);
         GeckoAppShell.setScreenOrientationDelegate(this);
 
-        if (lastSelectedTabId >= 0 && (lastActiveGeckoApp == null || lastActiveGeckoApp.get() != this)) {
-            Tabs.getInstance().selectTab(lastSelectedTabId);
-        }
+        restoreLastSelectedTab();
 
         int newOrientation = getResources().getConfiguration().orientation;
         if (GeckoScreenOrientation.getInstance().update(newOrientation)) {
             refreshChrome();
         }
 
         if (mAppStateListeners != null) {
             for (GeckoAppShell.AppStateListener listener : mAppStateListeners) {
@@ -2291,16 +2289,22 @@ public abstract class GeckoApp
                     Log.w(LOGTAG, "Can't record session: rec is null.");
                 }
             }
         });
 
         Restrictions.update(this);
     }
 
+    protected void restoreLastSelectedTab() {
+        if (lastSelectedTabId >= 0 && (lastActiveGeckoApp == null || lastActiveGeckoApp.get() != this)) {
+            Tabs.getInstance().selectTab(lastSelectedTabId);
+        }
+    }
+
     @Override
     public void onWindowFocusChanged(boolean hasFocus) {
         super.onWindowFocusChanged(hasFocus);
 
         if (!mWindowFocusInitialized && hasFocus) {
             mWindowFocusInitialized = true;
             // XXX our editor tests require the GeckoView to have focus to pass, so we have to
             // manually shift focus to the GeckoView. requestFocus apparently doesn't work at
--- a/mobile/android/base/java/org/mozilla/gecko/LauncherActivity.java
+++ b/mobile/android/base/java/org/mozilla/gecko/LauncherActivity.java
@@ -1,22 +1,24 @@
 /* -*- 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;
 
 import android.app.Activity;
+import android.content.Context;
 import android.content.Intent;
 import android.os.Bundle;
 import android.support.annotation.NonNull;
 import android.support.customtabs.CustomTabsIntent;
 
 import org.mozilla.gecko.webapps.WebAppActivity;
+import org.mozilla.gecko.webapps.WebAppIndexer;
 import org.mozilla.gecko.customtabs.CustomTabsActivity;
 import org.mozilla.gecko.db.BrowserContract;
 import org.mozilla.gecko.mozglue.SafeIntent;
 import org.mozilla.gecko.preferences.GeckoPreferences;
 import org.mozilla.gecko.tabqueue.TabQueueHelper;
 import org.mozilla.gecko.tabqueue.TabQueueService;
 
 /**
@@ -84,21 +86,21 @@ public class LauncherActivity extends Ac
         intent.setClassName(getApplicationContext(), CustomTabsActivity.class.getName());
 
         filterFlags(intent);
 
         startActivity(intent);
     }
 
     private void dispatchWebAppIntent() {
-        Intent intent = new Intent(getIntent());
-        intent.setClassName(getApplicationContext(), WebAppActivity.class.getName());
-
-        filterFlags(intent);
-
+        final Intent intent = new Intent(getIntent());
+        final String manifestPath = getIntent().getStringExtra(WebAppActivity.MANIFEST_PATH);
+        final int index = WebAppIndexer.getInstance().getIndexForManifest(manifestPath, this);
+        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        intent.setClassName(this, WebAppIndexer.WEBAPP_CLASS + index);
         startActivity(intent);
     }
 
     private static void filterFlags(Intent intent) {
         // Explicitly remove the new task and clear task flags (Our browser activity is a single
         // task activity and we never want to start a second task here). See bug 1280112.
         intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_NEW_TASK);
         intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_CLEAR_TASK);
--- a/mobile/android/base/java/org/mozilla/gecko/webapps/WebAppActivity.java
+++ b/mobile/android/base/java/org/mozilla/gecko/webapps/WebAppActivity.java
@@ -4,60 +4,89 @@
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
 package org.mozilla.gecko.webapps;
 
 import java.io.File;
 import java.io.IOException;
 
 import android.app.ActivityManager;
+import android.content.Intent;
 import android.graphics.Bitmap;
+import android.net.Uri;
 import android.os.Build;
 import android.os.Bundle;
 import android.view.Window;
 import android.view.WindowManager;
 import android.util.Log;
 
 import org.json.JSONObject;
 import org.json.JSONException;
 
 import org.mozilla.gecko.AppConstants;
 import org.mozilla.gecko.EventDispatcher;
 import org.mozilla.gecko.GeckoApp;
 import org.mozilla.gecko.GeckoAppShell;
 import org.mozilla.gecko.GeckoProfile;
 import org.mozilla.gecko.icons.decoders.FaviconDecoder;
+import org.mozilla.gecko.mozglue.SafeIntent;
 import org.mozilla.gecko.R;
+import org.mozilla.gecko.Tabs;
 import org.mozilla.gecko.util.ColorUtil;
 import org.mozilla.gecko.util.EventCallback;
 import org.mozilla.gecko.util.FileUtils;
 import org.mozilla.gecko.util.GeckoBundle;
 
 public class WebAppActivity extends GeckoApp {
 
     public static final String INTENT_KEY = "IS_A_WEBAPP";
     public static final String MANIFEST_PATH = "MANIFEST_PATH";
 
     private static final String LOGTAG = "WebAppActivity";
 
     @Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
-
-        String manifestPath = getIntent().getStringExtra(WebAppActivity.MANIFEST_PATH);
-        if (manifestPath != null) {
-            updateFromManifest(manifestPath);
-        }
+        loadManifest(getIntent());
     }
 
     @Override
     public int getLayout() {
         return R.layout.webapp_activity;
     }
 
+    /**
+     * In case this activity is reused (the user has opened > 10 current web apps)
+     * we check that app launched is still within the same host as the
+     * shortcut has set, if not we reload the homescreens url
+     */
+    @Override
+    protected void onNewIntent(Intent externalIntent) {
+
+        restoreLastSelectedTab();
+
+        final SafeIntent intent = new SafeIntent(externalIntent);
+        final String launchUrl = intent.getDataString();
+        final String currentUrl = Tabs.getInstance().getSelectedTab().getURL();
+        final boolean isSameDomain = Uri.parse(currentUrl).getHost()
+            .equals(Uri.parse(launchUrl).getHost());
+
+        if (!isSameDomain) {
+            loadManifest(externalIntent);
+            Tabs.getInstance().loadUrl(launchUrl);
+        }
+    }
+
+    private void loadManifest(Intent intent) {
+        String manifestPath = intent.getStringExtra(WebAppActivity.MANIFEST_PATH);
+        if (manifestPath != null) {
+            updateFromManifest(manifestPath);
+        }
+    }
+
     private void updateFromManifest(String manifestPath) {
         try {
             final File manifestFile = new File(manifestPath);
             final JSONObject manifest = FileUtils.readJSONObjectFromFile(manifestFile);
             final JSONObject manifestField = (JSONObject) manifest.get("manifest");
             final Integer color = readColorFromManifest(manifestField);
             final String name = readNameFromManifest(manifestField);
             final Bitmap icon = readIconFromManifest(manifest);
new file mode 100644
--- /dev/null
+++ b/mobile/android/base/java/org/mozilla/gecko/webapps/WebAppIndexer.java
@@ -0,0 +1,135 @@
+/* -*- 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.webapps;
+
+import java.util.ArrayList;
+
+import android.content.Context;
+import android.content.SharedPreferences;
+import android.support.annotation.UiThread;
+
+import org.mozilla.gecko.GeckoSharedPrefs;
+
+/**
+ * WebAppIndexer lets us create bookmarks that behave like android applications
+ * we create 10 slots of WebAppN in the manifest, when a bookmark is launched
+ * we take its manifest and assign it an index, subsequent launches of that
+ * bookmark are given the same index and therefore reopen the previous activity.
+ * We limit this to 10 spaces and recycle the least recently used index once
+ * we hit the limit, this means if the user can actively use 10 webapps at the same
+ * time, more than that and the last used will be replaced
+ **/
+
+public class WebAppIndexer {
+
+    public static final String WEBAPP_CLASS = "org.mozilla.gecko.webapps.WebApps$WebApp";
+
+    private final String mPrefNumSavedEntries = "WebAppIndexer.numActivities";
+    private final String mPrefActivityIndex = "WebAppIndexer.index";
+    private final String mPrefActivityId = "WebAppIndexer.manifest";
+
+    private static final int MAX_ACTIVITIES = 10;
+    private static final int INVALID_INDEX = -1;
+
+    private ArrayList<ActivityEntry> mActivityList = new ArrayList<ActivityEntry>();
+
+    private static class ActivityEntry {
+        public final int index;
+        public final String manifest;
+        ActivityEntry(int _index, String _manifest) {
+            index = _index;
+            manifest = _manifest;
+        }
+    }
+
+    private WebAppIndexer() { }
+    private final static WebAppIndexer INSTANCE = new WebAppIndexer();
+    public static WebAppIndexer getInstance() {
+        return INSTANCE;
+    }
+
+    public int getIndexForManifest(String manifest, Context context) {
+
+        if (mActivityList.size() == 0) {
+            loadActivityList(context);
+        }
+
+        int index = getManifestIndex(manifest);
+
+        // If we havent assigned this manifest an index then reassign the
+        // least recently used index
+        if (index == INVALID_INDEX) {
+            index = mActivityList.get(0).index;
+            final ActivityEntry newEntry = new ActivityEntry(index, manifest);
+            mActivityList.set(0, newEntry);
+        }
+
+        // Put the index at the back of the queue to be recycled
+        markActivityUsed(index, manifest, context);
+
+        return index;
+    }
+
+    private int getManifestIndex(String manifest) {
+        for (int i = mActivityList.size() - 1; i >= 0; i--) {
+            if (manifest.equals(mActivityList.get(i).manifest)) {
+                return mActivityList.get(i).index;
+            }
+        }
+        return INVALID_INDEX;
+    }
+
+    private void markActivityUsed(int index, String manifest, Context context) {
+        final int elementIndex = findActivityElement(index);
+        final ActivityEntry updatedEntry = new ActivityEntry(index, manifest);
+        mActivityList.remove(elementIndex);
+        mActivityList.add(updatedEntry);
+        storeActivityList(context);
+    }
+
+    private int findActivityElement(int index) {
+        for (int elementIndex = 0; elementIndex < mActivityList.size(); elementIndex++) {
+            if (mActivityList.get(elementIndex).index == index) {
+                return elementIndex;
+            }
+        }
+        return INVALID_INDEX;
+    }
+
+    // Store the list of assigned indexes in sharedPrefs because the LauncherActivity
+    // is likely to be killed and restarted between webapp launches
+    @UiThread
+    private void storeActivityList(Context context) {
+        final SharedPreferences prefs = GeckoSharedPrefs.forProfile(context);
+        final SharedPreferences.Editor editor = prefs.edit();
+        editor.clear();
+        editor.putInt(mPrefNumSavedEntries, mActivityList.size());
+        for (int i = 0; i < mActivityList.size(); ++i) {
+            editor.putInt(mPrefActivityIndex + i, mActivityList.get(i).index);
+            editor.putString(mPrefActivityId + i, mActivityList.get(i).manifest);
+        }
+        editor.apply();
+    }
+
+    @UiThread
+    private void loadActivityList(Context context) {
+        final SharedPreferences prefs = GeckoSharedPrefs.forProfile(context);
+        final int numSavedEntries = prefs.getInt(mPrefNumSavedEntries, 0);
+        for (int i = 0; i < numSavedEntries; ++i) {
+          int index = prefs.getInt(mPrefActivityIndex + i, i);
+          String manifest = prefs.getString(mPrefActivityId + i, null);
+          ActivityEntry entry = new ActivityEntry(index, manifest);
+          mActivityList.add(entry);
+        }
+
+        // Fill rest of the list with null spacers to be assigned
+        final int leftToFill = MAX_ACTIVITIES - mActivityList.size();
+        for (int i = 0; i < leftToFill; ++i) {
+            ActivityEntry entry = new ActivityEntry(i, null);
+            mActivityList.add(entry);
+        }
+    }
+}
new file mode 100644
--- /dev/null
+++ b/mobile/android/base/java/org/mozilla/gecko/webapps/WebApps.java
@@ -0,0 +1,25 @@
+/* -*- 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.webapps;
+
+/**
+ * 10 predefined slots for homescreen webapps, in LauncherActivity
+ * launched webapps will be given an index (via WebAppIndexer) that
+ * points to one of these class names
+ **/
+
+public final class WebApps {
+    public static class WebApp0 extends WebAppActivity { }
+    public static class WebApp1 extends WebAppActivity { }
+    public static class WebApp2 extends WebAppActivity { }
+    public static class WebApp3 extends WebAppActivity { }
+    public static class WebApp4 extends WebAppActivity { }
+    public static class WebApp5 extends WebAppActivity { }
+    public static class WebApp6 extends WebAppActivity { }
+    public static class WebApp7 extends WebAppActivity { }
+    public static class WebApp8 extends WebAppActivity { }
+    public static class WebApp9 extends WebAppActivity { }
+}
--- a/mobile/android/base/moz.build
+++ b/mobile/android/base/moz.build
@@ -787,16 +787,18 @@ gbjar.sources += ['java/org/mozilla/geck
     'updater/UpdateServiceHelper.java',
     'util/ColorUtil.java',
     'util/DrawableUtil.java',
     'util/JavaUtil.java',
     'util/ResourceDrawableUtils.java',
     'util/TouchTargetUtil.java',
     'util/ViewUtil.java',
     'webapps/WebAppActivity.java',
+    'webapps/WebAppIndexer.java',
+    'webapps/WebApps.java',
     'widget/ActivityChooserModel.java',
     'widget/AllCapsTextView.java',
     'widget/AnchoredPopup.java',
     'widget/AnimatedHeightLayout.java',
     'widget/BasicColorPicker.java',
     'widget/CheckableLinearLayout.java',
     'widget/ClickableWhenDisabledEditText.java',
     'widget/ContentSecurityDoorHanger.java',
--- a/modules/libpref/init/all.js
+++ b/modules/libpref/init/all.js
@@ -3274,22 +3274,22 @@ pref("ui.mouse.radius.visitedWeight", 12
 // When false, the prefs will be used for all mouse events.
 pref("ui.mouse.radius.inputSource.touchOnly", true);
 
 #ifdef XP_WIN
 
 pref("font.name.serif.ar", "Times New Roman");
 pref("font.name.sans-serif.ar", "Segoe UI");
 pref("font.name-list.sans-serif.ar", "Segoe UI, Tahoma, Arial");
-pref("font.name.monospace.ar", "Consolas");
+pref("font.name.monospace.ar", "Courier New");
 pref("font.name.cursive.ar", "Comic Sans MS");
 
 pref("font.name.serif.el", "Times New Roman");
 pref("font.name.sans-serif.el", "Arial");
-pref("font.name.monospace.el", "Consolas");
+pref("font.name.monospace.el", "Courier New");
 pref("font.name.cursive.el", "Comic Sans MS");
 
 pref("font.name.serif.he", "Narkisim");
 pref("font.name.sans-serif.he", "Arial");
 pref("font.name.monospace.he", "Fixed Miriam Transparent");
 pref("font.name.cursive.he", "Guttman Yad");
 pref("font.name-list.serif.he", "Narkisim, David");
 pref("font.name-list.monospace.he", "Fixed Miriam Transparent, Miriam Fixed, Rod, Courier New");
@@ -3314,27 +3314,27 @@ pref("font.name-list.cursive.ko", "Gungs
 
 pref("font.name.serif.th", "Tahoma");
 pref("font.name.sans-serif.th", "Tahoma");
 pref("font.name.monospace.th", "Tahoma");
 pref("font.name.cursive.th", "Tahoma");
 
 pref("font.name.serif.x-cyrillic", "Times New Roman");
 pref("font.name.sans-serif.x-cyrillic", "Arial");
-pref("font.name.monospace.x-cyrillic", "Consolas");
+pref("font.name.monospace.x-cyrillic", "Courier New");
 pref("font.name.cursive.x-cyrillic", "Comic Sans MS");
 
 pref("font.name.serif.x-unicode", "Times New Roman");
 pref("font.name.sans-serif.x-unicode", "Arial");
-pref("font.name.monospace.x-unicode", "Consolas");
+pref("font.name.monospace.x-unicode", "Courier New");
 pref("font.name.cursive.x-unicode", "Comic Sans MS");
 
 pref("font.name.serif.x-western", "Times New Roman");
 pref("font.name.sans-serif.x-western", "Arial");
-pref("font.name.monospace.x-western", "Consolas");
+pref("font.name.monospace.x-western", "Courier New");
 pref("font.name.cursive.x-western", "Comic Sans MS");
 
 pref("font.name.serif.zh-CN", "SimSun");
 pref("font.name.sans-serif.zh-CN", "Microsoft YaHei");
 pref("font.name.monospace.zh-CN", "SimSun");
 pref("font.name.cursive.zh-CN", "KaiTi");
 pref("font.name-list.serif.zh-CN", "MS Song, SimSun, SimSun-ExtB");
 pref("font.name-list.sans-serif.zh-CN", "Microsoft YaHei, SimHei");
@@ -3469,17 +3469,17 @@ pref("font.name-list.sans-serif.x-tibt",
 pref("font.name-list.monospace.x-tibt", "Tibetan Machine Uni, Jomolhari, Microsoft Himalaya");
 
 pref("font.minimum-size.th", 10);
 
 pref("font.default.x-devanagari", "sans-serif");
 pref("font.name.serif.x-math", "Latin Modern Math");
 pref("font.name-list.serif.x-math", "Latin Modern Math, STIX Two 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, Times New Roman");
 pref("font.name.sans-serif.x-math", "Arial");
-pref("font.name.monospace.x-math", "Consolas");
+pref("font.name.monospace.x-math", "Courier New");
 pref("font.name.cursive.x-math", "Comic Sans MS");
 
 // ClearType tuning parameters for directwrite/d2d.
 //
 // Allows overriding of underlying registry values in:
 //   HKCU/Software/Microsoft/Avalon.Graphics/<display> (contrast and level)
 //   HKLM/Software/Microsoft/Avalon.Graphics/<display> (gamma, pixel structure)
 // and selection of the ClearType/antialiasing mode.
deleted file mode 100644
--- a/security/sandbox/chromium-shim/base/MissingBasicTypes.h
+++ /dev/null
@@ -1,25 +0,0 @@
-/* -*- 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/. */
-
-#ifndef security_sandbox_MissingBasicTypes_h__
-#define security_sandbox_MissingBasicTypes_h__
-
-#include <stdint.h>
-
-// These types are still used by the Chromium sandbox code. When referencing
-// Chromium sandbox code from Gecko we can't use the normal base/basictypes.h as
-// it clashes with the one from ipc/chromium/src/base/. These types have been
-// removed from the one in ipc/chromium/src/base/.
-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;
-
-#endif  // security_sandbox_MissingBasicTypes_h__
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/debug/activity_tracker.h
@@ -0,0 +1,56 @@
+/* -*- 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/debug/activity_tracker.h.
+// To provide a class required in base/synchronization/lock_impl_win.cc
+// ScopedLockAcquireActivity. We don't use activity tracking.
+
+#ifndef BASE_DEBUG_ACTIVITY_TRACKER_H_
+#define BASE_DEBUG_ACTIVITY_TRACKER_H_
+
+#include "base/base_export.h"
+#include "base/compiler_specific.h"
+#include "base/macros.h"
+
+namespace base {
+class PlatformThreadHandle;
+class WaitableEvent;
+
+namespace internal {
+class LockImpl;
+}
+
+namespace debug {
+
+class BASE_EXPORT ScopedLockAcquireActivity
+{
+ public:
+  ALWAYS_INLINE
+  explicit ScopedLockAcquireActivity(const base::internal::LockImpl* lock) {}
+  DISALLOW_COPY_AND_ASSIGN(ScopedLockAcquireActivity);
+};
+
+class BASE_EXPORT ScopedEventWaitActivity
+{
+ public:
+  ALWAYS_INLINE
+  explicit ScopedEventWaitActivity(const base::WaitableEvent* event) {}
+  DISALLOW_COPY_AND_ASSIGN(ScopedEventWaitActivity);
+};
+
+class BASE_EXPORT ScopedThreadJoinActivity
+{
+ public:
+  ALWAYS_INLINE
+  explicit ScopedThreadJoinActivity(const base::PlatformThreadHandle* thread) {}
+  DISALLOW_COPY_AND_ASSIGN(ScopedThreadJoinActivity);
+};
+
+
+}  // namespace debug
+}  // namespace base
+
+#endif  // BASE_DEBUG_ACTIVITY_TRACKER_H_
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/debug/stack_trace.h
@@ -0,0 +1,24 @@
+/* -*- 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/debug/stack_trace.h.
+// To provide a dummy class StackTrace required in base/win/scoped_handle.cc.
+
+#ifndef BASE_DEBUG_STACK_TRACE_H_
+#define BASE_DEBUG_STACK_TRACE_H_
+
+namespace base {
+namespace debug {
+
+class BASE_EXPORT StackTrace {
+ public:
+  StackTrace() {};
+};
+
+}  // namespace debug
+}  // namespace base
+
+#endif  // BASE_DEBUG_STACK_TRACE_H_
--- a/security/sandbox/chromium-shim/base/file_version_info_win.h
+++ b/security/sandbox/chromium-shim/base/file_version_info_win.h
@@ -6,24 +6,26 @@
 
 // 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_
 
+#include "mozilla/Assertions.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; }
+    CreateFileVersionInfo(const base::FilePath& file_path) { MOZ_CRASH(); }
 
-  VS_FIXEDFILEINFO* fixed_file_info() { return nullptr; }
+  VS_FIXEDFILEINFO* fixed_file_info() { MOZ_CRASH(); }
 };
 
 #endif  // BASE_FILE_VERSION_INFO_WIN_H_
--- a/security/sandbox/chromium-shim/base/files/file_path.cpp
+++ b/security/sandbox/chromium-shim/base/files/file_path.cpp
@@ -3,17 +3,20 @@
 // 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"
 
+#include "mozilla/Assertions.h"
+
 namespace base {
 
 FilePath::FilePath(FilePath::StringPieceType path) {
+  MOZ_CRASH();
 }
 
 FilePath::~FilePath() {
 }
 
 } // namespace base
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/files/file_util.h
@@ -0,0 +1,11 @@
+/* -*- 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 cut down version of Chromium source file base/files/file_util.h
+// This is included in base/memory/shared_memory.h, but it only actually
+// requires the include for base/files/file_path.h.
+
+#include "base/files/file_path.h"
--- a/security/sandbox/chromium-shim/base/gtest_prod_util.h
+++ b/security/sandbox/chromium-shim/base/gtest_prod_util.h
@@ -1,17 +1,22 @@
 /* -*- 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/. */
 
+#ifndef BASE_GTEST_PROD_UTIL_H_
+#define BASE_GTEST_PROD_UTIL_H_
+
 #ifndef FRIEND_TEST
 #define FRIEND_TEST(A, B)
 #endif
 
 #ifndef FRIEND_TEST_ALL_PREFIXES
 #define FRIEND_TEST_ALL_PREFIXES(test_case_name, test_name)
 #endif
 
 #ifndef FORWARD_DECLARE_TEST
 #define FORWARD_DECLARE_TEST(test_case_name, test_name)
 #endif
+
+#endif  // BASE_GTEST_PROD_UTIL_H_
--- a/security/sandbox/chromium-shim/base/logging.cpp
+++ b/security/sandbox/chromium-shim/base/logging.cpp
@@ -23,16 +23,18 @@
 #endif
 
 #if defined(OS_WIN)
 #include "base/strings/utf_string_conversions.h"
 #endif
 
 #include <algorithm>
 
+#include "mozilla/Unused.h"
+
 namespace logging {
 
 namespace {
 
 int g_min_log_level = 0;
 
 LoggingDestination g_logging_destination = LOG_DEFAULT;
 
@@ -122,27 +124,29 @@ SystemErrorCode GetLastSystemErrorCode()
 
 #if defined(OS_WIN)
 Win32ErrorLogMessage::Win32ErrorLogMessage(const char* file,
                                            int line,
                                            LogSeverity severity,
                                            SystemErrorCode err)
     : err_(err),
       log_message_(file, line, severity) {
+  mozilla::Unused << err_;
 }
 
 Win32ErrorLogMessage::~Win32ErrorLogMessage() {
 }
 #elif defined(OS_POSIX)
 ErrnoLogMessage::ErrnoLogMessage(const char* file,
                                  int line,
                                  LogSeverity severity,
                                  SystemErrorCode err)
     : err_(err),
       log_message_(file, line, severity) {
+  mozilla::Unused << err_;
 }
 
 ErrnoLogMessage::~ErrnoLogMessage() {
 }
 #endif  // OS_WIN
 
 void RawLog(int level, const char* message) {
 }
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/metrics/histogram_macros.h
@@ -0,0 +1,18 @@
+/* -*- 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/metrics/histogram_macros.h.
+// To provide to histogram macros required in base/memory/shared_memory_win.cc
+// UMA_HISTOGRAM_ENUMERATION and UMA_HISTOGRAM_SPARSE_SLOWLY.
+// We don't require Chromiums histogram collection code.
+
+#ifndef BASE_METRICS_HISTOGRAM_MACROS_H_
+#define BASE_METRICS_HISTOGRAM_MACROS_H_
+
+#define UMA_HISTOGRAM_ENUMERATION(name, sample, enum_max) do { } while (0)
+#define UMA_HISTOGRAM_SPARSE_SLOWLY(name, sample) do { } while (0)
+
+#endif  // BASE_METRICS_HISTOGRAM_MACROS_H_
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/scoped_native_library.h
@@ -0,0 +1,31 @@
+/* -*- 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 cut down version of Chromium source file base/scoped_native_library.h
+// The chromium sandbox only requires ScopedNativeLibrary class to automatically
+// unload the library, which we can achieve with UniquePtr.
+
+#ifndef BASE_SCOPED_NATIVE_LIBRARY_H_
+#define BASE_SCOPED_NATIVE_LIBRARY_H_
+
+#include "mozilla/UniquePtr.h"
+
+namespace base {
+
+struct HModuleFreePolicy
+{
+  typedef HMODULE pointer;
+  void operator()(pointer hModule)
+  {
+    ::FreeLibrary(hModule);
+  }
+};
+
+typedef mozilla::UniquePtr<HMODULE, HModuleFreePolicy> ScopedNativeLibrary;
+
+} // namespace base
+
+#endif  // BASE_SCOPED_NATIVE_LIBRARY_H_
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/threading/platform_thread_linux.cpp
@@ -0,0 +1,64 @@
+/* -*- 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 cut down version of Chromium source file base/threading/platform_thread_linux.h
+// with only the functions required. It also has a dummy implementation of
+// SetCurrentThreadPriorityForPlatform, which should not be called.
+
+#include "base/threading/platform_thread.h"
+
+#include "base/threading/platform_thread_internal_posix.h"
+
+#include "mozilla/Assertions.h"
+
+namespace base {
+namespace internal {
+
+namespace {
+const struct sched_param kRealTimePrio = {8};
+}  // namespace
+
+const ThreadPriorityToNiceValuePair kThreadPriorityToNiceValueMap[4] = {
+    {ThreadPriority::BACKGROUND, 10},
+    {ThreadPriority::NORMAL, 0},
+    {ThreadPriority::DISPLAY, -8},
+    {ThreadPriority::REALTIME_AUDIO, -10},
+};
+
+bool SetCurrentThreadPriorityForPlatform(ThreadPriority priority) {
+  MOZ_CRASH();
+}
+
+bool GetCurrentThreadPriorityForPlatform(ThreadPriority* priority) {
+  int maybe_sched_rr = 0;
+  struct sched_param maybe_realtime_prio = {0};
+  if (pthread_getschedparam(pthread_self(), &maybe_sched_rr,
+                            &maybe_realtime_prio) == 0 &&
+      maybe_sched_rr == SCHED_RR &&
+      maybe_realtime_prio.sched_priority == kRealTimePrio.sched_priority) {
+    *priority = ThreadPriority::REALTIME_AUDIO;
+    return true;
+  }
+  return false;
+}
+
+}  // namespace internal
+
+void InitThreading() {}
+
+void TerminateOnThread() {}
+
+size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes) {
+#if !defined(THREAD_SANITIZER)
+  return 0;
+#else
+  // ThreadSanitizer bloats the stack heavily. Evidence has been that the
+  // default stack size isn't enough for some browser tests.
+  return 2 * (1 << 23);  // 2 times 8192K (the default stack size on Linux).
+#endif
+}
+
+}  // namespace base
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/trace_event/heap_profiler_allocation_context_tracker.h
@@ -0,0 +1,32 @@
+/* -*- 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/trace_event/heap_profiler_allocation_context_tracker.h.
+// To provide a function required in base/threading/thread_id_name_manager.cc
+// SetCurrentThreadName. We don't use the heap profiler.
+
+#ifndef BASE_TRACE_EVENT_HEAP_PROFILER_ALLOCATION_CONTEXT_TRACKER_H_
+#define BASE_TRACE_EVENT_HEAP_PROFILER_ALLOCATION_CONTEXT_TRACKER_H_
+
+namespace base {
+namespace trace_event {
+
+// The allocation context tracker keeps track of thread-local context for heap
+// profiling. It includes a pseudo stack of trace events. On every allocation
+// the tracker provides a snapshot of its context in the form of an
+// |AllocationContext| that is to be stored together with the allocation
+// details.
+class BASE_EXPORT AllocationContextTracker {
+ public:
+  static void SetCurrentThreadName(const char* name) {}
+
+  DISALLOW_COPY_AND_ASSIGN(AllocationContextTracker);
+};
+
+}  // namespace trace_event
+}  // namespace base
+
+#endif  // BASE_TRACE_EVENT_HEAP_PROFILER_ALLOCATION_CONTEXT_TRACKER_H_
--- a/security/sandbox/chromium-shim/base/tracked_objects.h
+++ b/security/sandbox/chromium-shim/base/tracked_objects.h
@@ -1,19 +1,23 @@
 /* -*- 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/. */
 
 #ifndef _SECURITY_SANDBOX_TRACKED_OBJECTS_H_
 #define _SECURITY_SANDBOX_TRACKED_OBJECTS_H_
+
+#include "mozilla/Assertions.h"
+
 namespace tracked_objects
 {
   class ThreadData
   {
   public:
     static void InitializeThreadContext(const std::string& name)
     {
+      MOZ_CRASH();
     }
   };
 }
 #endif
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/win/base_features.h
@@ -0,0 +1,17 @@
+/* -*- 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 dummy version of a file that is generated by the chromium build
+// from base/win/BUILD.gn.
+
+#ifndef BASE_WIN_BASE_FEATURES_H_
+#define BASE_WIN_BASE_FEATURES_H_
+
+#include "build/buildflag.h"
+
+#define BUILDFLAG_INTERNAL_SINGLE_MODULE_MODE_HANDLE_VERIFIER() (false)
+
+#endif  // BASE_WIN_BASE_FEATURES_H_
--- a/security/sandbox/chromium-shim/base/win/registry.h
+++ b/security/sandbox/chromium-shim/base/win/registry.h
@@ -2,31 +2,45 @@
 /* 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 stripped down version of Chromium source file base/win/registry.h
 // Within our copy of Chromium files this is only used in base/win/windows_version.cc
 // in OSInfo::processor_model_name, which we don't use.
+// It is also used in GetUBR, which is used as the VersionNumber.patch, which
+// again is not needed by the sandbox.
 
 #ifndef BASE_WIN_REGISTRY_H_
 #define BASE_WIN_REGISTRY_H_
 
+#include <winerror.h>
+
 namespace base {
 namespace win {
 
 class BASE_EXPORT RegKey {
  public:
+  RegKey() {};
   RegKey(HKEY rootkey, const wchar_t* subkey, REGSAM access) {}
   ~RegKey() {}
 
+  LONG Open(HKEY rootkey, const wchar_t* subkey, REGSAM access) {
+    return ERROR_CANTOPEN;
+  }
+
+  LONG ReadValueDW(const wchar_t* name, DWORD* out_value) const
+  {
+    return ERROR_CANTREAD;
+  }
+
   LONG ReadValue(const wchar_t* name, std::wstring* out_value) const
   {
-    return 0;
+    return ERROR_CANTREAD;
   }
 
  private:
   DISALLOW_COPY_AND_ASSIGN(RegKey);
 };
 
 }  // namespace win
 }  // namespace base
--- a/security/sandbox/chromium-shim/base/win/sdkdecls.h
+++ b/security/sandbox/chromium-shim/base/win/sdkdecls.h
@@ -183,9 +183,63 @@ typedef struct _PROCESS_MITIGATION_EXTEN
       DWORD DisableExtensionPoints : 1;
       DWORD ReservedFlags : 31;
     };
   };
 } PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY, *PPROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY;
 
 #endif // NTDDI_WIN8
 #endif // (_WIN32_WINNT < 0x0602)
+
+#if (_WIN32_WINNT < 0x0A00)
+//
+// Define Font Disable Policy.  When enabled, this option will
+// block loading Non System Fonts.
+//
+
+#define PROCESS_CREATION_MITIGATION_POLICY_FONT_DISABLE_MASK                              (0x00000003ui64 << 48)
+#define PROCESS_CREATION_MITIGATION_POLICY_FONT_DISABLE_DEFER                             (0x00000000ui64 << 48)
+#define PROCESS_CREATION_MITIGATION_POLICY_FONT_DISABLE_ALWAYS_ON                         (0x00000001ui64 << 48)
+#define PROCESS_CREATION_MITIGATION_POLICY_FONT_DISABLE_ALWAYS_OFF                        (0x00000002ui64 << 48)
+#define PROCESS_CREATION_MITIGATION_POLICY_AUDIT_NONSYSTEM_FONTS                          (0x00000003ui64 << 48)
+
+//
+// Define remote image load options.  When enabled, this option will
+// block mapping of images from remote devices.
+//
+
+#define PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_REMOTE_MASK                      (0x00000003ui64 << 52)
+#define PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_REMOTE_DEFER                     (0x00000000ui64 << 52)
+#define PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_REMOTE_ALWAYS_ON                 (0x00000001ui64 << 52)
+#define PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_REMOTE_ALWAYS_OFF                (0x00000002ui64 << 52)
+#define PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_REMOTE_RESERVED                  (0x00000003ui64 << 52)
+
+//
+// Define low IL image load options.  When enabled, this option will
+// block mapping of images that have the low mandatory label.
+//
+
+#define PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_LOW_LABEL_MASK                   (0x00000003ui64 << 56)
+#define PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_LOW_LABEL_DEFER                  (0x00000000ui64 << 56)
+#define PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_LOW_LABEL_ALWAYS_ON              (0x00000001ui64 << 56)
+#define PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_LOW_LABEL_ALWAYS_OFF             (0x00000002ui64 << 56)
+#define PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_NO_LOW_LABEL_RESERVED               (0x00000003ui64 << 56)
+
+//
+// Define Attribute to disable creation of child process
+//
+
+#define PROCESS_CREATION_CHILD_PROCESS_RESTRICTED                                         0x01
+#define PROCESS_CREATION_CHILD_PROCESS_OVERRIDE                                           0x02
+
+//
+// Define Attribute for Desktop Appx Overide. 
+//
+
+#define PROCESS_CREATION_DESKTOP_APPX_OVERRIDE                                            0x04
+
+#define ProcThreadAttributeChildProcessPolicy 14
+
+#define PROC_THREAD_ATTRIBUTE_CHILD_PROCESS_POLICY \
+    ProcThreadAttributeValue (ProcThreadAttributeChildProcessPolicy, FALSE, TRUE, FALSE)
+
+#endif // (_WIN32_WINNT >= 0x0A00)
 #endif // _SECURITY_SANDBOX_BASE_SHIM_SDKDECLS_H_
--- a/security/sandbox/chromium/base/at_exit.cc
+++ b/security/sandbox/chromium/base/at_exit.cc
@@ -1,32 +1,34 @@
 // 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.
 
 #include "base/at_exit.h"
 
 #include <stddef.h>
 #include <ostream>
+#include <utility>
 
 #include "base/bind.h"
 #include "base/callback.h"
 #include "base/logging.h"
 
 namespace base {
 
 // Keep a stack of registered AtExitManagers.  We always operate on the most
 // recent, and we should never have more than one outside of testing (for a
 // statically linked version of this library).  Testing may use the shadow
 // version of the constructor, and if we are building a dynamic library we may
 // end up with multiple AtExitManagers on the same process.  We don't protect
 // this for thread-safe access, since it will only be modified in testing.
 static AtExitManager* g_top_manager = NULL;
 
-AtExitManager::AtExitManager() : next_manager_(g_top_manager) {
+AtExitManager::AtExitManager()
+    : processing_callbacks_(false), next_manager_(g_top_manager) {
 // If multiple modules instantiate AtExitManagers they'll end up living in this
 // module... they have to coexist.
 #if !defined(COMPONENT_BUILD)
   DCHECK(!g_top_manager);
 #endif
   g_top_manager = this;
 }
 
@@ -50,33 +52,46 @@ void AtExitManager::RegisterCallback(AtE
 // static
 void AtExitManager::RegisterTask(base::Closure task) {
   if (!g_top_manager) {
     NOTREACHED() << "Tried to RegisterCallback without an AtExitManager";
     return;
   }
 
   AutoLock lock(g_top_manager->lock_);
-  g_top_manager->stack_.push(task);
+  DCHECK(!g_top_manager->processing_callbacks_);
+  g_top_manager->stack_.push(std::move(task));
 }
 
 // static
 void AtExitManager::ProcessCallbacksNow() {
   if (!g_top_manager) {
     NOTREACHED() << "Tried to ProcessCallbacksNow without an AtExitManager";
     return;
   }
 
-  AutoLock lock(g_top_manager->lock_);
+  // Callbacks may try to add new callbacks, so run them without holding
+  // |lock_|. This is an error and caught by the DCHECK in RegisterTask(), but
+  // handle it gracefully in release builds so we don't deadlock.
+  std::stack<base::Closure> tasks;
+  {
+    AutoLock lock(g_top_manager->lock_);
+    tasks.swap(g_top_manager->stack_);
+    g_top_manager->processing_callbacks_ = true;
+  }
 
-  while (!g_top_manager->stack_.empty()) {
-    base::Closure task = g_top_manager->stack_.top();
+  while (!tasks.empty()) {
+    base::Closure task = tasks.top();
     task.Run();
-    g_top_manager->stack_.pop();
+    tasks.pop();
   }
+
+  // Expect that all callbacks have been run.
+  DCHECK(g_top_manager->stack_.empty());
 }
 
-AtExitManager::AtExitManager(bool shadow) : next_manager_(g_top_manager) {
+AtExitManager::AtExitManager(bool shadow)
+    : processing_callbacks_(false), next_manager_(g_top_manager) {
   DCHECK(shadow || !g_top_manager);
   g_top_manager = this;
 }
 
 }  // namespace base
--- a/security/sandbox/chromium/base/at_exit.h
+++ b/security/sandbox/chromium/base/at_exit.h
@@ -54,16 +54,17 @@ class BASE_EXPORT AtExitManager {
   // even if one already exists.  This should only be used for testing!
   // AtExitManagers are kept on a global stack, and it will be removed during
   // destruction.  This allows you to shadow another AtExitManager.
   explicit AtExitManager(bool shadow);
 
  private:
   base::Lock lock_;
   std::stack<base::Closure> stack_;
+  bool processing_callbacks_;
   AtExitManager* next_manager_;  // Stack of managers to allow shadowing.
 
   DISALLOW_COPY_AND_ASSIGN(AtExitManager);
 };
 
 #if defined(UNIT_TEST)
 class ShadowingAtExitManager : public AtExitManager {
  public:
--- a/security/sandbox/chromium/base/atomic_ref_count.h
+++ b/security/sandbox/chromium/base/atomic_ref_count.h
@@ -7,17 +7,17 @@
 
 #ifndef BASE_ATOMIC_REF_COUNT_H_
 #define BASE_ATOMIC_REF_COUNT_H_
 
 #include "base/atomicops.h"
 
 namespace base {
 
-typedef subtle::Atomic32 AtomicRefCount;
+typedef subtle::AtomicWord AtomicRefCount;
 
 // Increment a reference count by "increment", which must exceed 0.
 inline void AtomicRefCountIncN(volatile AtomicRefCount *ptr,
                                AtomicRefCount increment) {
   subtle::NoBarrier_AtomicIncrement(ptr, increment);
 }
 
 // Decrement a reference count by "decrement", which must exceed 0,
--- a/security/sandbox/chromium/base/base_paths.h
+++ b/security/sandbox/chromium/base/base_paths.h
@@ -27,19 +27,18 @@ namespace base {
 enum BasePathKey {
   PATH_START = 0,
 
   DIR_CURRENT,       // Current directory.
   DIR_EXE,           // Directory containing FILE_EXE.
   DIR_MODULE,        // Directory containing FILE_MODULE.
   DIR_TEMP,          // Temporary directory.
   DIR_HOME,          // User's root home directory. On Windows this will look
-                     // like "C:\Users\you" (or on XP
-                     // "C:\Document and Settings\you") which isn't necessarily
-                     // a great place to put files.
+                     // like "C:\Users\<user>"  which isn't necessarily a great
+                     // place to put files.
   FILE_EXE,          // Path and filename of the current executable.
   FILE_MODULE,       // Path and filename of the module containing the code for
                      // the PathService (which could differ from FILE_EXE if the
                      // PathService were compiled into a shared object, for
                      // example).
   DIR_SOURCE_ROOT,   // Returns the root of the source tree. This key is useful
                      // for tests that need to locate various resources. It
                      // should not be used outside of test code.
--- a/security/sandbox/chromium/base/base_paths_win.h
+++ b/security/sandbox/chromium/base/base_paths_win.h
@@ -20,35 +20,34 @@ enum {
   // 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
-                          // the user profile.
-  DIR_COMMON_APP_DATA,    // W2K, XP, W2K3: "C:\Documents and Settings\
-                          // 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
-                          // (Win7-8) via base::win::PinShortcutToTaskbar().
-  DIR_WINDOWS_FONTS,      // Usually C:\Windows\Fonts.
+  DIR_IE_INTERNET_CACHE,       // Temporary Internet Files directory.
+  DIR_COMMON_START_MENU,       // Usually "C:\ProgramData\Microsoft\Windows\
+                               // Start Menu\Programs"
+  DIR_START_MENU,              // Usually "C:\Users\<user>\AppData\Roaming\
+                               // Microsoft\Windows\Start Menu\Programs"
+  DIR_APP_DATA,                // Application Data directory under the user
+                               // profile.
+  DIR_LOCAL_APP_DATA,          // "Local Settings\Application Data" directory
+                               // under the user profile.
+  DIR_COMMON_APP_DATA,         // Usually "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.
+  DIR_IMPLICIT_APP_SHORTCUTS,  // The implicit user pinned shortcut directory.
+  DIR_WINDOWS_FONTS,           // Usually C:\Windows\Fonts.
 
   PATH_WIN_END
 };
 
 }  // namespace base
 
 #endif  // BASE_BASE_PATHS_WIN_H_
--- a/security/sandbox/chromium/base/base_switches.cc
+++ b/security/sandbox/chromium/base/base_switches.cc
@@ -15,16 +15,20 @@ const char kDisableBreakpad[]           
 // 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";
 
+// Report native (walk the stack) allocation traces. By default pseudo stacks
+// derived from trace events are reported.
+const char kEnableHeapProfilingModeNative[] = "native";
+
 // Generates full memory crash dump.
 const char kFullMemoryCrashReport[]         = "full-memory-crash-report";
 
 // 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";
@@ -41,16 +45,21 @@ const char kForceFieldTrials[]          
 
 // 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";
 
+// When running certain tests that spawn child processes, this switch indicates
+// to the test framework that the current process should not initialize ICU to
+// avoid creating any scoped handles too early in startup.
+const char kTestDoNotInitializeIcu[]        = "test-do-not-initialize-icu";
+
 // Gives the default maximal active V-logging level; 0 is the default.
 // Normally positive values are used for V-logging levels.
 const char kV[]                             = "v";
 
 // Gives the per-module maximal V-logging levels to override the value
 // given by --v.  E.g. "my_module=2,foo*=3" would change the logging
 // level for all code in source files "my_module.*" and "foo*.*"
 // ("-inl" suffixes are also disregarded for this matching).
@@ -75,16 +84,26 @@ const char kTraceToFileName[]           
 // 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";
 
+// Specifies a location for profiling output. This will only work if chrome has
+// been built with the gyp variable profiling=1 or gn arg enable_profiling=true.
+//
+//   {pid} if present will be replaced by the pid of the process.
+//   {count} if present will be incremented each time a profile is generated
+//           for this process.
+// The default is chrome-profile-{pid} for the browser and test-profile-{pid}
+// for tests.
+const char kProfilingFile[] = "profiling-file";
+
 #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.
--- a/security/sandbox/chromium/base/base_switches.h
+++ b/security/sandbox/chromium/base/base_switches.h
@@ -10,23 +10,26 @@
 #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 kEnableHeapProfilingModeNative[];
 extern const char kEnableLowEndDeviceMode[];
 extern const char kForceFieldTrials[];
 extern const char kFullMemoryCrashReport[];
 extern const char kNoErrorDialogs[];
 extern const char kProfilerTiming[];
 extern const char kProfilerTimingDisabledValue[];
+extern const char kProfilingFile[];
 extern const char kTestChildProcess[];
+extern const char kTestDoNotInitializeIcu[];
 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[];
--- a/security/sandbox/chromium/base/bind.h
+++ b/security/sandbox/chromium/base/bind.h
@@ -1,101 +1,83 @@
 // 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"
-#include "base/callback_internal.h"
 
 // -----------------------------------------------------------------------------
 // Usage documentation
 // -----------------------------------------------------------------------------
 //
-// See base/callback.h for documentation.
+// See //docs/callback.md for documentation.
 //
 //
 // -----------------------------------------------------------------------------
 // Implementation notes
 // -----------------------------------------------------------------------------
 //
 // If you're reading the implementation, before proceeding further, you should
 // read the top comment of base/bind_internal.h for a definition of common
 // terms and concepts.
-//
-// RETURN TYPES
-//
-// Though Bind()'s result is meant to be stored in a Callback<> type, it
-// cannot actually return the exact type without requiring a large amount
-// of extra template specializations. The problem is that in order to
-// discern the correct specialization of Callback<>, Bind would need to
-// unwrap the function signature to determine the signature's arity, and
-// whether or not it is a method.
-//
-// Each unique combination of (arity, function_type, num_prebound) where
-// 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 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 {
 
+// Bind as OnceCallback.
 template <typename Functor, typename... Args>
-base::Callback<
-    typename internal::BindState<
-        typename internal::FunctorTraits<Functor>::RunnableType,
-        typename internal::FunctorTraits<Functor>::RunType,
-        typename internal::CallbackParamTraits<Args>::StorageType...>
-            ::UnboundRunType>
-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;
+inline OnceCallback<MakeUnboundRunType<Functor, Args...>>
+BindOnce(Functor&& functor, Args&&... args) {
+  using BindState = internal::MakeBindStateType<Functor, Args...>;
+  using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
+  using Invoker = internal::Invoker<BindState, UnboundRunType>;
+  using CallbackType = OnceCallback<UnboundRunType>;
 
-  // Use RunnableType::RunType instead of RunType above because our
-  // checks below for bound references need to know what the actual
-  // functor is going to interpret the argument as.
-  using BoundRunType = typename RunnableType::RunType;
+  // Store the invoke func into PolymorphicInvoke before casting it to
+  // InvokeFuncStorage, so that we can ensure its type matches to
+  // PolymorphicInvoke, to which CallbackType will cast back.
+  using PolymorphicInvoke = typename CallbackType::PolymorphicInvoke;
+  PolymorphicInvoke invoke_func = &Invoker::RunOnce;
 
-  using BoundArgs =
-      internal::TakeTypeListItem<sizeof...(Args),
-                                 internal::ExtractArgs<BoundRunType>>;
+  using InvokeFuncStorage = internal::BindStateBase::InvokeFuncStorage;
+  return CallbackType(new BindState(
+      reinterpret_cast<InvokeFuncStorage>(invoke_func),
+      std::forward<Functor>(functor),
+      std::forward<Args>(args)...));
+}
 
-  // 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.
-  static_assert(!internal::HasNonConstReferenceItem<BoundArgs>::value,
-                "do not bind functions with nonconst ref");
+// Bind as RepeatingCallback.
+template <typename Functor, typename... Args>
+inline RepeatingCallback<MakeUnboundRunType<Functor, Args...>>
+BindRepeating(Functor&& functor, Args&&... args) {
+  using BindState = internal::MakeBindStateType<Functor, Args...>;
+  using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
+  using Invoker = internal::Invoker<BindState, UnboundRunType>;
+  using CallbackType = RepeatingCallback<UnboundRunType>;
 
-  const bool is_method = internal::HasIsMethodTag<RunnableType>::value;
+  // Store the invoke func into PolymorphicInvoke before casting it to
+  // InvokeFuncStorage, so that we can ensure its type matches to
+  // PolymorphicInvoke, to which CallbackType will cast back.
+  using PolymorphicInvoke = typename CallbackType::PolymorphicInvoke;
+  PolymorphicInvoke invoke_func = &Invoker::Run;
 
-  // 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.
-  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 InvokeFuncStorage = internal::BindStateBase::InvokeFuncStorage;
+  return CallbackType(new BindState(
+      reinterpret_cast<InvokeFuncStorage>(invoke_func),
+      std::forward<Functor>(functor),
+      std::forward<Args>(args)...));
+}
 
-  using BindState = internal::BindState<
-      RunnableType, RunType,
-      typename internal::CallbackParamTraits<Args>::StorageType...>;
-
-  return Callback<typename BindState::UnboundRunType>(
-      new BindState(internal::MakeRunnable(functor), args...));
+// Unannotated Bind.
+// TODO(tzik): Deprecate this and migrate to OnceCallback and
+// RepeatingCallback, once they get ready.
+template <typename Functor, typename... Args>
+inline Callback<MakeUnboundRunType<Functor, Args...>>
+Bind(Functor&& functor, Args&&... args) {
+  return BindRepeating(std::forward<Functor>(functor),
+                       std::forward<Args>(args)...);
 }
 
 }  // namespace base
 
 #endif  // BASE_BIND_H_
--- a/security/sandbox/chromium/base/bind_helpers.h
+++ b/security/sandbox/chromium/base/bind_helpers.h
@@ -23,16 +23,19 @@
 //
 // Passed() is for transferring movable-but-not-copyable types (eg. scoped_ptr)
 // through a Callback. Logically, this signifies a destructive transfer of
 // the state of the argument into the target function.  Invoking
 // Callback::Run() twice on a Callback that was created with a Passed()
 // argument will CHECK() because the first invocation would have already
 // transferred ownership to the target function.
 //
+// RetainedRef() accepts a ref counted object and retains a reference to it.
+// When the callback is called, the object is passed as a raw pointer.
+//
 // ConstRef() allows binding a constant reference to an argument rather
 // than a copy.
 //
 // IgnoreResult() is used to adapt a function or Callback with a return type to
 // one with a void return. This is most useful if you have a function with,
 // say, a pesky ignorable bool return that you want to use with PostTask or
 // something else that expect a Callback with a void return.
 //
@@ -66,16 +69,29 @@
 //   foo_callback.Run();  // Prints "2"
 //
 //   foo_callback.Reset();  // |pn| is deleted.  Also will happen when
 //                          // |foo_callback| goes out of scope.
 //
 // Without Owned(), someone would have to know to delete |pn| when the last
 // reference to the Callback is deleted.
 //
+// EXAMPLE OF RetainedRef():
+//
+//    void foo(RefCountedBytes* bytes) {}
+//
+//    scoped_refptr<RefCountedBytes> bytes = ...;
+//    Closure callback = Bind(&foo, base::RetainedRef(bytes));
+//    callback.Run();
+//
+// Without RetainedRef, the scoped_refptr would try to implicitly convert to
+// a raw pointer and fail compilation:
+//
+//    Closure callback = Bind(&foo, bytes); // ERROR!
+//
 //
 // EXAMPLE OF ConstRef():
 //
 //   void foo(int arg) { cout << arg << endl }
 //
 //   int n = 1;
 //   Closure no_ref = Bind(&foo, n);
 //   Closure has_ref = Bind(&foo, ConstRef(n));
@@ -100,20 +116,21 @@
 //   cb->Run(1);  // Prints "1".
 //
 //   // Prints "1" on |ml|.
 //   ml->PostTask(FROM_HERE, Bind(IgnoreResult(&DoSomething), 1);
 //
 //
 // EXAMPLE OF Passed():
 //
-//   void TakesOwnership(scoped_ptr<Foo> arg) { }
-//   scoped_ptr<Foo> CreateFoo() { return scoped_ptr<Foo>(new Foo()); }
+//   void TakesOwnership(std::unique_ptr<Foo> arg) { }
+//   std::unique_ptr<Foo> CreateFoo() { return std::unique_ptr<Foo>(new Foo());
+//   }
 //
-//   scoped_ptr<Foo> f(new Foo());
+//   std::unique_ptr<Foo> f(new Foo());
 //
 //   // |cb| is given ownership of Foo(). |f| is now NULL.
 //   // 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();
@@ -145,159 +162,27 @@
 
 #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.
-//
-// http://en.wikipedia.org/wiki/Substitution_failure_is_not_an_error
-// http://stackoverflow.com/questions/257288/is-it-possible-to-write-a-c-template-to-check-for-a-functions-existence
-// http://stackoverflow.com/questions/4358584/sfinae-approach-comparison
-// http://stackoverflow.com/questions/1966362/sfinae-to-check-for-inherited-member-functions
-//
-// The last link in particular show the method used below.
-//
-// For SFINAE to work with inherited methods, we need to pull some extra tricks
-// with multiple inheritance.  In the more standard formulation, the overloads
-// of Check would be:
-//
-//   template <typename C>
-//   Yes NotTheCheckWeWant(Helper<&C::TargetFunc>*);
-//
-//   template <typename C>
-//   No NotTheCheckWeWant(...);
-//
-//   static const bool value = sizeof(NotTheCheckWeWant<T>(0)) == sizeof(Yes);
-//
-// The problem here is that template resolution will not match
-// C::TargetFunc if TargetFunc does not exist directly in C.  That is, if
-// TargetFunc in inherited from an ancestor, &C::TargetFunc will not match,
-// |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().
-//
-// 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>*);
-//
-//   template <typename C>
-//   Yes GoodCheck(...);
-//
-//   static const bool value = sizeof(GoodCheck<Base>(0)) == sizeof(Yes);
-//
-// Notice here that the variadic version of GoodCheck() returns Yes here
-// instead of No like the previous one. Also notice that we calculate |value|
-// by specializing GoodCheck() on Base instead of T.
-//
-// We've reversed the roles of the variadic, and Helper overloads.
-// GoodCheck(Helper<&C::TargetFunc>*), when C = Base, fails to be a valid
-// substitution if T::TargetFunc exists. Thus GoodCheck<Base>(0) will resolve
-// to the variadic version if T has TargetFunc.  If T::TargetFunc does not
-// exist, then &C::TargetFunc is not ambiguous, and the overload resolution
-// will prefer GoodCheck(Helper<&C::TargetFunc>*).
-//
-// This method of SFINAE will correctly probe for inherited names, but it cannot
-// typecheck those names.  It's still a good enough sanity check though.
-//
-// Works on gcc-4.2, gcc-4.4, and Visual Studio 2008.
-//
-// 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 {
-  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.
-#if defined(OS_WIN)
-#pragma warning(push)
-#pragma warning(disable:4624)
-#endif
-  struct Base : public T, public BaseMixin {
-  };
-#if defined(OS_WIN)
-#pragma warning(pop)
-#endif
-
-  template <void(BaseMixin::*)()> struct Helper {};
-
-  template <typename C>
-  static No& Check(Helper<&C::AddRef>*);
-
-  template <typename >
-  static Yes& Check(...);
-
- public:
-  enum { value = sizeof(Check<Base>(0)) == sizeof(Yes) };
-};
-
-// Helpers to assert that arguments of a recounted type are bound with a
-// scoped_refptr.
-template <bool IsClasstype, typename T>
-struct UnsafeBindtoRefCountedArgHelper : false_type {
-};
 
 template <typename T>
-struct UnsafeBindtoRefCountedArgHelper<true, T>
-    : integral_constant<bool, SupportsAddRefAndRelease<T>::value> {
-};
-
-template <typename T>
-struct UnsafeBindtoRefCountedArg : false_type {
-};
-
-template <typename T>
-struct UnsafeBindtoRefCountedArg<T*>
-    : UnsafeBindtoRefCountedArgHelper<is_class<T>::value, T> {
-};
+struct IsWeakReceiver;
 
-template <typename T>
-class HasIsMethodTag {
-  using Yes = char[1];
-  using No = char[2];
+template <typename>
+struct BindUnwrapTraits;
 
-  template <typename U>
-  static Yes& Check(typename U::IsMethod*);
-
-  template <typename U>
-  static No& Check(...);
-
- public:
-  enum { value = sizeof(Check<T>(0)) == sizeof(Yes) };
-};
+namespace internal {
 
 template <typename T>
 class UnretainedWrapper {
  public:
   explicit UnretainedWrapper(T* o) : ptr_(o) {}
   T* get() const { return ptr_; }
  private:
   T* ptr_;
@@ -308,43 +193,47 @@ class ConstRefWrapper {
  public:
   explicit ConstRefWrapper(const T& o) : ptr_(&o) {}
   const T& get() const { return *ptr_; }
  private:
   const T* ptr_;
 };
 
 template <typename T>
+class RetainedRefWrapper {
+ public:
+  explicit RetainedRefWrapper(T* o) : ptr_(o) {}
+  explicit RetainedRefWrapper(scoped_refptr<T> o) : ptr_(std::move(o)) {}
+  T* get() const { return ptr_.get(); }
+ private:
+  scoped_refptr<T> ptr_;
+};
+
+template <typename T>
 struct IgnoreResultHelper {
-  explicit IgnoreResultHelper(T functor) : functor_(functor) {}
+  explicit IgnoreResultHelper(T functor) : functor_(std::move(functor)) {}
+  explicit operator bool() const { return !!functor_; }
 
   T functor_;
 };
 
-template <typename T>
-struct IgnoreResultHelper<Callback<T> > {
-  explicit IgnoreResultHelper(const Callback<T>& functor) : functor_(functor) {}
-
-  const Callback<T>& functor_;
-};
-
 // An alternate implementation is to avoid the destructive copy, and instead
 // specialize ParamTraits<> for OwnedWrapper<> to change the StorageType to
-// a class that is essentially a scoped_ptr<>.
+// a class that is essentially a std::unique_ptr<>.
 //
 // The current implementation has the benefit though of leaving ParamTraits<>
 // fully in callback_internal.h as well as avoiding type conversions during
 // storage.
 template <typename T>
 class OwnedWrapper {
  public:
   explicit OwnedWrapper(T* o) : ptr_(o) {}
   ~OwnedWrapper() { delete ptr_; }
   T* get() const { return ptr_; }
-  OwnedWrapper(const OwnedWrapper& other) {
+  OwnedWrapper(OwnedWrapper&& other) {
     ptr_ = other.ptr_;
     other.ptr_ = NULL;
   }
 
  private:
   mutable T* ptr_;
 };
 
@@ -371,141 +260,49 @@ class OwnedWrapper {
 //     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_(std::move(scoper)) {}
-  PassedWrapper(const PassedWrapper& other)
+  PassedWrapper(PassedWrapper&& other)
       : is_valid_(other.is_valid_), scoper_(std::move(other.scoper_)) {}
-  T Pass() const {
+  T Take() const {
     CHECK(is_valid_);
     is_valid_ = false;
     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 {
-  using ForwardType = const T&;
-  static ForwardType Unwrap(const T& o) { return o; }
-};
-
-template <typename T>
-struct UnwrapTraits<UnretainedWrapper<T> > {
-  using ForwardType = T*;
-  static ForwardType Unwrap(UnretainedWrapper<T> unretained) {
-    return unretained.get();
-  }
-};
-
-template <typename T>
-struct UnwrapTraits<ConstRefWrapper<T> > {
-  using ForwardType = const T&;
-  static ForwardType Unwrap(ConstRefWrapper<T> const_ref) {
-    return const_ref.get();
-  }
-};
-
-template <typename T>
-struct UnwrapTraits<scoped_refptr<T> > {
-  using ForwardType = T*;
-  static ForwardType Unwrap(const scoped_refptr<T>& o) { return o.get(); }
-};
-
-template <typename T>
-struct UnwrapTraits<WeakPtr<T> > {
-  using ForwardType = const WeakPtr<T>&;
-  static ForwardType Unwrap(const WeakPtr<T>& o) { return o; }
-};
-
-template <typename T>
-struct UnwrapTraits<OwnedWrapper<T> > {
-  using ForwardType = T*;
-  static ForwardType Unwrap(const OwnedWrapper<T>& o) {
-    return o.get();
-  }
-};
+using Unwrapper = BindUnwrapTraits<typename std::decay<T>::type>;
 
 template <typename T>
-struct UnwrapTraits<PassedWrapper<T> > {
-  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 MaybeScopedRefPtr;
-
-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, typename... Rest>
-struct MaybeScopedRefPtr<false, T[n], Rest...> {
-  MaybeScopedRefPtr(const T*, const Rest&...) {}
-};
-
-template <typename T, typename... Rest>
-struct MaybeScopedRefPtr<true, T, Rest...> {
-  MaybeScopedRefPtr(const T& o, const Rest&...) {}
-};
-
-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, typename... Rest>
-struct MaybeScopedRefPtr<true, scoped_refptr<T>, Rest...> {
-  MaybeScopedRefPtr(const scoped_refptr<T>&, const Rest&...) {}
-};
-
-template <typename T, typename... Rest>
-struct MaybeScopedRefPtr<true, const T*, Rest...> {
-  MaybeScopedRefPtr(const T* o, const Rest&...) : ref_(o) {}
-  scoped_refptr<const T> ref_;
-};
+auto Unwrap(T&& o) -> decltype(Unwrapper<T>::Unwrap(std::forward<T>(o))) {
+  return Unwrapper<T>::Unwrap(std::forward<T>(o));
+}
 
 // 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.
 //
 // 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 <bool is_method, typename... Args>
+struct IsWeakMethod : std::false_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 {};
-
+struct IsWeakMethod<true, T, Args...> : IsWeakReceiver<T> {};
 
 // 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;
@@ -578,38 +375,54 @@ struct MakeFunctionTypeImpl<R, TypeList<
   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.
+// Used for ExtractArgs and ExtractReturnType.
 template <typename Signature>
 struct ExtractArgsImpl;
 
 template <typename R, typename... Args>
 struct ExtractArgsImpl<R(Args...)> {
-  using Type = TypeList<Args...>;
+  using ReturnType = R;
+  using ArgsList = 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;
+using ExtractArgs = typename ExtractArgsImpl<Signature>::ArgsList;
+
+// A type-level function that extracts the return type of a function.
+// E.g. ExtractReturnType<R(A, B, C)> is evaluated to R.
+template <typename Signature>
+using ExtractReturnType = typename ExtractArgsImpl<Signature>::ReturnType;
 
 }  // namespace internal
 
 template <typename T>
 static inline internal::UnretainedWrapper<T> Unretained(T* o) {
   return internal::UnretainedWrapper<T>(o);
 }
 
 template <typename T>
+static inline internal::RetainedRefWrapper<T> RetainedRef(T* o) {
+  return internal::RetainedRefWrapper<T>(o);
+}
+
+template <typename T>
+static inline internal::RetainedRefWrapper<T> RetainedRef(scoped_refptr<T> o) {
+  return internal::RetainedRefWrapper<T>(std::move(o));
+}
+
+template <typename T>
 static inline internal::ConstRefWrapper<T> ConstRef(const T& o) {
   return internal::ConstRefWrapper<T>(o);
 }
 
 template <typename T>
 static inline internal::OwnedWrapper<T> Owned(T* o) {
   return internal::OwnedWrapper<T>(o);
 }
@@ -617,42 +430,97 @@ static inline internal::OwnedWrapper<T> 
 // 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* =
+          typename std::enable_if<!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,
-          typename std::enable_if<internal::IsMoveOnlyType<T>::value>::type* =
-              nullptr>
+template <typename T>
 static inline internal::PassedWrapper<T> Passed(T* scoper) {
   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>
-static inline internal::IgnoreResultHelper<Callback<T> >
-IgnoreResult(const Callback<T>& data) {
-  return internal::IgnoreResultHelper<Callback<T> >(data);
+  return internal::IgnoreResultHelper<T>(std::move(data));
 }
 
 BASE_EXPORT void DoNothing();
 
 template<typename T>
 void DeletePointer(T* obj) {
   delete obj;
 }
 
+// An injection point to control |this| pointer behavior on a method invocation.
+// If IsWeakReceiver<> is true_type for |T| and |T| is used for a receiver of a
+// method, base::Bind cancels the method invocation if the receiver is tested as
+// false.
+// E.g. Foo::bar() is not called:
+//   struct Foo : base::SupportsWeakPtr<Foo> {
+//     void bar() {}
+//   };
+//
+//   WeakPtr<Foo> oo = nullptr;
+//   base::Bind(&Foo::bar, oo).Run();
+template <typename T>
+struct IsWeakReceiver : std::false_type {};
+
+template <typename T>
+struct IsWeakReceiver<internal::ConstRefWrapper<T>> : IsWeakReceiver<T> {};
+
+template <typename T>
+struct IsWeakReceiver<WeakPtr<T>> : std::true_type {};
+
+// An injection point to control how bound objects passed to the target
+// function. BindUnwrapTraits<>::Unwrap() is called for each bound objects right
+// before the target function is invoked.
+template <typename>
+struct BindUnwrapTraits {
+  template <typename T>
+  static T&& Unwrap(T&& o) { return std::forward<T>(o); }
+};
+
+template <typename T>
+struct BindUnwrapTraits<internal::UnretainedWrapper<T>> {
+  static T* Unwrap(const internal::UnretainedWrapper<T>& o) {
+    return o.get();
+  }
+};
+
+template <typename T>
+struct BindUnwrapTraits<internal::ConstRefWrapper<T>> {
+  static const T& Unwrap(const internal::ConstRefWrapper<T>& o) {
+    return o.get();
+  }
+};
+
+template <typename T>
+struct BindUnwrapTraits<internal::RetainedRefWrapper<T>> {
+  static T* Unwrap(const internal::RetainedRefWrapper<T>& o) {
+    return o.get();
+  }
+};
+
+template <typename T>
+struct BindUnwrapTraits<internal::OwnedWrapper<T>> {
+  static T* Unwrap(const internal::OwnedWrapper<T>& o) {
+    return o.get();
+  }
+};
+
+template <typename T>
+struct BindUnwrapTraits<internal::PassedWrapper<T>> {
+  static T Unwrap(const internal::PassedWrapper<T>& o) {
+    return o.Take();
+  }
+};
+
 }  // namespace base
 
 #endif  // BASE_BIND_HELPERS_H_
--- a/security/sandbox/chromium/base/bind_internal.h
+++ b/security/sandbox/chromium/base/bind_internal.h
@@ -2,424 +2,557 @@
 // 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 <tuple>
 #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 {
 
 // See base/callback.h for user documentation.
 //
 //
 // CONCEPTS:
-//  Runnable -- A type (really a type class) that has a single Run() method
-//              and a RunType typedef that corresponds to the type of Run().
-//              A Runnable can declare that it should treated like a method
-//              call by including a typedef named IsMethod.  The value of
-//              this typedef is NOT inspected, only the existence.  When a
-//              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.
+//  Functor -- A movable type representing something that should be called.
+//             All function pointers and Callback<> 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.
+//             a Callback<>::Run().  Usually just a convenience typedef.
 //  (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.
 //  ForceVoidReturn<> -- Helper class for translating function signatures to
 //                       equivalent forms with a "void" return type.
-//  FunctorTraits<> -- Type traits used determine the correct RunType and
-//                     RunnableType for a Functor.  This is where function
+//  FunctorTraits<> -- Type traits used to determine the correct RunType and
+//                     invocation manner for a Functor.  This is where function
 //                     signature adapters are applied.
-//  MakeRunnable<> -- Takes a Functor and returns an object in the Runnable
-//                    type class that represents the underlying Functor.
-//  InvokeHelper<> -- Take a Runnable + arguments and actully invokes it.
+//  InvokeHelper<> -- Take a Functor + 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<>.
-//  Invoker<> -- Unwraps the curried parameters and executes the Runnable.
+//                    support.  This is separate from Invoker to avoid creating
+//                    multiple version of Invoker<>.
+//  Invoker<> -- Unwraps the curried parameters and executes the Functor.
 //  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.
+//                 into the Bind() system.
+
+template <typename...>
+struct make_void {
+  using type = void;
+};
+
+// A clone of C++17 std::void_t.
+// Unlike the original version, we need |make_void| as a helper struct to avoid
+// a C++14 defect.
+// ref: http://en.cppreference.com/w/cpp/types/void_t
+// ref: http://open-std.org/JTC1/SC22/WG21/docs/cwg_defects.html#1558
+template <typename... Ts>
+using void_t = typename make_void<Ts...>::type;
+
+template <typename Callable,
+          typename Signature = decltype(&Callable::operator())>
+struct ExtractCallableRunTypeImpl;
 
-// 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 {};
+template <typename Callable, typename R, typename... Args>
+struct ExtractCallableRunTypeImpl<Callable, R(Callable::*)(Args...) const> {
+  using Type = R(Args...);
+};
+
+// Evaluated to RunType of the given callable type.
+// Example:
+//   auto f = [](int, char*) { return 0.1; };
+//   ExtractCallableRunType<decltype(f)>
+//   is evaluated to
+//   double(int, char*);
+template <typename Callable>
+using ExtractCallableRunType =
+    typename ExtractCallableRunTypeImpl<Callable>::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 {};
+// IsConvertibleToRunType<Functor> is std::true_type if |Functor| has operator()
+// and convertible to the corresponding function pointer. Otherwise, it's
+// std::false_type.
+// Example:
+//   IsConvertibleToRunType<void(*)()>::value is false.
+//
+//   struct Foo {};
+//   IsConvertibleToRunType<void(Foo::*)()>::value is false.
+//
+//   auto f = []() {};
+//   IsConvertibleToRunType<decltype(f)>::value is true.
+//
+//   int i = 0;
+//   auto g = [i]() {};
+//   IsConvertibleToRunType<decltype(g)>::value is false.
+template <typename Functor, typename SFINAE = void>
+struct IsConvertibleToRunType : std::false_type {};
+
+template <typename Callable>
+struct IsConvertibleToRunType<Callable, void_t<decltype(&Callable::operator())>>
+    : std::is_convertible<Callable, ExtractCallableRunType<Callable>*> {};
 
 // 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 {};
+struct HasRefCountedTypeAsRawPtr : std::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,
+                       std::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.
-//
-// For method pointers and const method pointers the first argument to Run()
-// is considered to be the received of the method.  This is similar to STL's
-// mem_fun().
-//
-// This class also exposes a RunType typedef that is the function type of the
-// Run() function.
-//
-// 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.
-template <typename R, typename... Args>
-class RunnableAdapter<R(*)(Args...)> {
- public:
-  // 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(*function)(Args...))
-      : function_(function) {
-  }
-
-  R Run(typename CallbackParamTraits<Args>::ForwardType... args) {
-    return function_(CallbackForward(args)...);
-  }
-
- private:
-  R (*function_)(Args...);
-};
-
-// Method.
-template <typename R, typename T, typename... Args>
-class RunnableAdapter<R(T::*)(Args...)> {
- public:
-  // 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;
-
-  explicit RunnableAdapter(R(T::*method)(Args...))
-      : method_(method) {
-  }
-
-  R Run(T* object, typename CallbackParamTraits<Args>::ForwardType... args) {
-    return (object->*method_)(CallbackForward(args)...);
-  }
-
- private:
-  R (T::*method_)(Args...);
-};
-
-// Const Method.
-template <typename R, typename T, typename... Args>
-class RunnableAdapter<R(T::*)(Args...) const> {
- public:
-  using RunType = R(const T*, Args...);
-  using IsMethod = true_type;
-
-  explicit RunnableAdapter(R(T::*method)(Args...) const)
-      : method_(method) {
-  }
-
-  R Run(const T* object,
-        typename CallbackParamTraits<Args>::ForwardType... args) {
-    return (object->*method_)(CallbackForward(args)...);
-  }
-
- private:
-  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, 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...);
+  using RunType = void(Args...);
 };
 
-
 // FunctorTraits<>
 //
 // See description at top of file.
-template <typename T>
-struct FunctorTraits {
-  using RunnableType = RunnableAdapter<T>;
-  using RunType = typename RunnableType::RunType;
+template <typename Functor, typename SFINAE = void>
+struct FunctorTraits;
+
+// For a callable type that is convertible to the corresponding function type.
+// This specialization is intended to allow binding captureless lambdas by
+// base::Bind(), based on the fact that captureless lambdas can be convertible
+// to the function type while capturing lambdas can't.
+template <typename Functor>
+struct FunctorTraits<
+    Functor,
+    typename std::enable_if<IsConvertibleToRunType<Functor>::value>::type> {
+  using RunType = ExtractCallableRunType<Functor>;
+  static constexpr bool is_method = false;
+  static constexpr bool is_nullable = false;
+
+  template <typename... RunArgs>
+  static ExtractReturnType<RunType>
+  Invoke(const Functor& functor, RunArgs&&... args) {
+    return functor(std::forward<RunArgs>(args)...);
+  }
 };
 
-template <typename T>
-struct FunctorTraits<IgnoreResultHelper<T>> {
-  using RunnableType = typename FunctorTraits<T>::RunnableType;
-  using RunType =
-      typename ForceVoidReturn<typename RunnableType::RunType>::RunType;
+// For functions.
+template <typename R, typename... Args>
+struct FunctorTraits<R (*)(Args...)> {
+  using RunType = R(Args...);
+  static constexpr bool is_method = false;
+  static constexpr bool is_nullable = true;
+
+  template <typename... RunArgs>
+  static R Invoke(R (*function)(Args...), RunArgs&&... args) {
+    return function(std::forward<RunArgs>(args)...);
+  }
 };
 
-template <typename T>
-struct FunctorTraits<Callback<T>> {
-  using RunnableType = Callback<T> ;
-  using RunType = typename Callback<T>::RunType;
+#if defined(OS_WIN) && !defined(ARCH_CPU_X86_64)
+
+// For functions.
+template <typename R, typename... Args>
+struct FunctorTraits<R(__stdcall*)(Args...)> {
+  using RunType = R(Args...);
+  static constexpr bool is_method = false;
+  static constexpr bool is_nullable = true;
+
+  template <typename... RunArgs>
+  static R Invoke(R(__stdcall* function)(Args...), RunArgs&&... args) {
+    return function(std::forward<RunArgs>(args)...);
+  }
+};
+
+// For functions.
+template <typename R, typename... Args>
+struct FunctorTraits<R(__fastcall*)(Args...)> {
+  using RunType = R(Args...);
+  static constexpr bool is_method = false;
+  static constexpr bool is_nullable = true;
+
+  template <typename... RunArgs>
+  static R Invoke(R(__fastcall* function)(Args...), RunArgs&&... args) {
+    return function(std::forward<RunArgs>(args)...);
+  }
 };
 
+#endif  // defined(OS_WIN) && !defined(ARCH_CPU_X86_64)
 
-// MakeRunnable<>
-//
-// Converts a passed in functor to a RunnableType using type inference.
+// For methods.
+template <typename R, typename Receiver, typename... Args>
+struct FunctorTraits<R (Receiver::*)(Args...)> {
+  using RunType = R(Receiver*, Args...);
+  static constexpr bool is_method = true;
+  static constexpr bool is_nullable = true;
+
+  template <typename ReceiverPtr, typename... RunArgs>
+  static R Invoke(R (Receiver::*method)(Args...),
+                  ReceiverPtr&& receiver_ptr,
+                  RunArgs&&... args) {
+    // Clang skips CV qualifier check on a method pointer invocation when the
+    // receiver is a subclass. Store the receiver into a const reference to
+    // T to ensure the CV check works.
+    // https://llvm.org/bugs/show_bug.cgi?id=27037
+    Receiver& receiver = *receiver_ptr;
+    return (receiver.*method)(std::forward<RunArgs>(args)...);
+  }
+};
 
-template <typename T>
-typename FunctorTraits<T>::RunnableType MakeRunnable(const T& t) {
-  return RunnableAdapter<T>(t);
-}
+// For const methods.
+template <typename R, typename Receiver, typename... Args>
+struct FunctorTraits<R (Receiver::*)(Args...) const> {
+  using RunType = R(const Receiver*, Args...);
+  static constexpr bool is_method = true;
+  static constexpr bool is_nullable = true;
 
+  template <typename ReceiverPtr, typename... RunArgs>
+  static R Invoke(R (Receiver::*method)(Args...) const,
+                  ReceiverPtr&& receiver_ptr,
+                  RunArgs&&... args) {
+    // Clang skips CV qualifier check on a method pointer invocation when the
+    // receiver is a subclass. Store the receiver into a const reference to
+    // T to ensure the CV check works.
+    // https://llvm.org/bugs/show_bug.cgi?id=27037
+    const Receiver& receiver = *receiver_ptr;
+    return (receiver.*method)(std::forward<RunArgs>(args)...);
+  }
+};
+
+// For IgnoreResults.
 template <typename T>
-typename FunctorTraits<T>::RunnableType
-MakeRunnable(const IgnoreResultHelper<T>& t) {
-  return MakeRunnable(t.functor_);
-}
+struct FunctorTraits<IgnoreResultHelper<T>> : FunctorTraits<T> {
+  using RunType =
+      typename ForceVoidReturn<typename FunctorTraits<T>::RunType>::RunType;
+
+  template <typename IgnoreResultType, typename... RunArgs>
+  static void Invoke(IgnoreResultType&& ignore_result_helper,
+                     RunArgs&&... args) {
+    FunctorTraits<T>::Invoke(
+        std::forward<IgnoreResultType>(ignore_result_helper).functor_,
+        std::forward<RunArgs>(args)...);
+  }
+};
 
-template <typename T>
-const typename FunctorTraits<Callback<T>>::RunnableType&
-MakeRunnable(const Callback<T>& t) {
-  DCHECK(!t.is_null());
-  return t;
-}
+// For Callbacks.
+template <typename R, typename... Args,
+          CopyMode copy_mode, RepeatMode repeat_mode>
+struct FunctorTraits<Callback<R(Args...), copy_mode, repeat_mode>> {
+  using RunType = R(Args...);
+  static constexpr bool is_method = false;
+  static constexpr bool is_nullable = true;
 
+  template <typename CallbackType, typename... RunArgs>
+  static R Invoke(CallbackType&& callback, RunArgs&&... args) {
+    DCHECK(!callback.is_null());
+    return std::forward<CallbackType>(callback).Run(
+        std::forward<RunArgs>(args)...);
+  }
+};
 
 // InvokeHelper<>
 //
-// There are 3 logical InvokeHelper<> specializations: normal, void-return,
-// WeakCalls.
+// There are 2 logical InvokeHelper<> specializations: normal, WeakCalls.
 //
 // The normal type just calls the underlying runnable.
 //
-// We need a InvokeHelper to handle void return types in order to support
-// IgnoreResult().  Normally, if the Runnable's RunType had a void return,
-// the template system would just accept "return functor.Run()" ignoring
-// the fact that a void function is being used with return. This piece of
-// sugar breaks though when the Runnable's RunType is not void.  Thus, we
-// need a partial specialization to change the syntax to drop the "return"
-// 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>
+// WeakCalls need special syntax that is applied to the first argument to check
+// if they should no-op themselves.
+template <bool is_weak_call, typename ReturnType>
 struct InvokeHelper;
 
-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 ReturnType>
+struct InvokeHelper<false, ReturnType> {
+  template <typename Functor, typename... RunArgs>
+  static inline ReturnType MakeItSo(Functor&& functor, RunArgs&&... args) {
+    using Traits = FunctorTraits<typename std::decay<Functor>::type>;
+    return Traits::Invoke(std::forward<Functor>(functor),
+                          std::forward<RunArgs>(args)...);
   }
 };
 
-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 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(args)...);
-  }
-};
-
-#if !defined(_MSC_VER)
-
-template <typename ReturnType, typename Runnable, typename ArgsType>
-struct InvokeHelper<true, ReturnType, Runnable, ArgsType> {
+template <typename ReturnType>
+struct InvokeHelper<true, ReturnType> {
   // WeakCalls are only supported for functions with a void return type.
   // Otherwise, the function result would be undefined if the the WeakPtr<>
   // is invalidated.
-  static_assert(is_void<ReturnType>::value,
+  static_assert(std::is_void<ReturnType>::value,
                 "weak_ptrs can only bind to methods without return values");
+
+  template <typename Functor, typename BoundWeakPtr, typename... RunArgs>
+  static inline void MakeItSo(Functor&& functor,
+                              BoundWeakPtr&& weak_ptr,
+                              RunArgs&&... args) {
+    if (!weak_ptr)
+      return;
+    using Traits = FunctorTraits<typename std::decay<Functor>::type>;
+    Traits::Invoke(std::forward<Functor>(functor),
+                   std::forward<BoundWeakPtr>(weak_ptr),
+                   std::forward<RunArgs>(args)...);
+  }
 };
 
-#endif
-
 // Invoker<>
 //
 // See description at the top of the file.
-template <typename BoundIndices,
-          typename StorageType, typename Unwrappers,
-          typename InvokeHelperType, typename UnboundForwardRunType>
+template <typename StorageType, typename UnboundRunType>
 struct Invoker;
 
-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,
-               UnboundForwardArgs... unbound_args) {
+template <typename StorageType, typename R, typename... UnboundArgs>
+struct Invoker<StorageType, R(UnboundArgs...)> {
+  static R RunOnce(BindStateBase* base, UnboundArgs&&... unbound_args) {
+    // 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.
     StorageType* storage = static_cast<StorageType*>(base);
+    static constexpr size_t num_bound_args =
+        std::tuple_size<decltype(storage->bound_args_)>::value;
+    return RunImpl(std::move(storage->functor_),
+                   std::move(storage->bound_args_),
+                   MakeIndexSequence<num_bound_args>(),
+                   std::forward<UnboundArgs>(unbound_args)...);
+  }
+
+  static R Run(BindStateBase* base, UnboundArgs&&... unbound_args) {
     // 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 InvokeHelperType::MakeItSo(
-        storage->runnable_,
-        Unwrappers::Unwrap(get<bound_indices>(storage->bound_args_))...,
-        CallbackForward(unbound_args)...);
+    const StorageType* storage = static_cast<StorageType*>(base);
+    static constexpr size_t num_bound_args =
+        std::tuple_size<decltype(storage->bound_args_)>::value;
+    return RunImpl(storage->functor_,
+                   storage->bound_args_,
+                   MakeIndexSequence<num_bound_args>(),
+                   std::forward<UnboundArgs>(unbound_args)...);
+  }
+
+ private:
+  template <typename Functor, typename BoundArgsTuple, size_t... indices>
+  static inline R RunImpl(Functor&& functor,
+                          BoundArgsTuple&& bound,
+                          IndexSequence<indices...>,
+                          UnboundArgs&&... unbound_args) {
+    static constexpr bool is_method =
+        FunctorTraits<typename std::decay<Functor>::type>::is_method;
+
+    using DecayedArgsTuple = typename std::decay<BoundArgsTuple>::type;
+    static constexpr bool is_weak_call =
+        IsWeakMethod<is_method,
+                     typename std::tuple_element<
+                         indices,
+                         DecayedArgsTuple>::type...>::value;
+
+    return InvokeHelper<is_weak_call, R>::MakeItSo(
+        std::forward<Functor>(functor),
+        Unwrap(base::get<indices>(std::forward<BoundArgsTuple>(bound)))...,
+        std::forward<UnboundArgs>(unbound_args)...);
   }
 };
 
+// Used to implement MakeUnboundRunType.
+template <typename Functor, typename... BoundArgs>
+struct MakeUnboundRunTypeImpl {
+  using RunType =
+      typename FunctorTraits<typename std::decay<Functor>::type>::RunType;
+  using ReturnType = ExtractReturnType<RunType>;
+  using Args = ExtractArgs<RunType>;
+  using UnboundArgs = DropTypeListItem<sizeof...(BoundArgs), Args>;
+  using Type = MakeFunctionType<ReturnType, UnboundArgs>;
+};
+template <typename Functor>
+typename std::enable_if<FunctorTraits<Functor>::is_nullable, bool>::type
+IsNull(const Functor& functor) {
+  return !functor;
+}
+
+template <typename Functor>
+typename std::enable_if<!FunctorTraits<Functor>::is_nullable, bool>::type
+IsNull(const Functor&) {
+  return false;
+}
+
+template <typename Functor, typename... BoundArgs>
+struct BindState;
+
+template <typename BindStateType, typename SFINAE = void>
+struct CancellationChecker {
+  static constexpr bool is_cancellable = false;
+  static bool Run(const BindStateBase*) {
+    return false;
+  }
+};
+
+template <typename Functor, typename... BoundArgs>
+struct CancellationChecker<
+    BindState<Functor, BoundArgs...>,
+    typename std::enable_if<IsWeakMethod<FunctorTraits<Functor>::is_method,
+                                         BoundArgs...>::value>::type> {
+  static constexpr bool is_cancellable = true;
+  static bool Run(const BindStateBase* base) {
+    using BindStateType = BindState<Functor, BoundArgs...>;
+    const BindStateType* bind_state = static_cast<const BindStateType*>(base);
+    return !base::get<0>(bind_state->bound_args_);
+  }
+};
+
+template <typename Signature,
+          typename... BoundArgs,
+          CopyMode copy_mode,
+          RepeatMode repeat_mode>
+struct CancellationChecker<
+    BindState<Callback<Signature, copy_mode, repeat_mode>, BoundArgs...>> {
+  static constexpr bool is_cancellable = true;
+  static bool Run(const BindStateBase* base) {
+    using Functor = Callback<Signature, copy_mode, repeat_mode>;
+    using BindStateType = BindState<Functor, BoundArgs...>;
+    const BindStateType* bind_state = static_cast<const BindStateType*>(base);
+    return bind_state->functor_.IsCancelled();
+  }
+};
+
+// Template helpers to detect using Bind() on a base::Callback without any
+// additional arguments. In that case, the original base::Callback object should
+// just be directly used.
+template <typename Functor, typename... BoundArgs>
+struct BindingCallbackWithNoArgs {
+  static constexpr bool value = false;
+};
+
+template <typename Signature,
+          typename... BoundArgs,
+          CopyMode copy_mode,
+          RepeatMode repeat_mode>
+struct BindingCallbackWithNoArgs<Callback<Signature, copy_mode, repeat_mode>,
+                                 BoundArgs...> {
+  static constexpr bool value = sizeof...(BoundArgs) == 0;
+};
 
 // 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.
-//
-// BoundArgs contains the storage type for all the bound arguments.
-template <typename Runnable, typename RunType, typename... BoundArgs>
-struct BindState;
-
-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;
-
-  // true_type if Runnable is a method invocation and the first bound argument
-  // is a WeakPtr.
-  using IsWeakCall =
-      IsWeakMethod<HasIsMethodTag<Runnable>::value, BoundArgs...>;
+// This stores all the state passed into Bind().
+template <typename Functor, typename... BoundArgs>
+struct BindState final : BindStateBase {
+  using IsCancellable = std::integral_constant<
+      bool, CancellationChecker<BindState>::is_cancellable>;
 
-  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>;
-
-  using InvokeHelperArgs = ConcatTypeLists<
-      TypeList<typename UnwrapTraits<BoundArgs>::ForwardType...>,
-      UnboundForwardArgs>;
-  using InvokeHelperType =
-      InvokeHelper<IsWeakCall::value, R, Runnable, InvokeHelperArgs>;
-
-  using UnboundArgs = DropTypeListItem<sizeof...(BoundArgs), TypeList<Args...>>;
+  template <typename ForwardFunctor, typename... ForwardBoundArgs>
+  explicit BindState(BindStateBase::InvokeFuncStorage invoke_func,
+                     ForwardFunctor&& functor,
+                     ForwardBoundArgs&&... bound_args)
+      // IsCancellable is std::false_type if the CancellationChecker<>::Run
+      // returns always false. Otherwise, it's std::true_type.
+      : BindState(IsCancellable{},
+                  invoke_func,
+                  std::forward<ForwardFunctor>(functor),
+                  std::forward<ForwardBoundArgs>(bound_args)...) {
+    static_assert(!BindingCallbackWithNoArgs<Functor, BoundArgs...>::value,
+                  "Attempting to bind a base::Callback with no additional "
+                  "arguments: save a heap allocation and use the original "
+                  "base::Callback object");
+  }
 
- public:
-  using InvokerType = Invoker<BoundIndices, StorageType, Unwrappers,
-                              InvokeHelperType, UnboundForwardRunType>;
-  using UnboundRunType = MakeFunctionType<R, UnboundArgs>;
-
-  BindState(const Runnable& runnable, const BoundArgs&... bound_args)
-      : BindStateBase(&Destroy),
-        runnable_(runnable),
-        ref_(bound_args...),
-        bound_args_(bound_args...) {}
-
-  RunnableType runnable_;
-  MaybeScopedRefPtr<HasIsMethodTag<Runnable>::value, BoundArgs...> ref_;
-  Tuple<BoundArgs...> bound_args_;
+  Functor functor_;
+  std::tuple<BoundArgs...> bound_args_;
 
  private:
+  template <typename ForwardFunctor, typename... ForwardBoundArgs>
+  explicit BindState(std::true_type,
+                     BindStateBase::InvokeFuncStorage invoke_func,
+                     ForwardFunctor&& functor,
+                     ForwardBoundArgs&&... bound_args)
+      : BindStateBase(invoke_func, &Destroy,
+                      &CancellationChecker<BindState>::Run),
+        functor_(std::forward<ForwardFunctor>(functor)),
+        bound_args_(std::forward<ForwardBoundArgs>(bound_args)...) {
+    DCHECK(!IsNull(functor_));
+  }
+
+  template <typename ForwardFunctor, typename... ForwardBoundArgs>
+  explicit BindState(std::false_type,
+                     BindStateBase::InvokeFuncStorage invoke_func,
+                     ForwardFunctor&& functor,
+                     ForwardBoundArgs&&... bound_args)
+      : BindStateBase(invoke_func, &Destroy),
+        functor_(std::forward<ForwardFunctor>(functor)),
+        bound_args_(std::forward<ForwardBoundArgs>(bound_args)...) {
+    DCHECK(!IsNull(functor_));
+  }
+
   ~BindState() {}
 
-  static void Destroy(BindStateBase* self) {
-    delete static_cast<BindState*>(self);
+  static void Destroy(const BindStateBase* self) {
+    delete static_cast<const BindState*>(self);
   }
 };
 
+// Used to implement MakeBindStateType.
+template <bool is_method, typename Functor, typename... BoundArgs>
+struct MakeBindStateTypeImpl;
+
+template <typename Functor, typename... BoundArgs>
+struct MakeBindStateTypeImpl<false, Functor, BoundArgs...> {
+  static_assert(!HasRefCountedTypeAsRawPtr<BoundArgs...>::value,
+                "A parameter is a refcounted type and needs scoped_refptr.");
+  using Type = BindState<typename std::decay<Functor>::type,
+                         typename std::decay<BoundArgs>::type...>;
+};
+
+template <typename Functor>
+struct MakeBindStateTypeImpl<true, Functor> {
+  using Type = BindState<typename std::decay<Functor>::type>;
+};
+
+template <typename Functor, typename Receiver, typename... BoundArgs>
+struct MakeBindStateTypeImpl<true, Functor, Receiver, BoundArgs...> {
+  static_assert(
+      !std::is_array<typename std::remove_reference<Receiver>::type>::value,
+      "First bound argument to a method cannot be an array.");
+  static_assert(!HasRefCountedTypeAsRawPtr<BoundArgs...>::value,
+                "A parameter is a refcounted type and needs scoped_refptr.");
+
+ private:
+  using DecayedReceiver = typename std::decay<Receiver>::type;
+
+ public:
+  using Type = BindState<
+      typename std::decay<Functor>::type,
+      typename std::conditional<
+          std::is_pointer<DecayedReceiver>::value,
+          scoped_refptr<typename std::remove_pointer<DecayedReceiver>::type>,
+          DecayedReceiver>::type,
+      typename std::decay<BoundArgs>::type...>;
+};
+
+template <typename Functor, typename... BoundArgs>
+using MakeBindStateType = typename MakeBindStateTypeImpl<
+    FunctorTraits<typename std::decay<Functor>::type>::is_method,
+    Functor,
+    BoundArgs...>::Type;
+
 }  // namespace internal
+
+// Returns a RunType of bound functor.
+// E.g. MakeUnboundRunType<R(A, B, C), A, B> is evaluated to R(C).
+template <typename Functor, typename... BoundArgs>
+using MakeUnboundRunType =
+    typename internal::MakeUnboundRunTypeImpl<Functor, BoundArgs...>::Type;
+
 }  // namespace base
 
 #endif  // BASE_BIND_INTERNAL_H_
deleted file mode 100644
--- a/security/sandbox/chromium/base/bind_internal_win.h
+++ /dev/null
@@ -1,69 +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.
-
-// 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:
-  // 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...);
-  }
-
- private:
-  R (__stdcall *function_)(Args...);
-};
-
-// __fastcall Function.
-template <typename R, typename... Args>
-class RunnableAdapter<R(__fastcall *)(Args...)> {
- public:
-  // 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...);
-  }
-
- private:
-  R (__fastcall *function_)(Args...);
-};
-
-}  // namespace internal
-}  // namespace base
-
-#endif  // !defined(ARCH_CPU_X86_64)
-
-#endif  // BASE_BIND_INTERNAL_WIN_H_
--- a/security/sandbox/chromium/base/bit_cast.h
+++ b/security/sandbox/chromium/base/bit_cast.h
@@ -1,16 +1,20 @@
 // 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>
+#include <type_traits>
+
+#include "base/compiler_specific.h"
+#include "build/build_config.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
@@ -49,23 +53,48 @@
 // 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");
 
+#if (__GNUC__ > 5 || (__GNUC__ == 5 && __GNUC_MINOR__ >= 1) || \
+     (defined(__clang__) && defined(_LIBCPP_VERSION)))
+  // GCC 5.1 contains the first libstdc++ with is_trivially_copyable.
+  // Assume libc++ Just Works: is_trivially_copyable added on May 13th 2011.
+  // However, with libc++ when GCC is the compiler the trait is buggy, see
+  // crbug.com/607158, so fall back to the less strict variant for non-clang.
+  static_assert(std::is_trivially_copyable<Dest>::value,
+                "non-trivially-copyable bit_cast is undefined");
+  static_assert(std::is_trivially_copyable<Source>::value,
+                "non-trivially-copyable bit_cast is undefined");
+#elif HAS_FEATURE(is_trivially_copyable)
+  // The compiler supports an equivalent intrinsic.
+  static_assert(__is_trivially_copyable(Dest),
+                "non-trivially-copyable bit_cast is undefined");
+  static_assert(__is_trivially_copyable(Source),
+                "non-trivially-copyable bit_cast is undefined");
+#elif COMPILER_GCC
+  // Fallback to compiler intrinsic on GCC and clang (which pretends to be
+  // GCC). This isn't quite the same as is_trivially_copyable but it'll do for
+  // our purpose.
+  static_assert(__has_trivial_copy(Dest),
+                "non-trivially-copyable bit_cast is undefined");
+  static_assert(__has_trivial_copy(Source),
+                "non-trivially-copyable bit_cast is undefined");
+#else
+  // Do nothing, let the bots handle it.
+#endif
+
   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
@@ -2,404 +2,123 @@
 // 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"
 #include "base/callback_internal.h"
-#include "base/template_util.h"
 
 // NOTE: Header files that do not require the full definition of Callback or
 // Closure should #include "base/callback_forward.h" instead of this file.
 
 // -----------------------------------------------------------------------------
-// Introduction
-// -----------------------------------------------------------------------------
-//
-// The templated Callback class is a generalized function object. Together
-// with the Bind() function in bind.h, they provide a type-safe method for
-// 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()>)
-// 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
-// and thus do not need to be deleted.
-//
-// The reason to pass via a const-reference is to avoid unnecessary
-// AddRef/Release pairs to the internal state.
-//
-//
-// -----------------------------------------------------------------------------
-// Quick reference for basic stuff
-// -----------------------------------------------------------------------------
-//
-// BINDING A BARE FUNCTION
-//
-//   int Return5() { return 5; }
-//   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()> 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
-//
-//   Callbacks can be run with their "Run" method, which has the same
-//   signature as the template argument to the callback.
-//
-//   void DoSomething(const base::Callback<void(int, std::string)>& callback) {
-//     callback.Run(5, "hello");
-//   }
-//
-//   Callbacks can be run more than once (they don't get deleted or marked when
-//   run). However, this precludes using base::Passed (see below).
-//
-//   void DoSomething(const base::Callback<double(double)>& callback) {
-//     double myresult = callback.Run(3.14159);
-//     myresult += callback.Run(2.71828);
-//   }
-//
-// PASSING UNBOUND INPUT PARAMETERS
-//
-//   Unbound parameters are specified at the time a callback is Run(). They are
-//   specified in the Callback template type:
-//
-//   void MyFunc(int i, const std::string& str) {}
-//   base::Callback<void(int, const std::string&)> cb = base::Bind(&MyFunc);
-//   cb.Run(23, "hello, world");
-//
-// 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()> cb = base::Bind(&MyFunc, 23, "hello world");
-//   cb.Run();
-//
-//   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");
-//
-// PARTIAL BINDING OF PARAMETERS
-//
-//   You can specify some parameters when you create the callback, and specify
-//   the rest when you execute the callback.
-//
-//   void MyFunc(int i, const std::string& str) {}
-//   base::Callback<void(const std::string&)> cb = base::Bind(&MyFunc, 23);
-//   cb.Run("hello world");
-//
-//   When calling a function bound parameters are first, followed by unbound
-//   parameters.
-//
-//
-// -----------------------------------------------------------------------------
-// Quick reference for advanced binding
-// -----------------------------------------------------------------------------
-//
-// BINDING A CLASS METHOD WITH WEAK POINTERS
-//
-//   base::Bind(&MyClass::Foo, GetWeakPtr());
-//
-//   The callback will not be run if the object has already been destroyed.
-//   DANGER: weak pointers are not threadsafe, so don't use this
-//   when passing between threads!
-//
-// BINDING A CLASS METHOD WITH MANUAL LIFETIME MANAGEMENT
-//
-//   base::Bind(&MyClass::Foo, base::Unretained(this));
-//
-//   This disables all lifetime management on the object. You're responsible
-//   for making sure the object is alive at the time of the call. You break it,
-//   you own it!
-//
-// BINDING A CLASS METHOD AND HAVING THE CALLBACK OWN THE CLASS
-//
-//   MyClass* myclass = new MyClass;
-//   base::Bind(&MyClass::Foo, base::Owned(myclass));
-//
-//   The object will be deleted when the callback is destroyed, even if it's
-//   not run (like if you post a task during shutdown). Potentially useful for
-//   "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::Bind(base::IgnoreResult(&DoSomething));
-//
-//
-// -----------------------------------------------------------------------------
-// Quick reference for binding parameters to Bind()
+// Usage documentation
 // -----------------------------------------------------------------------------
 //
-// 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()> 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
-//   not run (like if you post a task during shutdown).
-//
-// PASSING PARAMETERS AS A scoped_ptr
-//
-//   void TakesOwnership(scoped_ptr<Foo> arg) {}
-//   scoped_ptr<Foo> f(new Foo);
-//   // f becomes null during the following call.
-//   base::Closure cb = base::Bind(&TakesOwnership, base::Passed(&f));
-//
-//   Ownership of the parameter will be with the callback until the it is run,
-//   when ownership is passed to the callback function. This means the callback
-//   can only be run once. If the callback is never run, it will delete the
-//   object when it's destroyed.
-//
-// PASSING PARAMETERS AS A scoped_refptr
-//
-//   void TakesOneRef(scoped_refptr<Foo> arg) {}
-//   scoped_refptr<Foo> f(new Foo)
-//   base::Closure cb = base::Bind(&TakesOneRef, f);
-//
-//   This should "just work." The closure will take a reference as long as it
-//   is alive, and another reference will be taken for the called function.
-//
-// PASSING PARAMETERS BY REFERENCE
-//
-//   Const references are *copied* unless ConstRef is used. Example:
-//
-//   void foo(const int& arg) { printf("%d %p\n", arg, &arg); }
-//   int n = 1;
-//   base::Closure has_copy = base::Bind(&foo, n);
-//   base::Closure has_ref = base::Bind(&foo, base::ConstRef(n));
-//   n = 2;
-//   foo(n);                        // Prints "2 0xaaaaaaaaaaaa"
-//   has_copy.Run();                // Prints "1 0xbbbbbbbbbbbb"
-//   has_ref.Run();                 // Prints "2 0xaaaaaaaaaaaa"
-//
-//   Normally parameters are copied in the closure. DANGER: ConstRef stores a
-//   const reference instead, referencing the original parameter. This means
-//   that you must ensure the object outlives the callback!
-//
-//
-// -----------------------------------------------------------------------------
-// Implementation notes
-// -----------------------------------------------------------------------------
-//
-// WHERE IS THIS DESIGN FROM:
-//
-// The design Callback and Bind is heavily influenced by C++'s
-// tr1::function/tr1::bind, and by the "Google Callback" system used inside
-// Google.
-//
-//
-// HOW THE IMPLEMENTATION WORKS:
-//
-// There are three main components to the system:
-//   1) The Callback classes.
-//   2) The Bind() functions.
-//   3) The arguments wrappers (e.g., Unretained() and ConstRef()).
-//
-// The Callback classes represent a generic function pointer. Internally,
-// it stores a refcounted piece of state that represents the target function
-// and all its bound parameters.  Each Callback specialization has a templated
-// constructor that takes an BindState<>*.  In the context of the constructor,
-// the static type of this BindState<> pointer uniquely identifies the
-// function it is representing, all its bound parameters, and a Run() method
-// that is capable of invoking the target.
-//
-// Callback's constructor takes the BindState<>* that has the full static type
-// and erases the target function type as well as the types of the bound
-// parameters.  It does this by storing a pointer to the specific Run()
-// function, and upcasting the state of BindState<>* to a
-// BindStateBase*. This is safe as long as this BindStateBase pointer
-// is only used with the stored Run() pointer.
-//
-// To BindState<> objects are created inside the Bind() functions.
-// These functions, along with a set of internal templates, are responsible for
-//
-//  - Unwrapping the function signature into return type, and parameters
-//  - Determining the number of parameters that are bound
-//  - Creating the BindState storing the bound parameters
-//  - Performing compile-time asserts to avoid error-prone behavior
-//  - Returning an Callback<> with an arity matching the number of unbound
-//    parameters and that knows the correct refcounting semantics for the
-//    target object if we are binding a method.
-//
-// The Bind functions do the above using type-inference, and template
-// specializations.
-//
-// By default Bind() will store copies of all bound parameters, and attempt
-// to refcount a target object if the function being bound is a class method.
-// These copies are created even if the function takes parameters as const
-// references. (Binding to non-const references is forbidden, see bind.h.)
-//
-// To change this behavior, we introduce a set of argument wrappers
-// (e.g., Unretained(), and ConstRef()).  These are simple container templates
-// that are passed by value, and wrap a pointer to argument.  See the
-// file-level comment in base/bind_helpers.h for more info.
-//
-// These types are passed to the Unwrap() functions, and the MaybeRefcount()
-// functions respectively to modify the behavior of Bind().  The Unwrap()
-// and MaybeRefcount() functions change behavior by doing partial
-// specialization based on whether or not a parameter is a wrapper type.
-//
-// ConstRef() is similar to tr1::cref.  Unretained() is specific to Chromium.
-//
-//
-// WHY NOT TR1 FUNCTION/BIND?
-//
-// Direct use of tr1::function and tr1::bind was considered, but ultimately
-// rejected because of the number of copy constructors invocations involved
-// in the binding of arguments during construction, and the forwarding of
-// arguments during invocation.  These copies will no longer be an issue in
-// C++0x because C++0x will support rvalue reference allowing for the compiler
-// to avoid these copies.  However, waiting for C++0x is not an option.
-//
-// Measured with valgrind on gcc version 4.4.3 (Ubuntu 4.4.3-4ubuntu5), the
-// tr1::bind call itself will invoke a non-trivial copy constructor three times
-// for each bound parameter.  Also, each when passing a tr1::function, each
-// bound argument will be copied again.
-//
-// In addition to the copies taken at binding and invocation, copying a
-// tr1::function causes a copy to be made of all the bound parameters and
-// state.
-//
-// Furthermore, in Chromium, it is desirable for the Callback to take a
-// reference on a target object when representing a class method call.  This
-// is not supported by tr1.
-//
-// Lastly, tr1::function and tr1::bind has a more general and flexible API.
-// This includes things like argument reordering by use of
-// tr1::bind::placeholder, support for non-const reference parameters, and some
-// limited amount of subtyping of the tr1::function object (e.g.,
-// tr1::function<int(int)> is convertible to tr1::function<void(int)>).
-//
-// These are not features that are required in Chromium. Some of them, such as
-// allowing for reference parameters, and subtyping of functions, may actually
-// become a source of errors. Removing support for these features actually
-// allows for a simpler implementation, and a terser Currying API.
-//
-//
-// WHY NOT GOOGLE CALLBACKS?
-//
-// The Google callback system also does not support refcounting.  Furthermore,
-// its implementation has a number of strange edge cases with respect to type
-// conversion of its arguments.  In particular, the argument's constness must
-// at times match exactly the function signature, or the type-inference might
-// break.  Given the above, writing a custom solution was easier.
-//
-//
-// MISSING FUNCTIONALITY
-//  - Invoking the return of Bind.  Bind(&foo).Run() does not work;
-//  - Binding arrays to functions that take a non-const pointer.
-//    Example:
-//      void Foo(const char* ptr);
-//      void Bar(char* ptr);
-//      Bind(&Foo, "test");
-//      Bind(&Bar, "test");  // This fails because ptr is not const.
+// See //docs/callback.md for documentation.
 
 namespace base {
 
-// First, we forward declare the Callback class template. This informs the
-// compiler that the template only has 1 type parameter which is the function
-// 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.
+namespace internal {
+
+// RunMixin provides different variants of `Run()` function to `Callback<>`
+// based on the type of callback.
+template <typename CallbackType>
+class RunMixin;
+
+// Specialization for OnceCallback.
+template <typename R, typename... Args>
+class RunMixin<Callback<R(Args...), CopyMode::MoveOnly, RepeatMode::Once>> {
+ private:
+  using CallbackType =
+      Callback<R(Args...), CopyMode::MoveOnly, RepeatMode::Once>;
+
+ public:
+  using PolymorphicInvoke = R(*)(internal::BindStateBase*, Args&&...);
 
-namespace internal {
-template <typename Runnable, typename RunType, typename... BoundArgsType>
-struct BindState;
+  R Run(Args... args) && {
+    // Move the callback instance into a local variable before the invocation,
+    // that ensures the internal state is cleared after the invocation.
+    // It's not safe to touch |this| after the invocation, since running the
+    // bound function may destroy |this|.
+    CallbackType cb = static_cast<CallbackType&&>(*this);
+    PolymorphicInvoke f =
+        reinterpret_cast<PolymorphicInvoke>(cb.polymorphic_invoke());
+    return f(cb.bind_state_.get(), std::forward<Args>(args)...);
+  }
+};
+
+// Specialization for RepeatingCallback.
+template <typename R, typename... Args, CopyMode copy_mode>
+class RunMixin<Callback<R(Args...), copy_mode, RepeatMode::Repeating>> {
+ private:
+  using CallbackType = Callback<R(Args...), copy_mode, RepeatMode::Repeating>;
+
+ public:
+  using PolymorphicInvoke = R(*)(internal::BindStateBase*, Args&&...);
+
+  R Run(Args... args) const {
+    const CallbackType& cb = static_cast<const CallbackType&>(*this);
+    PolymorphicInvoke f =
+        reinterpret_cast<PolymorphicInvoke>(cb.polymorphic_invoke());
+    return f(cb.bind_state_.get(), std::forward<Args>(args)...);
+  }
+};
+
+template <typename From, typename To>
+struct IsCallbackConvertible : std::false_type {};
+
+template <typename Signature>
+struct IsCallbackConvertible<
+  Callback<Signature, CopyMode::Copyable, RepeatMode::Repeating>,
+  Callback<Signature, CopyMode::MoveOnly, RepeatMode::Once>> : std::true_type {
+};
+
 }  // namespace internal
 
-template <typename R, typename... Args>
-class Callback<R(Args...)> : public internal::CallbackBase {
+template <typename R,
+          typename... Args,
+          internal::CopyMode copy_mode,
+          internal::RepeatMode repeat_mode>
+class Callback<R(Args...), copy_mode, repeat_mode>
+    : public internal::CallbackBase<copy_mode>,
+      public internal::RunMixin<Callback<R(Args...), copy_mode, repeat_mode>> {
  public:
-  // MSVC 2013 doesn't support Type Alias of function types.
-  // Revisit this after we update it to newer version.
-  typedef R RunType(Args...);
+  static_assert(repeat_mode != internal::RepeatMode::Once ||
+                copy_mode == internal::CopyMode::MoveOnly,
+                "OnceCallback must be MoveOnly.");
 
-  Callback() : CallbackBase(nullptr) { }
+  using RunType = R(Args...);
+
+  Callback() : internal::CallbackBase<copy_mode>(nullptr) {}
 
-  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);
+  explicit Callback(internal::BindStateBase* bind_state)
+      : internal::CallbackBase<copy_mode>(bind_state) {
+  }
+
+  template <typename OtherCallback,
+            typename = typename std::enable_if<
+                internal::IsCallbackConvertible<OtherCallback, Callback>::value
+            >::type>
+  Callback(OtherCallback other)
+      : internal::CallbackBase<copy_mode>(std::move(other)) {}
+
+  template <typename OtherCallback,
+            typename = typename std::enable_if<
+                internal::IsCallbackConvertible<OtherCallback, Callback>::value
+            >::type>
+  Callback& operator=(OtherCallback other) {
+    static_cast<internal::CallbackBase<copy_mode>&>(*this) = std::move(other);
+    return *this;
   }
 
   bool Equals(const Callback& other) const {
-    return CallbackBase::Equals(other);
+    return this->EqualsInternal(other);
   }
 
-  R Run(typename internal::CallbackParamTraits<Args>::ForwardType... args)
-      const {
-    PolymorphicInvoke f =
-        reinterpret_cast<PolymorphicInvoke>(polymorphic_invoke_);
-
-    return f(bind_state_.get(), internal::CallbackForward(args)...);
-  }
-
- private:
-  using PolymorphicInvoke =
-      R(*)(internal::BindStateBase*,
-           typename internal::CallbackParamTraits<Args>::ForwardType...);
+  friend class internal::RunMixin<Callback>;
 };
 
 }  // namespace base
 
 #endif  // BASE_CALLBACK_H_
--- a/security/sandbox/chromium/base/callback_forward.h
+++ b/security/sandbox/chromium/base/callback_forward.h
@@ -1,19 +1,48 @@
 // 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_CALLBACK_FORWARD_H_
 #define BASE_CALLBACK_FORWARD_H_
 
 namespace base {
+namespace internal {
 
-template <typename Sig>
+// CopyMode is used to control the copyablity of a Callback.
+// MoveOnly indicates the Callback is not copyable but movable, and Copyable
+// indicates it is copyable and movable.
+enum class CopyMode {
+  MoveOnly,
+  Copyable,
+};
+
+enum class RepeatMode {
+  Once,
+  Repeating,
+};
+
+}  // namespace internal
+
+template <typename Signature,
+          internal::CopyMode copy_mode = internal::CopyMode::Copyable,
+          internal::RepeatMode repeat_mode = internal::RepeatMode::Repeating>
 class Callback;
 
 // Syntactic sugar to make Callback<void()> easier to declare since it
 // will be used in a lot of APIs with delayed execution.
 using Closure = Callback<void()>;
 
+template <typename Signature>
+using OnceCallback = Callback<Signature,
+                              internal::CopyMode::MoveOnly,
+                              internal::RepeatMode::Once>;
+template <typename Signature>
+using RepeatingCallback = Callback<Signature,
+                                   internal::CopyMode::Copyable,
+                                   internal::RepeatMode::Repeating>;
+using OnceClosure = OnceCallback<void()>;
+using RepeatingClosure = RepeatingCallback<void()>;
+
 }  // namespace base
 
 #endif  // BASE_CALLBACK_FORWARD_H_
--- a/security/sandbox/chromium/base/callback_internal.cc
+++ b/security/sandbox/chromium/base/callback_internal.cc
@@ -4,43 +4,99 @@
 
 #include "base/callback_internal.h"
 
 #include "base/logging.h"
 
 namespace base {
 namespace internal {
 
-void BindStateBase::AddRef() {
+namespace {
+
+bool ReturnFalse(const BindStateBase*) {
+  return false;
+}
+
+}  // namespace
+
+BindStateBase::BindStateBase(InvokeFuncStorage polymorphic_invoke,
+                             void (*destructor)(const BindStateBase*))
+    : BindStateBase(polymorphic_invoke, destructor, &ReturnFalse) {
+}
+
+BindStateBase::BindStateBase(InvokeFuncStorage polymorphic_invoke,
+                             void (*destructor)(const BindStateBase*),
+                             bool (*is_cancelled)(const BindStateBase*))
+    : polymorphic_invoke_(polymorphic_invoke),
+      ref_count_(0),
+      destructor_(destructor),
+      is_cancelled_(is_cancelled) {}
+
+void BindStateBase::AddRef() const {
   AtomicRefCountInc(&ref_count_);
 }
 
-void BindStateBase::Release() {
+void BindStateBase::Release() const {
   if (!AtomicRefCountDec(&ref_count_))
     destructor_(this);
 }
 
-CallbackBase::CallbackBase(const CallbackBase& c) = default;
-CallbackBase& CallbackBase::operator=(const CallbackBase& c) = default;
+CallbackBase<CopyMode::MoveOnly>::CallbackBase(CallbackBase&& c) = default;
+
+CallbackBase<CopyMode::MoveOnly>&
+CallbackBase<CopyMode::MoveOnly>::operator=(CallbackBase&& c) = default;
 
-void CallbackBase::Reset() {
-  polymorphic_invoke_ = NULL;
+CallbackBase<CopyMode::MoveOnly>::CallbackBase(
+    const CallbackBase<CopyMode::Copyable>& c)
+    : bind_state_(c.bind_state_) {}
+
+CallbackBase<CopyMode::MoveOnly>& CallbackBase<CopyMode::MoveOnly>::operator=(
+    const CallbackBase<CopyMode::Copyable>& c) {
+  bind_state_ = c.bind_state_;
+  return *this;
+}
+
+void CallbackBase<CopyMode::MoveOnly>::Reset() {
   // NULL the bind_state_ last, since it may be holding the last ref to whatever
   // object owns us, and we may be deleted after that.
-  bind_state_ = NULL;
+  bind_state_ = nullptr;
+}
+
+bool CallbackBase<CopyMode::MoveOnly>::IsCancelled() const {
+  DCHECK(bind_state_);
+  return bind_state_->IsCancelled();
 }
 
-bool CallbackBase::Equals(const CallbackBase& other) const {
-  return bind_state_.get() == other.bind_state_.get() &&
-         polymorphic_invoke_ == other.polymorphic_invoke_;
+bool CallbackBase<CopyMode::MoveOnly>::EqualsInternal(
+    const CallbackBase& other) const {
+  return bind_state_ == other.bind_state_;
 }
 
-CallbackBase::CallbackBase(BindStateBase* bind_state)
-    : bind_state_(bind_state),
-      polymorphic_invoke_(NULL) {
+CallbackBase<CopyMode::MoveOnly>::CallbackBase(
+    BindStateBase* bind_state)
+    : bind_state_(bind_state) {
   DCHECK(!bind_state_.get() || bind_state_->ref_count_ == 1);
 }
 
-CallbackBase::~CallbackBase() {
+CallbackBase<CopyMode::MoveOnly>::~CallbackBase() {}
+
+CallbackBase<CopyMode::Copyable>::CallbackBase(
+    const CallbackBase& c)
+    : CallbackBase<CopyMode::MoveOnly>(nullptr) {
+  bind_state_ = c.bind_state_;
 }
 
+CallbackBase<CopyMode::Copyable>::CallbackBase(CallbackBase&& c) = default;
+
+CallbackBase<CopyMode::Copyable>&
+CallbackBase<CopyMode::Copyable>::operator=(const CallbackBase& c) {
+  bind_state_ = c.bind_state_;
+  return *this;
+}
+
+CallbackBase<CopyMode::Copyable>&
+CallbackBase<CopyMode::Copyable>::operator=(CallbackBase&& c) = default;
+
+template class CallbackBase<CopyMode::MoveOnly>;
+template class CallbackBase<CopyMode::Copyable>;
+
 }  // namespace internal
 }  // namespace base
--- a/security/sandbox/chromium/base/callback_internal.h
+++ b/security/sandbox/chromium/base/callback_internal.h
@@ -3,232 +3,137 @@
 // found in the LICENSE file.
 
 // This file contains utility functions and classes that help the
 // implementation, and management of the Callback objects.
 
 #ifndef BASE_CALLBACK_INTERNAL_H_
 #define BASE_CALLBACK_INTERNAL_H_
 
-#include <stddef.h>
-#include <memory>
-#include <type_traits>
-
 #include "base/atomic_ref_count.h"
 #include "base/base_export.h"
+#include "base/callback_forward.h"
 #include "base/macros.h"
 #include "base/memory/ref_counted.h"
-#include "base/memory/scoped_ptr.h"
-#include "base/template_util.h"
 
 namespace base {
 namespace internal {
+template <CopyMode copy_mode>
 class CallbackBase;
 
 // BindStateBase is used to provide an opaque handle that the Callback
 // class can use to represent a function object with bound arguments.  It
 // behaves as an existential type that is used by a corresponding
 // DoInvoke function to perform the function execution.  This allows
 // us to shield the Callback class from the types of the bound argument via
 // "type erasure."
 // At the base level, the only task is to add reference counting data. Don't use
 // RefCountedThreadSafe since it requires the destructor to be a virtual method.
 // Creating a vtable for every BindState template instantiation results in a lot
 // of bloat. Its only task is to call the destructor which can be done with a
 // function pointer.
-class BindStateBase {
+class BASE_EXPORT BindStateBase {
+ public:
+  using InvokeFuncStorage = void(*)();
+
  protected:
-  explicit BindStateBase(void (*destructor)(BindStateBase*))
-      : ref_count_(0), destructor_(destructor) {}
+  BindStateBase(InvokeFuncStorage polymorphic_invoke,
+                void (*destructor)(const BindStateBase*));
+  BindStateBase(InvokeFuncStorage polymorphic_invoke,
+                void (*destructor)(const BindStateBase*),
+                bool (*is_cancelled)(const BindStateBase*));
   ~BindStateBase() = default;
 
  private:
   friend class scoped_refptr<BindStateBase>;
+  template <CopyMode copy_mode>
   friend class CallbackBase;
 
-  void AddRef();
-  void Release();
+  bool IsCancelled() const {
+    return is_cancelled_(this);
+  }
+
+  void AddRef() const;
+  void Release() const;
 
-  AtomicRefCount ref_count_;
+  // In C++, it is safe to cast function pointers to function pointers of
+  // another type. It is not okay to use void*. We create a InvokeFuncStorage
+  // that that can store our function pointer, and then cast it back to
+  // the original type on usage.
+  InvokeFuncStorage polymorphic_invoke_;
+
+  mutable AtomicRefCount ref_count_;
 
   // Pointer to a function that will properly destroy |this|.
-  void (*destructor_)(BindStateBase*);
+  void (*destructor_)(const BindStateBase*);
+  bool (*is_cancelled_)(const BindStateBase*);
 
   DISALLOW_COPY_AND_ASSIGN(BindStateBase);
 };
 
 // Holds the Callback methods that don't require specialization to reduce
 // template bloat.
-class BASE_EXPORT CallbackBase {
+// CallbackBase<MoveOnly> is a direct base class of MoveOnly callbacks, and
+// CallbackBase<Copyable> uses CallbackBase<MoveOnly> for its implementation.
+template <>
+class BASE_EXPORT CallbackBase<CopyMode::MoveOnly> {
  public:
-  CallbackBase(const CallbackBase& c);
-  CallbackBase& operator=(const CallbackBase& c);
+  CallbackBase(CallbackBase&& c);
+  CallbackBase& operator=(CallbackBase&& c);
+
+  explicit CallbackBase(const CallbackBase<CopyMode::Copyable>& c);
+  CallbackBase& operator=(const CallbackBase<CopyMode::Copyable>& c);
 
   // Returns true if Callback is null (doesn't refer to anything).
   bool is_null() const { return bind_state_.get() == NULL; }
+  explicit operator bool() const { return !is_null(); }
+
+  // Returns true if the callback invocation will be nop due to an cancellation.
+  // It's invalid to call this on uninitialized callback.
+  bool IsCancelled() const;
 
   // Returns the Callback into an uninitialized state.
   void Reset();
 
  protected:
-  // In C++, it is safe to cast function pointers to function pointers of
-  // another type. It is not okay to use void*. We create a InvokeFuncStorage
-  // that that can store our function pointer, and then cast it back to
-  // the original type on usage.
-  using InvokeFuncStorage = void(*)();
+  using InvokeFuncStorage = BindStateBase::InvokeFuncStorage;
 
   // Returns true if this callback equals |other|. |other| may be null.
-  bool Equals(const CallbackBase& other) const;
+  bool EqualsInternal(const CallbackBase& other) const;
 
   // Allow initializing of |bind_state_| via the constructor to avoid default
-  // initialization of the scoped_refptr.  We do not also initialize
-  // |polymorphic_invoke_| here because doing a normal assignment in the
-  // derived Callback templates makes for much nicer compiler errors.
+  // initialization of the scoped_refptr.
   explicit CallbackBase(BindStateBase* bind_state);
 
+  InvokeFuncStorage polymorphic_invoke() const {
+    return bind_state_->polymorphic_invoke_;
+  }
+
   // Force the destructor to be instantiated inside this translation unit so
   // that our subclasses will not get inlined versions.  Avoids more template
   // bloat.
   ~CallbackBase();
 
   scoped_refptr<BindStateBase> bind_state_;
-  InvokeFuncStorage polymorphic_invoke_;
-};
-
-// A helper template to determine if given type is non-const move-only-type,
-// i.e. if a value of the given type should be passed via std::move() in a
-// destructive way. Types are considered to be move-only if they have a
-// sentinel MoveOnlyTypeForCPP03 member: a class typically gets this from using
-// the DISALLOW_COPY_AND_ASSIGN_WITH_MOVE_FOR_BIND macro.
-// It would be easy to generalize this trait to all move-only types... but this
-// confuses template deduction in VS2013 with certain types such as
-// std::unique_ptr.
-// TODO(dcheng): Revisit this when Windows switches to VS2015 by default.
-template <typename T> struct IsMoveOnlyType {
-  template <typename U>
-  static YesType Test(const typename U::MoveOnlyTypeForCPP03*);
-
-  template <typename U>
-  static NoType Test(...);
-
-  static const bool value = sizeof((Test<T>(0))) == sizeof(YesType) &&
-                            !is_const<T>::value;
-};
-
-// Specialization of IsMoveOnlyType so that std::unique_ptr is still considered
-// move-only, even without the sentinel member.
-template <typename T>
-struct IsMoveOnlyType<std::unique_ptr<T>> : std::true_type {};
-
-template <typename>
-struct CallbackParamTraitsForMoveOnlyType;
-
-template <typename>
-struct CallbackParamTraitsForNonMoveOnlyType;
-
-// TODO(tzik): Use a default parameter once MSVS supports variadic templates
-// with default values.
-// http://connect.microsoft.com/VisualStudio/feedbackdetail/view/957801/compilation-error-with-variadic-templates
-//
-// This is a typetraits object that's used to take an argument type, and
-// extract a suitable type for storing and forwarding arguments.
-//
-// In particular, it strips off references, and converts arrays to
-// pointers for storage; and it avoids accidentally trying to create a
-// "reference of a reference" if the argument is a reference type.
-//
-// This array type becomes an issue for storage because we are passing bound
-// parameters by const reference. In this case, we end up passing an actual
-// array type in the initializer list which C++ does not allow.  This will
-// break passing of C-string literals.
-template <typename T>
-struct CallbackParamTraits
-    : std::conditional<IsMoveOnlyType<T>::value,
-         CallbackParamTraitsForMoveOnlyType<T>,
-         CallbackParamTraitsForNonMoveOnlyType<T>>::type {
-};
-
-template <typename T>
-struct CallbackParamTraitsForNonMoveOnlyType {
-  using ForwardType = const T&;
-  using StorageType = T;
 };
 
-// The Storage should almost be impossible to trigger unless someone manually
-// specifies type of the bind parameters.  However, in case they do,
-// this will guard against us accidentally storing a reference parameter.
-//
-// The ForwardType should only be used for unbound arguments.
-template <typename T>
-struct CallbackParamTraitsForNonMoveOnlyType<T&> {
-  using ForwardType = T&;
-  using StorageType = T;
-};
-
-// Note that for array types, we implicitly add a const in the conversion. This
-// means that it is not possible to bind array arguments to functions that take
-// a non-const pointer. Trying to specialize the template based on a "const
-// T[n]" does not seem to match correctly, so we are stuck with this
-// restriction.
-template <typename T, size_t n>
-struct CallbackParamTraitsForNonMoveOnlyType<T[n]> {
-  using ForwardType = const T*;
-  using StorageType = const T*;
-};
-
-// See comment for CallbackParamTraits<T[n]>.
-template <typename T>
-struct CallbackParamTraitsForNonMoveOnlyType<T[]> {
-  using ForwardType = const T*;
-  using StorageType = const T*;
+// CallbackBase<Copyable> is a direct base class of Copyable Callbacks.
+template <>
+class BASE_EXPORT CallbackBase<CopyMode::Copyable>
+    : public CallbackBase<CopyMode::MoveOnly> {
+ public:
+  CallbackBase(const CallbackBase& c);
+  CallbackBase(CallbackBase&& c);
+  CallbackBase& operator=(const CallbackBase& c);
+  CallbackBase& operator=(CallbackBase&& c);
+ protected:
+  explicit CallbackBase(BindStateBase* bind_state)
+      : CallbackBase<CopyMode::MoveOnly>(bind_state) {}
+  ~CallbackBase() {}
 };
 
-// Parameter traits for movable-but-not-copyable scopers.
-//
-// Callback<>/Bind() understands movable-but-not-copyable semantics where
-// the type cannot be copied but can still have its state destructively
-// transferred (aka. moved) to another instance of the same type by calling a
-// helper function.  When used with Bind(), this signifies transferal of the
-// object's state to the target function.
-//
-// For these types, the ForwardType must not be a const reference, or a
-// reference.  A const reference is inappropriate, and would break const
-// correctness, because we are implementing a destructive move.  A non-const
-// reference cannot be used with temporaries which means the result of a
-// function or a cast would not be usable with Callback<> or Bind().
-template <typename T>
-struct CallbackParamTraitsForMoveOnlyType {
-  using ForwardType = T;
-  using StorageType = T;
-};
-
-// CallbackForward() is a very limited simulation of C++11's std::forward()
-// used by the Callback/Bind system for a set of movable-but-not-copyable
-// types.  It is needed because forwarding a movable-but-not-copyable
-// argument to another function requires us to invoke the proper move
-// operator to create a rvalue version of the type.  The supported types are
-// whitelisted below as overloads of the CallbackForward() function. The
-// default template compiles out to be a no-op.
-//
-// In C++11, std::forward would replace all uses of this function.  However, it
-// is impossible to implement a general std::forward without C++11 due to a lack
-// of rvalue references.
-//
-// In addition to Callback/Bind, this is used by PostTaskAndReplyWithResult to
-// simulate std::forward() and forward the result of one Callback as a
-// parameter to another callback. This is to support Callbacks that return
-// the movable-but-not-copyable types whitelisted above.
-template <typename T>
-typename std::enable_if<!IsMoveOnlyType<T>::value, T>::type& CallbackForward(
-    T& t) {
-  return t;
-}
-
-template <typename T>
-typename std::enable_if<IsMoveOnlyType<T>::value, T>::type CallbackForward(
-    T& t) {
-  return std::move(t);
-}
+extern template class CallbackBase<CopyMode::MoveOnly>;
+extern template class CallbackBase<CopyMode::Copyable>;
 
 }  // namespace internal
 }  // namespace base
 
 #endif  // BASE_CALLBACK_INTERNAL_H_
--- a/security/sandbox/chromium/base/compiler_specific.h
+++ b/security/sandbox/chromium/base/compiler_specific.h
@@ -95,16 +95,24 @@
 #if defined(COMPILER_GCC)
 #define NOINLINE __attribute__((noinline))
 #elif defined(COMPILER_MSVC)
 #define NOINLINE __declspec(noinline)
 #else
 #define NOINLINE
 #endif
 
+#if COMPILER_GCC && defined(NDEBUG)
+#define ALWAYS_INLINE inline __attribute__((__always_inline__))
+#elif COMPILER_MSVC && defined(NDEBUG)
+#define ALWAYS_INLINE __forceinline
+#else
+#define ALWAYS_INLINE inline
+#endif
+
 // Specify memory alignment for structs, classes, etc.
 // Use like:
 //   class ALIGNAS(16) MyClass { ... }
 //   ALIGNAS(16) int array[4];
 #if defined(COMPILER_MSVC)
 #define ALIGNAS(byte_alignment) __declspec(align(byte_alignment))
 #elif defined(COMPILER_GCC)
 #define ALIGNAS(byte_alignment) __attribute__((aligned(byte_alignment)))
@@ -164,16 +172,25 @@
 // passing data to another process via shared memory.
 #define MSAN_CHECK_MEM_IS_INITIALIZED(p, size) \
     __msan_check_mem_is_initialized(p, size)
 #else  // MEMORY_SANITIZER
 #define MSAN_UNPOISON(p, size)
 #define MSAN_CHECK_MEM_IS_INITIALIZED(p, size)
 #endif  // MEMORY_SANITIZER
 
+// DISABLE_CFI_PERF -- Disable Control Flow Integrity for perf reasons.
+#if !defined(DISABLE_CFI_PERF)
+#if defined(__clang__) && defined(OFFICIAL_BUILD)
+#define DISABLE_CFI_PERF __attribute__((no_sanitize("cfi")))
+#else
+#define DISABLE_CFI_PERF
+#endif
+#endif
+
 // Macro useful for writing cross-platform function pointers.
 #if !defined(CDECL)
 #if defined(OS_WIN)
 #define CDECL __cdecl
 #else  // defined(OS_WIN)
 #define CDECL
 #endif  // defined(OS_WIN)
 #endif  // !defined(CDECL)
@@ -182,9 +199,25 @@
 #if !defined(UNLIKELY)
 #if defined(COMPILER_GCC)
 #define UNLIKELY(x) __builtin_expect(!!(x), 0)
 #else
 #define UNLIKELY(x) (x)
 #endif  // defined(COMPILER_GCC)
 #endif  // !defined(UNLIKELY)
 
+#if !defined(LIKELY)
+#if defined(COMPILER_GCC)
+#define LIKELY(x) __builtin_expect((x), 1)
+#else
+#define LIKELY(x) (x)
+#endif  // defined(COMPILER_GCC)
+#endif  // !defined(LIKELY)
+
+// Compiler feature-detection.
+// clang.llvm.org/docs/LanguageExtensions.html#has-feature-and-has-extension
+#if defined(__has_feature)
+#define HAS_FEATURE(FEATURE) __has_feature(FEATURE)
+#else
+#define HAS_FEATURE(FEATURE) 0
+#endif
+
 #endif  // BASE_COMPILER_SPECIFIC_H_
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium/base/containers/adapters.h
@@ -0,0 +1,73 @@
+// Copyright 2014 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef BASE_CONTAINERS_ADAPTERS_H_
+#define BASE_CONTAINERS_ADAPTERS_H_
+
+#include <stddef.h>
+
+#include <iterator>
+
+#include "base/macros.h"
+
+namespace base {
+
+namespace internal {
+
+// Internal adapter class for implementing base::Reversed.
+template <typename T>
+class ReversedAdapter {
+ public:
+  using Iterator = decltype(static_cast<T*>(nullptr)->rbegin());
+
+  explicit ReversedAdapter(T& t) : t_(t) {}
+  ReversedAdapter(const ReversedAdapter& ra) : t_(ra.t_) {}
+
+  // TODO(mdempsky): Once we can use C++14 library features, use std::rbegin
+  // and std::rend instead, so we can remove the specialization below.
+  Iterator begin() const { return t_.rbegin(); }
+  Iterator end() const { return t_.rend(); }
+
+ private:
+  T& t_;
+
+  DISALLOW_ASSIGN(ReversedAdapter);
+};
+
+template <typename T, size_t N>
+class ReversedAdapter<T[N]> {
+ public:
+  using Iterator = std::reverse_iterator<T*>;
+
+  explicit ReversedAdapter(T (&t)[N]) : t_(t) {}
+  ReversedAdapter(const ReversedAdapter& ra) : t_(ra.t_) {}
+
+  Iterator begin() const { return Iterator(&t_[N]); }
+  Iterator end() const { return Iterator(&t_[0]); }
+
+ private:
+  T (&t_)[N];
+
+  DISALLOW_ASSIGN(ReversedAdapter);
+};
+
+}  // namespace internal
+
+// Reversed returns a container adapter usable in a range-based "for" statement
+// for iterating a reversible container in reverse order.
+//
+// Example:
+//
+//   std::vector<int> v = ...;
+//   for (int i : base::Reversed(v)) {
+//     // iterates through v from back to front
+//   }
+template <typename T>
+internal::ReversedAdapter<T> Reversed(T& t) {
+  return internal::ReversedAdapter<T>(t);
+}
+
+}  // namespace base
+
+#endif  // BASE_CONTAINERS_ADAPTERS_H_
--- a/security/sandbox/chromium/base/containers/hash_tables.h
+++ b/security/sandbox/chromium/base/containers/hash_tables.h
@@ -1,281 +1,75 @@
 // 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.
-//
-
-//
-// Deal with the differences between Microsoft and GNU implemenations
-// of hash_map. Allows all platforms to use |base::hash_map| and
-// |base::hash_set|.
-//  eg:
-//   base::hash_map<int> my_map;
-//   base::hash_set<int> my_set;
-//
-// NOTE: It is an explicit non-goal of this class to provide a generic hash
-// function for pointers.  If you want to hash a pointers to a particular class,
-// please define the template specialization elsewhere (for example, in its
-// header file) and keep it specific to just pointers to that class.  This is
-// because identity hashes are not desirable for all types that might show up
-// in containers as pointers.
 
 #ifndef BASE_CONTAINERS_HASH_TABLES_H_
 #define BASE_CONTAINERS_HASH_TABLES_H_
 
-#include <stddef.h>
-#include <stdint.h>
-
-#include <utility>
-
-#include "base/strings/string16.h"
-#include "build/build_config.h"
-
-#if defined(COMPILER_MSVC)
+#include <cstddef>
 #include <unordered_map>
 #include <unordered_set>
-
-#define BASE_HASH_NAMESPACE std
+#include <utility>
 
-#elif defined(COMPILER_GCC)
-
-#define BASE_HASH_NAMESPACE base_hash
+#include "base/hash.h"
 
-// This is a hack to disable the gcc 4.4 warning about hash_map and hash_set
-// being deprecated.  We can get rid of this when we upgrade to VS2008 and we
-// can use <tr1/unordered_map> and <tr1/unordered_set>.
-#ifdef __DEPRECATED
-#define CHROME_OLD__DEPRECATED __DEPRECATED
-#undef __DEPRECATED
-#endif
+// This header file is deprecated. Use the corresponding C++11 type
+// instead. https://crbug.com/576864
 
-#include <ext/hash_map>
-#include <ext/hash_set>
-#define BASE_HASH_IMPL_NAMESPACE __gnu_cxx
-
-#include <string>
-
-#ifdef CHROME_OLD__DEPRECATED
-#define __DEPRECATED CHROME_OLD__DEPRECATED
-#undef CHROME_OLD__DEPRECATED
-#endif
+// Use a custom hasher instead.
+#define BASE_HASH_NAMESPACE base_hash
 
 namespace BASE_HASH_NAMESPACE {
 
-// The pre-standard hash behaves like C++11's std::hash, except around pointers.
-// const char* is specialized to hash the C string and hash functions for
-// general T* are missing. Define a BASE_HASH_NAMESPACE::hash which aligns with
-// the C++11 behavior.
-
+// A separate hasher which, by default, forwards to std::hash. This is so legacy
+// uses of BASE_HASH_NAMESPACE with base::hash_map do not interfere with
+// std::hash mid-transition.
 template<typename T>
 struct hash {
-  std::size_t operator()(const T& value) const {
-    return BASE_HASH_IMPL_NAMESPACE::hash<T>()(value);
-  }
-};
-
-template<typename T>
-struct hash<T*> {
-  std::size_t operator()(T* value) const {
-    return BASE_HASH_IMPL_NAMESPACE::hash<uintptr_t>()(
-        reinterpret_cast<uintptr_t>(value));
-  }
+  std::size_t operator()(const T& value) const { return std::hash<T>()(value); }
 };
 
-// The GNU C++ library provides identity hash functions for many integral types,
-// but not for |long long|.  This hash function will truncate if |size_t| is
-// narrower than |long long|.  This is probably good enough for what we will
-// use it for.
-
-#define DEFINE_TRIVIAL_HASH(integral_type) \
-    template<> \
-    struct hash<integral_type> { \
-      std::size_t operator()(integral_type value) const { \
-        return static_cast<std::size_t>(value); \
-      } \
-    }
-
-DEFINE_TRIVIAL_HASH(long long);
-DEFINE_TRIVIAL_HASH(unsigned long long);
-
-#undef DEFINE_TRIVIAL_HASH
-
-// Implement string hash functions so that strings of various flavors can
-// be used as keys in STL maps and sets.  The hash algorithm comes from the
-// GNU C++ library, in <tr1/functional>.  It is duplicated here because GCC
-// versions prior to 4.3.2 are unable to compile <tr1/functional> when RTTI
-// is disabled, as it is in our build.
-
-#define DEFINE_STRING_HASH(string_type) \
-    template<> \
-    struct hash<string_type> { \
-      std::size_t operator()(const string_type& s) const { \
-        std::size_t result = 0; \
-        for (string_type::const_iterator i = s.begin(); i != s.end(); ++i) \
-          result = (result * 131) + *i; \
-        return result; \
-      } \
-    }
-
-DEFINE_STRING_HASH(std::string);
-DEFINE_STRING_HASH(base::string16);
-
-#undef DEFINE_STRING_HASH
-
-}  // namespace BASE_HASH_NAMESPACE
-
-#else  // COMPILER
-#error define BASE_HASH_NAMESPACE for your compiler
-#endif  // COMPILER
-
-namespace base {
-
-// On MSVC, use the C++11 containers.
-#if defined(COMPILER_MSVC)
-
-template<class Key, class T,
-         class Hash = std::hash<Key>,
-         class Pred = std::equal_to<Key>,
-         class Alloc = std::allocator<std::pair<const Key, T>>>
-using hash_map = std::unordered_map<Key, T, Hash, Pred, Alloc>;
-
-template<class Key, class T,
-         class Hash = std::hash<Key>,
-         class Pred = std::equal_to<Key>,
-         class Alloc = std::allocator<std::pair<const Key, T>>>
-using hash_multimap = std::unordered_multimap<Key, T, Hash, Pred, Alloc>;
-
-template<class Key,
-         class Hash = std::hash<Key>,
-         class Pred = std::equal_to<Key>,
-         class Alloc = std::allocator<Key>>
-using hash_multiset = std::unordered_multiset<Key, Hash, Pred, Alloc>;
-
-template<class Key,
-         class Hash = std::hash<Key>,
-         class Pred = std::equal_to<Key>,
-         class Alloc = std::allocator<Key>>
-using hash_set = std::unordered_set<Key, Hash, Pred, Alloc>;
-
-#else  // !COMPILER_MSVC
-
-// Otherwise, use the pre-standard ones, but override the default hash to match
-// C++11.
-template<class Key, class T,
-         class Hash = BASE_HASH_NAMESPACE::hash<Key>,
-         class Pred = std::equal_to<Key>,
-         class Alloc = std::allocator<std::pair<const Key, T>>>
-using hash_map = BASE_HASH_IMPL_NAMESPACE::hash_map<Key, T, Hash, Pred, Alloc>;
-
-template<class Key, class T,
-         class Hash = BASE_HASH_NAMESPACE::hash<Key>,
-         class Pred = std::equal_to<Key>,
-         class Alloc = std::allocator<std::pair<const Key, T>>>
-using hash_multimap =
-    BASE_HASH_IMPL_NAMESPACE::hash_multimap<Key, T, Hash, Pred, Alloc>;
-
-template<class Key,
-         class Hash = BASE_HASH_NAMESPACE::hash<Key>,
-         class Pred = std::equal_to<Key>,
-         class Alloc = std::allocator<Key>>
-using hash_multiset =
-    BASE_HASH_IMPL_NAMESPACE::hash_multiset<Key, Hash, Pred, Alloc>;
-
-template<class Key,
-         class Hash = BASE_HASH_NAMESPACE::hash<Key>,
-         class Pred = std::equal_to<Key>,
-         class Alloc = std::allocator<Key>>
-using hash_set = BASE_HASH_IMPL_NAMESPACE::hash_set<Key, Hash, Pred, Alloc>;
-
-#undef BASE_HASH_IMPL_NAMESPACE
-
-#endif  // COMPILER_MSVC
-
-// Implement hashing for pairs of at-most 32 bit integer values.
-// When size_t is 32 bits, we turn the 64-bit hash code into 32 bits by using
-// multiply-add hashing. This algorithm, as described in
-// Theorem 4.3.3 of the thesis "Über die Komplexität der Multiplikation in
-// eingeschränkten Branchingprogrammmodellen" by Woelfel, is:
-//
-//   h32(x32, y32) = (h64(x32, y32) * rand_odd64 + rand16 * 2^16) % 2^64 / 2^32
-//
-// Contact danakj@chromium.org for any questions.
-inline std::size_t HashInts32(uint32_t value1, uint32_t value2) {
-  uint64_t value1_64 = value1;
-  uint64_t hash64 = (value1_64 << 32) | value2;
-
-  if (sizeof(std::size_t) >= sizeof(uint64_t))
-    return static_cast<std::size_t>(hash64);
-
-  uint64_t odd_random = 481046412LL << 32 | 1025306955LL;
-  uint32_t shift_random = 10121U << 16;
-
-  hash64 = hash64 * odd_random + shift_random;
-  std::size_t high_bits = static_cast<std::size_t>(
-      hash64 >> (8 * (sizeof(uint64_t) - sizeof(std::size_t))));
-  return high_bits;
-}
-
-// Implement hashing for pairs of up-to 64-bit integer values.
-// We use the compound integer hash method to produce a 64-bit hash code, by
-// breaking the two 64-bit inputs into 4 32-bit values:
-// http://opendatastructures.org/versions/edition-0.1d/ods-java/node33.html#SECTION00832000000000000000
-// Then we reduce our result to 32 bits if required, similar to above.
-inline std::size_t HashInts64(uint64_t value1, uint64_t value2) {
-  uint32_t short_random1 = 842304669U;
-  uint32_t short_random2 = 619063811U;
-  uint32_t short_random3 = 937041849U;
-  uint32_t short_random4 = 3309708029U;
-
-  uint32_t value1a = static_cast<uint32_t>(value1 & 0xffffffff);
-  uint32_t value1b = static_cast<uint32_t>((value1 >> 32) & 0xffffffff);
-  uint32_t value2a = static_cast<uint32_t>(value2 & 0xffffffff);
-  uint32_t value2b = static_cast<uint32_t>((value2 >> 32) & 0xffffffff);
-
-  uint64_t product1 = static_cast<uint64_t>(value1a) * short_random1;
-  uint64_t product2 = static_cast<uint64_t>(value1b) * short_random2;
-  uint64_t product3 = static_cast<uint64_t>(value2a) * short_random3;
-  uint64_t product4 = static_cast<uint64_t>(value2b) * short_random4;
-
-  uint64_t hash64 = product1 + product2 + product3 + product4;
-
-  if (sizeof(std::size_t) >= sizeof(uint64_t))
-    return static_cast<std::size_t>(hash64);
-
-  uint64_t odd_random = 1578233944LL << 32 | 194370989LL;
-  uint32_t shift_random = 20591U << 16;
-
-  hash64 = hash64 * odd_random + shift_random;
-  std::size_t high_bits = static_cast<std::size_t>(
-      hash64 >> (8 * (sizeof(uint64_t) - sizeof(std::size_t))));
-  return high_bits;
-}
-
-template<typename T1, typename T2>
-inline std::size_t HashPair(T1 value1, T2 value2) {
-  // This condition is expected to be compile-time evaluated and optimised away
-  // in release builds.
-  if (sizeof(T1) > sizeof(uint32_t) || (sizeof(T2) > sizeof(uint32_t)))
-    return HashInts64(value1, value2);
-
-  return HashInts32(value1, value2);
-}
-
-}  // namespace base
-
-namespace BASE_HASH_NAMESPACE {
-
-// Implement methods for hashing a pair of integers, so they can be used as
-// keys in STL containers.
-
-template<typename Type1, typename Type2>
-struct hash<std::pair<Type1, Type2> > {
+// Use base::IntPairHash from base/hash.h as a custom hasher instead.
+template <typename Type1, typename Type2>
+struct hash<std::pair<Type1, Type2>> {
   std::size_t operator()(std::pair<Type1, Type2> value) const {
-    return base::HashPair(value.first, value.second);
+    return base::HashInts(value.first, value.second);
   }
 };
 
 }  // namespace BASE_HASH_NAMESPACE
 
-#undef DEFINE_PAIR_HASH_FUNCTION_START
-#undef DEFINE_PAIR_HASH_FUNCTION_END
+namespace base {
+
+// Use std::unordered_map instead.
+template <class Key,
+          class T,
+          class Hash = BASE_HASH_NAMESPACE::hash<Key>,
+          class Pred = std::equal_to<Key>,
+          class Alloc = std::allocator<std::pair<const Key, T>>>
+using hash_map = std::unordered_map<Key, T, Hash, Pred, Alloc>;
+
+// Use std::unordered_multimap instead.
+template <class Key,
+          class T,
+          class Hash = BASE_HASH_NAMESPACE::hash<Key>,
+          class Pred = std::equal_to<Key>,
+          class Alloc = std::allocator<std::pair<const Key, T>>>
+using hash_multimap = std::unordered_multimap<Key, T, Hash, Pred, Alloc>;
+
+// Use std::unordered_multiset instead.
+template <class Key,
+          class Hash = BASE_HASH_NAMESPACE::hash<Key>,
+          class Pred = std::equal_to<Key>,
+          class Alloc = std::allocator<Key>>
+using hash_multiset = std::unordered_multiset<Key, Hash, Pred, Alloc>;
+
+// Use std::unordered_set instead.
+template <class Key,
+          class Hash = BASE_HASH_NAMESPACE::hash<Key>,
+          class Pred = std::equal_to<Key>,
+          class Alloc = std::allocator<Key>>
+using hash_set = std::unordered_set<Key, Hash, Pred, Alloc>;
+
+}  // namespace base
 
 #endif  // BASE_CONTAINERS_HASH_TABLES_H_
--- a/security/sandbox/chromium/base/cpu.cc
+++ b/security/sandbox/chromium/base/cpu.cc
@@ -2,23 +2,21 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
 #include "base/cpu.h"
 
 #include <limits.h>
 #include <stddef.h>
 #include <stdint.h>
-#include <stdlib.h>
 #include <string.h>
 
 #include <algorithm>
 
 #include "base/macros.h"
-#include "base/strings/string_piece.h"
 #include "build/build_config.h"
 
 #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
 #include "base/files/file_util.h"
 #include "base/lazy_instance.h"
 #endif
 
 #if defined(ARCH_CPU_X86_FAMILY)
@@ -40,21 +38,21 @@ CPU::CPU()
     ext_family_(0),
     has_mmx_(false),
     has_sse_(false),
     has_sse2_(false),
     has_sse3_(false),
     has_ssse3_(false),
     has_sse41_(false),
     has_sse42_(false),
+    has_popcnt_(false),
     has_avx_(false),
     has_avx2_(false),
     has_aesni_(false),
     has_non_stop_time_stamp_counter_(false),
-    has_broken_neon_(false),
     cpu_vendor_("unknown") {
   Initialize();
 }
 
 namespace {
 
 #if defined(ARCH_CPU_X86_FAMILY)
 #ifndef _MSC_VER
@@ -94,101 +92,47 @@ uint64_t _xgetbv(uint32_t xcr) {
 }
 
 #endif  // !_MSC_VER
 #endif  // ARCH_CPU_X86_FAMILY
 
 #if defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
 class LazyCpuInfoValue {
  public:
-  LazyCpuInfoValue() : has_broken_neon_(false) {
+  LazyCpuInfoValue() {
     // This function finds the value from /proc/cpuinfo under the key "model
     // name" or "Processor". "model name" is used in Linux 3.8 and later (3.7
     // and later for arm64) and is shown once per CPU. "Processor" is used in
     // earler versions and is shown only once at the top of /proc/cpuinfo
     // regardless of the number CPUs.
     const char kModelNamePrefix[] = "model name\t: ";
     const char kProcessorPrefix[] = "Processor\t: ";
 
-    // This function also calculates whether we believe that this CPU has a
-    // broken NEON unit based on these fields from cpuinfo:
-    unsigned implementer = 0, architecture = 0, variant = 0, part = 0,
-             revision = 0;
-    const struct {
-      const char key[17];
-      unsigned int* result;
-    } kUnsignedValues[] = {
-      {"CPU implementer", &implementer},
-      {"CPU architecture", &architecture},
-      {"CPU variant", &variant},
-      {"CPU part", &part},
-      {"CPU revision", &revision},
-    };
-
     std::string contents;
     ReadFileToString(FilePath("/proc/cpuinfo"), &contents);
     DCHECK(!contents.empty());
     if (contents.empty()) {
       return;
     }
 
     std::istringstream iss(contents);
     std::string line;
     while (std::getline(iss, line)) {
       if (brand_.empty() &&
           (line.compare(0, strlen(kModelNamePrefix), kModelNamePrefix) == 0 ||
            line.compare(0, strlen(kProcessorPrefix), kProcessorPrefix) == 0)) {
         brand_.assign(line.substr(strlen(kModelNamePrefix)));
       }
-
-      for (size_t i = 0; i < arraysize(kUnsignedValues); i++) {
-        const char *key = kUnsignedValues[i].key;
-        const size_t len = strlen(key);
-
-        if (line.compare(0, len, key) == 0 &&
-            line.size() >= len + 1 &&
-            (line[len] == '\t' || line[len] == ' ' || line[len] == ':')) {
-          size_t colon_pos = line.find(':', len);
-          if (colon_pos == std::string::npos) {
-            continue;
-          }
-
-          const StringPiece line_sp(line);
-          StringPiece value_sp = line_sp.substr(colon_pos + 1);
-          while (!value_sp.empty() &&
-                 (value_sp[0] == ' ' || value_sp[0] == '\t')) {
-            value_sp = value_sp.substr(1);
-          }
-
-          // The string may have leading "0x" or not, so we use strtoul to
-          // handle that.
-          char* endptr;
-          std::string value(value_sp.as_string());
-          unsigned long int result = strtoul(value.c_str(), &endptr, 0);
-          if (*endptr == 0 && result <= UINT_MAX) {
-            *kUnsignedValues[i].result = result;
-          }
-        }
-      }
     }
-
-    has_broken_neon_ =
-      implementer == 0x51 &&
-      architecture == 7 &&
-      variant == 1 &&
-      part == 0x4d &&
-      revision == 0;
   }
 
   const std::string& brand() const { return brand_; }
-  bool has_broken_neon() const { return has_broken_neon_; }
 
  private:
   std::string brand_;
-  bool has_broken_neon_;
   DISALLOW_COPY_AND_ASSIGN(LazyCpuInfoValue);
 };
 
 base::LazyInstance<LazyCpuInfoValue>::Leaky g_lazy_cpuinfo =
     LAZY_INSTANCE_INITIALIZER;
 
 #endif  // defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) ||
         // defined(OS_LINUX))
@@ -229,16 +173,18 @@ void CPU::Initialize() {
     ext_family_ = (cpu_info[0] >> 20) & 0xff;
     has_mmx_ =   (cpu_info[3] & 0x00800000) != 0;
     has_sse_ =   (cpu_info[3] & 0x02000000) != 0;
     has_sse2_ =  (cpu_info[3] & 0x04000000) != 0;
     has_sse3_ =  (cpu_info[2] & 0x00000001) != 0;
     has_ssse3_ = (cpu_info[2] & 0x00000200) != 0;
     has_sse41_ = (cpu_info[2] & 0x00080000) != 0;
     has_sse42_ = (cpu_info[2] & 0x00100000) != 0;
+    has_popcnt_ = (cpu_info[2] & 0x00800000) != 0;
+
     // AVX instructions will generate an illegal instruction exception unless
     //   a) they are supported by the CPU,
     //   b) XSAVE is supported by the CPU and
     //   c) XSAVE is enabled by the kernel.
     // See http://software.intel.com/en-us/blogs/2011/04/14/is-avx-enabled
     //
     // In addition, we have observed some crashes with the xgetbv instruction
     // even after following Intel's example code. (See crbug.com/375968.)
@@ -272,17 +218,16 @@ void CPU::Initialize() {
 
   const int parameter_containing_non_stop_time_stamp_counter = 0x80000007;
   if (max_parameter >= parameter_containing_non_stop_time_stamp_counter) {
     __cpuid(cpu_info, parameter_containing_non_stop_time_stamp_counter);
     has_non_stop_time_stamp_counter_ = (cpu_info[3] & (1 << 8)) != 0;
   }
 #elif defined(ARCH_CPU_ARM_FAMILY) && (defined(OS_ANDROID) || defined(OS_LINUX))
   cpu_brand_.assign(g_lazy_cpuinfo.Get().brand());
-  has_broken_neon_ = g_lazy_cpuinfo.Get().has_broken_neon();
 #endif
 }
 
 CPU::IntelMicroArchitecture CPU::GetIntelMicroArchitecture() const {
   if (has_avx2()) return AVX2;
   if (has_avx()) return AVX;
   if (has_sse42()) return SSE42;
   if (has_sse41()) return SSE41;
--- a/security/sandbox/chromium/base/cpu.h
+++ b/security/sandbox/chromium/base/cpu.h
@@ -41,26 +41,23 @@ class BASE_EXPORT CPU {
   int extended_family() const { return ext_family_; }
   bool has_mmx() const { return has_mmx_; }
   bool has_sse() const { return has_sse_; }
   bool has_sse2() const { return has_sse2_; }
   bool has_sse3() const { return has_sse3_; }
   bool has_ssse3() const { return has_ssse3_; }
   bool has_sse41() const { return has_sse41_; }
   bool has_sse42() const { return has_sse42_; }
+  bool has_popcnt() const { return has_popcnt_; }
   bool has_avx() const { return has_avx_; }
   bool has_avx2() const { return has_avx2_; }
   bool has_aesni() const { return has_aesni_; }
   bool has_non_stop_time_stamp_counter() const {
     return has_non_stop_time_stamp_counter_;
   }
-  // has_broken_neon is only valid on ARM chips. If true, it indicates that we
-  // believe that the NEON unit on the current CPU is flawed and cannot execute
-  // some code. See https://code.google.com/p/chromium/issues/detail?id=341598
-  bool has_broken_neon() const { return has_broken_neon_; }
 
   IntelMicroArchitecture GetIntelMicroArchitecture() const;
   const std::string& cpu_brand() const { return cpu_brand_; }
 
  private:
   // Query the processor for CPUID information.
   void Initialize();
 
@@ -73,20 +70,20 @@ class BASE_EXPORT CPU {
   int ext_family_;
   bool has_mmx_;
   bool has_sse_;
   bool has_sse2_;
   bool has_sse3_;
   bool has_ssse3_;
   bool has_sse41_;
   bool has_sse42_;
+  bool has_popcnt_;
   bool has_avx_;
   bool has_avx2_;
   bool has_aesni_;
   bool has_non_stop_time_stamp_counter_;
-  bool has_broken_neon_;
   std::string cpu_vendor_;
   std::string cpu_brand_;
 };
 
 }  // namespace base
 
 #endif  // BASE_CPU_H_
--- a/security/sandbox/chromium/base/debug/profiler.cc
+++ b/security/sandbox/chromium/base/debug/profiler.cc
@@ -8,16 +8,17 @@
 
 #include "base/debug/debugging_flags.h"
 #include "base/process/process_handle.h"
 #include "base/strings/string_number_conversions.h"
 #include "base/strings/string_util.h"
 #include "build/build_config.h"
 
 #if defined(OS_WIN)
+#include "base/win/current_module.h"
 #include "base/win/pe_image.h"
 #endif  // defined(OS_WIN)
 
 // TODO(peria): Enable profiling on Windows.
 #if BUILDFLAG(ENABLE_PROFILING) && !defined(NO_TCMALLOC) && !defined(OS_WIN)
 #include "third_party/tcmalloc/chromium/src/gperftools/profiler.h"
 #endif
 
@@ -51,16 +52,20 @@ void FlushProfiling() {
 bool BeingProfiled() {
   return ProfilingIsEnabledForAllThreads();
 }
 
 void RestartProfilingAfterFork() {
   ProfilerRegisterThread();
 }
 
+bool IsProfilingSupported() {
+  return true;
+}
+
 #else
 
 void StartProfiling(const std::string& name) {
 }
 
 void StopProfiling() {
 }
 
@@ -69,16 +74,20 @@ void FlushProfiling() {
 
 bool BeingProfiled() {
   return false;
 }
 
 void RestartProfilingAfterFork() {
 }
 
+bool IsProfilingSupported() {
+  return false;
+}
+
 #endif
 
 #if !defined(OS_WIN)
 
 bool IsBinaryInstrumented() {
   return false;
 }
 
@@ -95,31 +104,27 @@ AddDynamicSymbol GetProfilerAddDynamicSy
 }
 
 MoveDynamicSymbol GetProfilerMoveDynamicSymbolFunc() {
   return NULL;
 }
 
 #else  // defined(OS_WIN)
 
-// http://blogs.msdn.com/oldnewthing/archive/2004/10/25/247180.aspx
-extern "C" IMAGE_DOS_HEADER __ImageBase;
-
 bool IsBinaryInstrumented() {
   enum InstrumentationCheckState {
     UNINITIALIZED,
     INSTRUMENTED_IMAGE,
     NON_INSTRUMENTED_IMAGE,
   };
 
   static InstrumentationCheckState state = UNINITIALIZED;
 
   if (state == UNINITIALIZED) {
-    HMODULE this_module = reinterpret_cast<HMODULE>(&__ImageBase);
-    base::win::PEImage image(this_module);
+    base::win::PEImage image(CURRENT_MODULE());
 
     // Check to be sure our image is structured as we'd expect.
     DCHECK(image.VerifyMagic());
 
     // Syzygy-instrumented binaries contain a PE image section named ".thunks",
     // and all Syzygy-modified binaries contain the ".syzygy" image section.
     // This is a very fast check, as it only looks at the image header.
     if ((image.GetImageSectionHeaderByName(".thunks") != NULL) &&
@@ -144,18 +149,18 @@ struct FunctionSearchContext {
 // Callback function to PEImage::EnumImportChunks.
 bool FindResolutionFunctionInImports(
     const base::win::PEImage &image, const char* module_name,
     PIMAGE_THUNK_DATA unused_name_table, PIMAGE_THUNK_DATA import_address_table,
     PVOID cookie) {
   FunctionSearchContext* context =
       reinterpret_cast<FunctionSearchContext*>(cookie);
 
-  DCHECK_NE(static_cast<FunctionSearchContext*>(NULL), context);
-  DCHECK_EQ(static_cast<FARPROC>(NULL), context->function);
+  DCHECK(context);
+  DCHECK(!context->function);
 
   // Our import address table contains pointers to the functions we import
   // at this point. Let's retrieve the first such function and use it to
   // find the module this import was resolved to by the loader.
   const wchar_t* function_in_module =
       reinterpret_cast<const wchar_t*>(import_address_table->u1.Function);
 
   // Retrieve the module by a function in the module.
@@ -179,18 +184,17 @@ bool FindResolutionFunctionInImports(
   return true;
 }
 
 template <typename FunctionType>
 FunctionType FindFunctionInImports(const char* function_name) {
   if (!IsBinaryInstrumented())
     return NULL;
 
-  HMODULE this_module = reinterpret_cast<HMODULE>(&__ImageBase);
-  base::win::PEImage image(this_module);
+  base::win::PEImage image(CURRENT_MODULE());
 
   FunctionSearchContext ctx = { function_name, NULL };
   image.EnumImportChunks(FindResolutionFunctionInImports, &ctx);
 
   return reinterpret_cast<FunctionType>(ctx.function);
 }
 
 }  // namespace
--- a/security/sandbox/chromium/base/debug/profiler.h
+++ b/security/sandbox/chromium/base/debug/profiler.h
@@ -33,16 +33,19 @@ BASE_EXPORT void FlushProfiling();
 BASE_EXPORT bool BeingProfiled();
 
 // Reset profiling after a fork, which disables timers.
 BASE_EXPORT void RestartProfilingAfterFork();
 
 // Returns true iff this executable is instrumented with the Syzygy profiler.
 BASE_EXPORT bool IsBinaryInstrumented();
 
+// Returns true iff this executable supports profiling.
+BASE_EXPORT bool IsProfilingSupported();
+
 // There's a class of profilers that use "return address swizzling" to get a
 // hook on function exits. This class of profilers uses some form of entry hook,
 // like e.g. binary instrumentation, or a compiler flag, that calls a hook each
 // time a function is invoked. The hook then switches the return address on the
 // stack for the address of an exit hook function, and pushes the original
 // return address to a shadow stack of some type. When in due course the CPU
 // executes a return to the exit hook, the exit hook will do whatever work it
 // does on function exit, then arrange to return to the original return address.
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium/base/environment.h
@@ -0,0 +1,90 @@
+// 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_ENVIRONMENT_H_
+#define BASE_ENVIRONMENT_H_
+
+#include <map>
+#include <memory>
+#include <string>
+
+#include "base/base_export.h"
+#include "base/strings/string16.h"
+#include "base/strings/string_piece.h"
+#include "build/build_config.h"
+
+namespace base {
+
+namespace env_vars {
+
+#if defined(OS_POSIX)
+BASE_EXPORT extern const char kHome[];
+#endif
+
+}  // namespace env_vars
+
+class BASE_EXPORT Environment {
+ public:
+  virtual ~Environment();
+
+  // Returns the appropriate platform-specific instance.
+  static std::unique_ptr<Environment> Create();
+
+  // Gets an environment variable's value and stores it in |result|.
+  // Returns false if the key is unset.
+  virtual bool GetVar(StringPiece variable_name, std::string* result) = 0;
+
+  // Syntactic sugar for GetVar(variable_name, nullptr);
+  virtual bool HasVar(StringPiece variable_name);
+
+  // Returns true on success, otherwise returns false.
+  virtual bool SetVar(StringPiece variable_name,
+                      const std::string& new_value) = 0;
+
+  // Returns true on success, otherwise returns false.
+  virtual bool UnSetVar(StringPiece variable_name) = 0;
+};
+
+
+#if defined(OS_WIN)
+
+typedef string16 NativeEnvironmentString;
+typedef std::map<NativeEnvironmentString, NativeEnvironmentString>
+    EnvironmentMap;
+
+// Returns a modified environment vector constructed from the given environment
+// and the list of changes given in |changes|. Each key in the environment is
+// matched against the first element of the pairs. In the event of a match, the
+// value is replaced by the second of the pair, unless the second is empty, in
+// which case the key-value is removed.
+//
+// This Windows version takes and returns a Windows-style environment block
+// which is a concatenated list of null-terminated 16-bit strings. The end is
+// marked by a double-null terminator. The size of the returned string will
+// include the terminators.
+BASE_EXPORT string16 AlterEnvironment(const wchar_t* env,
+                                      const EnvironmentMap& changes);
+
+#elif defined(OS_POSIX)
+
+typedef std::string NativeEnvironmentString;
+typedef std::map<NativeEnvironmentString, NativeEnvironmentString>
+    EnvironmentMap;
+
+// See general comments for the Windows version above.
+//
+// This Posix version takes and returns a Posix-style environment block, which
+// is a null-terminated list of pointers to null-terminated strings. The
+// returned array will have appended to it the storage for the array itself so
+// there is only one pointer to manage, but this means that you can't copy the
+// array without keeping the original around.
+BASE_EXPORT std::unique_ptr<char* []> AlterEnvironment(
+    const char* const* env,
+    const EnvironmentMap& changes);
+
+#endif
+
+}  // namespace base
+
+#endif  // BASE_ENVIRONMENT_H_
--- a/security/sandbox/chromium/base/files/file_path.h
+++ b/security/sandbox/chromium/base/files/file_path.h
@@ -133,16 +133,17 @@
 #elif defined(OS_WIN)
 #define PRIsFP "ls"
 #endif  // OS_WIN
 
 namespace base {
 
 class Pickle;
 class PickleIterator;
+class PickleSizer;
 
 // An abstraction to isolate users from the differences between native
 // pathnames on different platforms.
 class BASE_EXPORT FilePath {
  public:
 #if defined(OS_POSIX)
   // On most platforms, native pathnames are char arrays, and the encoding
   // may or may not be specified.  On Mac OS X, native pathnames are encoded
@@ -367,21 +368,22 @@ class BASE_EXPORT FilePath {
   // Returns a FilePath object from a path name in UTF-8. This function
   // should only be used for cases where you are sure that the input
   // string is UTF-8.
   //
   // Like AsUTF8Unsafe(), this function is unsafe. This function
   // internally calls SysWideToNativeMB() on POSIX systems other than Mac
   // and Chrome OS, to mitigate the encoding issue. See the comment at
   // AsUTF8Unsafe() for details.
-  static FilePath FromUTF8Unsafe(const std::string& utf8);
+  static FilePath FromUTF8Unsafe(StringPiece utf8);
 
   // Similar to FromUTF8Unsafe, but accepts UTF-16 instead.
-  static FilePath FromUTF16Unsafe(const string16& utf16);
+  static FilePath FromUTF16Unsafe(StringPiece16 utf16);
 
+  void GetSizeForPickle(PickleSizer* sizer) const;
   void WriteToPickle(Pickle* pickle) const;
   bool ReadFromPickle(PickleIterator* iter);
 
   // Normalize all path separators to backslash on Windows
   // (if FILE_PATH_USES_WIN_SEPARATORS is true), or do nothing on POSIX systems.
   FilePath NormalizePathSeparators() const;
 
   // Normalize all path separattors to given type on Windows
--- a/security/sandbox/chromium/base/guid.h
+++ b/security/sandbox/chromium/base/guid.h
@@ -5,29 +5,39 @@
 #ifndef BASE_GUID_H_
 #define BASE_GUID_H_
 
 #include <stdint.h>
 
 #include <string>
 
 #include "base/base_export.h"
+#include "base/strings/string_piece.h"
 #include "build/build_config.h"
 
 namespace base {
 
-// Generate a 128-bit random GUID of the form: "%08X-%04X-%04X-%04X-%012llX".
+// Generate a 128-bit (pseudo) random GUID in the form of version 4 as described
+// in RFC 4122, section 4.4.
+// The format of GUID version 4 must be xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx,
+// where y is one of [8, 9, A, B].
+// The hexadecimal values "a" through "f" are output as lower case characters.
 // If GUID generation fails an empty string is returned.
-// The POSIX implementation uses pseudo random number generation to create
-// the GUID.  The Windows implementation uses system services.
 BASE_EXPORT std::string GenerateGUID();
 
-// Returns true if the input string conforms to the GUID format.
-BASE_EXPORT bool IsValidGUID(const std::string& guid);
+// Returns true if the input string conforms to the version 4 GUID format.
+// Note that this does NOT check if the hexadecimal values "a" through "f"
+// are in lower case characters, as Version 4 RFC says onput they're
+// case insensitive. (Use IsValidGUIDOutputString for checking if the
+// given string is valid output string)
+BASE_EXPORT bool IsValidGUID(const base::StringPiece& guid);
 
-#if defined(OS_POSIX)
+// Returns true if the input string is valid version 4 GUID output string.
+// This also checks if the hexadecimal values "a" through "f" are in lower
+// case characters.
+BASE_EXPORT bool IsValidGUIDOutputString(const base::StringPiece& guid);
+
 // For unit testing purposes only.  Do not use outside of tests.
 BASE_EXPORT std::string RandomDataToGUIDString(const uint64_t bytes[2]);
-#endif
 
 }  // namespace base
 
 #endif  // BASE_GUID_H_
--- a/security/sandbox/chromium/base/hash.cc
+++ b/security/sandbox/chromium/base/hash.cc
@@ -6,13 +6,17 @@
 
 // Definition in base/third_party/superfasthash/superfasthash.c. (Third-party
 // code did not come with its own header file, so declaring the function here.)
 // Note: This algorithm is also in Blink under Source/wtf/StringHasher.h.
 extern "C" uint32_t SuperFastHash(const char* data, int len);
 
 namespace base {
 
-uint32_t SuperFastHash(const char* data, int len) {
-  return ::SuperFastHash(data, len);
+uint32_t SuperFastHash(const char* data, size_t length) {
+  if (length > static_cast<size_t>(std::numeric_limits<int>::max())) {
+    NOTREACHED();
+    return 0;
+  }
+  return ::SuperFastHash(data, static_cast<int>(length));
 }
 
 }  // namespace base
--- a/security/sandbox/chromium/base/hash.h
+++ b/security/sandbox/chromium/base/hash.h
@@ -5,36 +5,114 @@
 #ifndef BASE_HASH_H_
 #define BASE_HASH_H_
 
 #include <stddef.h>
 #include <stdint.h>
 
 #include <limits>
 #include <string>
+#include <utility>
 
 #include "base/base_export.h"
 #include "base/logging.h"
 
 namespace base {
 
 // WARNING: This hash function should not be used for any cryptographic purpose.
-BASE_EXPORT uint32_t SuperFastHash(const char* data, int len);
+BASE_EXPORT uint32_t SuperFastHash(const char* data, size_t length);
 
 // Computes a hash of a memory buffer |data| of a given |length|.
 // WARNING: This hash function should not be used for any cryptographic purpose.
 inline uint32_t Hash(const char* data, size_t length) {
-  if (length > static_cast<size_t>(std::numeric_limits<int>::max())) {
-    NOTREACHED();
-    return 0;
-  }
-  return SuperFastHash(data, static_cast<int>(length));
+  return SuperFastHash(data, length);
 }
 
 // Computes a hash of a string |str|.
 // WARNING: This hash function should not be used for any cryptographic purpose.
 inline uint32_t Hash(const std::string& str) {
   return Hash(str.data(), str.size());
 }
 
+// Implement hashing for pairs of at-most 32 bit integer values.
+// When size_t is 32 bits, we turn the 64-bit hash code into 32 bits by using
+// multiply-add hashing. This algorithm, as described in
+// Theorem 4.3.3 of the thesis "Über die Komplexität der Multiplikation in
+// eingeschränkten Branchingprogrammmodellen" by Woelfel, is:
+//
+//   h32(x32, y32) = (h64(x32, y32) * rand_odd64 + rand16 * 2^16) % 2^64 / 2^32
+//
+// Contact danakj@chromium.org for any questions.
+inline size_t HashInts32(uint32_t value1, uint32_t value2) {
+  uint64_t value1_64 = value1;
+  uint64_t hash64 = (value1_64 << 32) | value2;
+
+  if (sizeof(size_t) >= sizeof(uint64_t))
+    return static_cast<size_t>(hash64);
+
+  uint64_t odd_random = 481046412LL << 32 | 1025306955LL;
+  uint32_t shift_random = 10121U << 16;
+
+  hash64 = hash64 * odd_random + shift_random;
+  size_t high_bits =
+      static_cast<size_t>(hash64 >> (8 * (sizeof(uint64_t) - sizeof(size_t))));
+  return high_bits;
+}
+
+// Implement hashing for pairs of up-to 64-bit integer values.
+// We use the compound integer hash method to produce a 64-bit hash code, by
+// breaking the two 64-bit inputs into 4 32-bit values:
+// http://opendatastructures.org/versions/edition-0.1d/ods-java/node33.html#SECTION00832000000000000000
+// Then we reduce our result to 32 bits if required, similar to above.
+inline size_t HashInts64(uint64_t value1, uint64_t value2) {
+  uint32_t short_random1 = 842304669U;
+  uint32_t short_random2 = 619063811U;
+  uint32_t short_random3 = 937041849U;
+  uint32_t short_random4 = 3309708029U;
+
+  uint32_t value1a = static_cast<uint32_t>(value1 & 0xffffffff);
+  uint32_t value1b = static_cast<uint32_t>((value1 >> 32) & 0xffffffff);
+  uint32_t value2a = static_cast<uint32_t>(value2 & 0xffffffff);
+  uint32_t value2b = static_cast<uint32_t>((value2 >> 32) & 0xffffffff);
+
+  uint64_t product1 = static_cast<uint64_t>(value1a) * short_random1;
+  uint64_t product2 = static_cast<uint64_t>(value1b) * short_random2;
+  uint64_t product3 = static_cast<uint64_t>(value2a) * short_random3;
+  uint64_t product4 = static_cast<uint64_t>(value2b) * short_random4;
+
+  uint64_t hash64 = product1 + product2 + product3 + product4;
+
+  if (sizeof(size_t) >= sizeof(uint64_t))
+    return static_cast<size_t>(hash64);
+
+  uint64_t odd_random = 1578233944LL << 32 | 194370989LL;
+  uint32_t shift_random = 20591U << 16;
+
+  hash64 = hash64 * odd_random + shift_random;
+  size_t high_bits =
+      static_cast<size_t>(hash64 >> (8 * (sizeof(uint64_t) - sizeof(size_t))));
+  return high_bits;
+}
+
+template <typename T1, typename T2>
+inline size_t HashInts(T1 value1, T2 value2) {
+  // This condition is expected to be compile-time evaluated and optimised away
+  // in release builds.
+  if (sizeof(T1) > sizeof(uint32_t) || (sizeof(T2) > sizeof(uint32_t)))
+    return HashInts64(value1, value2);
+
+  return HashInts32(value1, value2);
+}
+
+// A templated hasher for pairs of integer types.
+template <typename T>
+struct IntPairHash;
+
+template <typename Type1, typename Type2>
+struct IntPairHash<std::pair<Type1, Type2>> {
+  size_t operator()(std::pair<Type1, Type2> value) const {
+    return HashInts(value.first, value.second);
+  }
+};
+
 }  // namespace base
 
 #endif  // BASE_HASH_H_
--- a/security/sandbox/chromium/base/lazy_instance.h
+++ b/security/sandbox/chromium/base/lazy_instance.h
@@ -50,17 +50,17 @@
 // initialization.
 #define LAZY_INSTANCE_INITIALIZER {0}
 
 namespace base {
 
 template <typename Type>
 struct DefaultLazyInstanceTraits {
   static const bool kRegisterOnExit = true;
-#ifndef NDEBUG
+#if DCHECK_IS_ON()
   static const bool kAllowedToAccessOnNonjoinableThread = false;
 #endif
 
   static Type* New(void* instance) {
     DCHECK_EQ(reinterpret_cast<uintptr_t>(instance) & (ALIGNOF(Type) - 1), 0u)
         << ": Bad boy, the buffer passed to placement new is not aligned!\n"
         "This may break some stuff like SSE-based optimizations assuming the "
         "<Type> objects are word aligned.";
@@ -84,30 +84,30 @@ namespace internal {
 // base::LazyInstance<T, base::internal::LeakyLazyInstanceTraits<T> >
 // my_leaky_lazy_instance;
 // (especially when T is MyLongTypeNameImplClientHolderFactory).
 // Only use this internal::-qualified verbose form to extend this traits class
 // (depending on its implementation details).
 template <typename Type>
 struct LeakyLazyInstanceTraits {
   static const bool kRegisterOnExit = false;
-#ifndef NDEBUG
+#if DCHECK_IS_ON()
   static const bool kAllowedToAccessOnNonjoinableThread = true;
 #endif
 
   static Type* New(void* instance) {
     ANNOTATE_SCOPED_MEMORY_LEAK;
     return DefaultLazyInstanceTraits<Type>::New(instance);
   }
   static void Delete(Type* instance) {
   }
 };
 
 // Our AtomicWord doubles as a spinlock, where a value of
-// kBeingCreatedMarker means the spinlock is being held for creation.
+// kLazyInstanceStateCreating means the spinlock is being held for creation.
 static const subtle::AtomicWord kLazyInstanceStateCreating = 1;
 
 // Check if instance needs to be created. If so return true otherwise
 // if another thread has beat us, wait for instance to be created and
 // return false.
 BASE_EXPORT bool NeedsLazyInstance(subtle::AtomicWord* state);
 
 // After creating an instance, call this to register the dtor to be called
@@ -133,17 +133,17 @@ class LazyInstance {
   // instances.
   typedef LazyInstance<Type, internal::LeakyLazyInstanceTraits<Type> > Leaky;
 
   Type& Get() {
     return *Pointer();
   }
 
   Type* Pointer() {
-#ifndef NDEBUG
+#if DCHECK_IS_ON()
     // Avoid making TLS lookup on release builds.
     if (!Traits::kAllowedToAccessOnNonjoinableThread)
       ThreadRestrictions::AssertSingletonAllowed();
 #endif
     // If any bit in the created mask is true, the instance has already been
     // fully constructed.
     static const subtle::AtomicWord kLazyInstanceCreatedMask =
         ~internal::kLazyInstanceStateCreating;
--- a/security/sandbox/chromium/base/location.h
+++ b/security/sandbox/chromium/base/location.h
@@ -6,17 +6,17 @@
 #define BASE_LOCATION_H_
 
 #include <stddef.h>
 
 #include <cassert>
 #include <string>
 
 #include "base/base_export.h"
-#include "base/containers/hash_tables.h"
+#include "base/hash.h"
 
 namespace tracked_objects {
 
 // Location provides basic info where of an object was constructed, or was
 // significantly brought to life.
 class BASE_EXPORT Location {
  public:
   // Constructor should be called with a long-lived char*, such as __FILE__.
@@ -54,17 +54,17 @@ class BASE_EXPORT Location {
       // Compute the hash value using file name pointer and line number.
       // No need to use |function_name_| since the other two fields uniquely
       // identify this location.
 
       // The file name will always be uniquely identified by its pointer since
       // it comes from __FILE__, so no need to check the contents of the string.
       // See the definition of FROM_HERE in location.h, and how it is used
       // elsewhere.
-      return base::HashPair(reinterpret_cast<uintptr_t>(location.file_name()),
+      return base::HashInts(reinterpret_cast<uintptr_t>(location.file_name()),
                             location.line_number());
     }
   };
 
   // Translate the some of the state in this instance into a human readable
   // string with HTML characters in the function names escaped, and append that
   // string to |output|.  Inclusion of the file_name_ and function_name_ are
   // optional, and controlled by the boolean arguments.
@@ -92,17 +92,17 @@ struct BASE_EXPORT LocationSnapshot {
   std::string file_name;
   std::string function_name;
   int line_number;
 };
 
 BASE_EXPORT const void* GetProgramCounter();
 
 // Define a macro to record the current source location.
-#define FROM_HERE FROM_HERE_WITH_EXPLICIT_FUNCTION(__FUNCTION__)
+#define FROM_HERE FROM_HERE_WITH_EXPLICIT_FUNCTION(__func__)
 
 #define FROM_HERE_WITH_EXPLICIT_FUNCTION(function_name)                        \
     ::tracked_objects::Location(function_name,                                 \
                                 __FILE__,                                      \
                                 __LINE__,                                      \
                                 ::tracked_objects::GetProgramCounter())
 
 }  // namespace tracked_objects
--- a/security/sandbox/chromium/base/logging.h
+++ b/security/sandbox/chromium/base/logging.h
@@ -6,20 +6,23 @@
 #define BASE_LOGGING_H_
 
 #include <stddef.h>
 
 #include <cassert>
 #include <cstring>
 #include <sstream>
 #include <string>
+#include <type_traits>
+#include <utility>
 
 #include "base/base_export.h"
 #include "base/debug/debugger.h"
 #include "base/macros.h"
+#include "base/template_util.h"
 #include "build/build_config.h"
 
 //
 // Optional message capabilities
 // -----------------------------
 // Assertion failed messages and fatal errors are displayed in a dialog box
 // before the application exits. However, running this UI creates a message
 // loop, which causes application messages to be processed and potentially
@@ -301,25 +304,26 @@ const LogSeverity LOG_DFATAL = LOG_ERROR
 #else
 const LogSeverity LOG_DFATAL = LOG_FATAL;
 #endif
 
 // A few definitions of macros that don't generate much code. These are used
 // by LOG() and LOG_IF, etc. Since these are used all over our code, it's
 // better to have compact code for these operations.
 #define COMPACT_GOOGLE_LOG_EX_INFO(ClassName, ...) \
-  logging::ClassName(__FILE__, __LINE__, logging::LOG_INFO , ##__VA_ARGS__)
-#define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...) \
-  logging::ClassName(__FILE__, __LINE__, logging::LOG_WARNING , ##__VA_ARGS__)
+  ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_INFO, ##__VA_ARGS__)
+#define COMPACT_GOOGLE_LOG_EX_WARNING(ClassName, ...)              \
+  ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_WARNING, \
+                       ##__VA_ARGS__)
 #define COMPACT_GOOGLE_LOG_EX_ERROR(ClassName, ...) \
-  logging::ClassName(__FILE__, __LINE__, logging::LOG_ERROR , ##__VA_ARGS__)
+  ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_ERROR, ##__VA_ARGS__)
 #define COMPACT_GOOGLE_LOG_EX_FATAL(ClassName, ...) \
-  logging::ClassName(__FILE__, __LINE__, logging::LOG_FATAL , ##__VA_ARGS__)
+  ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_FATAL, ##__VA_ARGS__)
 #define COMPACT_GOOGLE_LOG_EX_DFATAL(ClassName, ...) \
-  logging::ClassName(__FILE__, __LINE__, logging::LOG_DFATAL , ##__VA_ARGS__)
+  ::logging::ClassName(__FILE__, __LINE__, ::logging::LOG_DFATAL, ##__VA_ARGS__)
 
 #define COMPACT_GOOGLE_LOG_INFO \
   COMPACT_GOOGLE_LOG_EX_INFO(LogMessage)
 #define COMPACT_GOOGLE_LOG_WARNING \
   COMPACT_GOOGLE_LOG_EX_WARNING(LogMessage)
 #define COMPACT_GOOGLE_LOG_ERROR \
   COMPACT_GOOGLE_LOG_EX_ERROR(LogMessage)
 #define COMPACT_GOOGLE_LOG_FATAL \
@@ -368,53 +372,48 @@ const LogSeverity LOG_0 = LOG_ERROR;
 // ostream. We employ a neat hack by calling the stream() member
 // function of LogMessage which seems to avoid the problem.
 #define LOG_STREAM(severity) COMPACT_GOOGLE_LOG_ ## severity.stream()
 
 #define LOG(severity) LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity))
 #define LOG_IF(severity, condition) \
   LAZY_STREAM(LOG_STREAM(severity), LOG_IS_ON(severity) && (condition))
 
-#define SYSLOG(severity) LOG(severity)
-#define SYSLOG_IF(severity, condition) LOG_IF(severity, condition)
-
 // The VLOG macros log with negative verbosities.
 #define VLOG_STREAM(verbose_level) \
-  logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream()
+  ::logging::LogMessage(__FILE__, __LINE__, -verbose_level).stream()
 
 #define VLOG(verbose_level) \
   LAZY_STREAM(VLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
 
 #define VLOG_IF(verbose_level, condition) \
   LAZY_STREAM(VLOG_STREAM(verbose_level), \
       VLOG_IS_ON(verbose_level) && (condition))
 
 #if defined (OS_WIN)
 #define VPLOG_STREAM(verbose_level) \
-  logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \
+  ::logging::Win32ErrorLogMessage(__FILE__, __LINE__, -verbose_level, \
     ::logging::GetLastSystemErrorCode()).stream()
 #elif defined(OS_POSIX)
 #define VPLOG_STREAM(verbose_level) \
-  logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \
+  ::logging::ErrnoLogMessage(__FILE__, __LINE__, -verbose_level, \
     ::logging::GetLastSystemErrorCode()).stream()
 #endif
 
 #define VPLOG(verbose_level) \
   LAZY_STREAM(VPLOG_STREAM(verbose_level), VLOG_IS_ON(verbose_level))
 
 #define VPLOG_IF(verbose_level, condition) \
   LAZY_STREAM(VPLOG_STREAM(verbose_level), \
     VLOG_IS_ON(verbose_level) && (condition))
 
 // TODO(akalin): Add more VLOG variants, e.g. VPLOG.
 
 #define LOG_ASSERT(condition)  \
   LOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
-#define SYSLOG_ASSERT(condition) \
-  SYSLOG_IF(FATAL, !(condition)) << "Assert failed: " #condition ". "
 
 #if defined(OS_WIN)
 #define PLOG_STREAM(severity) \
   COMPACT_GOOGLE_LOG_EX_ ## severity(Win32ErrorLogMessage, \
       ::logging::GetLastSystemErrorCode()).stream()
 #elif defined(OS_POSIX)
 #define PLOG_STREAM(severity) \
   COMPACT_GOOGLE_LOG_EX_ ## severity(ErrnoLogMessage, \
@@ -430,17 +429,17 @@ const LogSeverity LOG_0 = LOG_ERROR;
 // The actual stream used isn't important.
 #define EAT_STREAM_PARAMETERS                                           \
   true ? (void) 0 : ::logging::LogMessageVoidify() & LOG_STREAM(FATAL)
 
 // Captures the result of a CHECK_EQ (for example) and facilitates testing as a
 // boolean.
 class CheckOpResult {
  public:
-  // |message| must be null if and only if the check failed.
+  // |message| must be non-null if and only if the check failed.
   CheckOpResult(std::string* message) : message_(message) {}
   // Returns true if the check succeeded.
   operator bool() const { return !message_; }
   // Returns the message.
   std::string* message() { return message_; }
 
  private:
   std::string* message_;
@@ -448,32 +447,38 @@ class CheckOpResult {
 
 // CHECK dies with a fatal error if condition is not true.  It is *not*
 // controlled by NDEBUG, so the check will be executed regardless of
 // compilation mode.
 //
 // We make sure CHECK et al. always evaluates their arguments, as
 // doing CHECK(FunctionWithSideEffect()) is a common idiom.
 
-#if defined(OFFICIAL_BUILD) && defined(NDEBUG) && !defined(OS_ANDROID)
+#if defined(OFFICIAL_BUILD) && defined(NDEBUG)
 
 // Make all CHECK functions discard their log strings to reduce code
-// bloat for official release builds (except Android).
+// bloat, and improve performance, for official release builds.
 
-// TODO(akalin): This would be more valuable if there were some way to
-// remove BreakDebugger() from the backtrace, perhaps by turning it
-// into a macro (like __debugbreak() on Windows).
+#if defined(COMPILER_GCC) || __clang__
+#define LOGGING_CRASH() __builtin_trap()
+#else
+#define LOGGING_CRASH() ((void)(*(volatile char*)0 = 0))
+#endif
+
+// This is not calling BreakDebugger since this is called frequently, and
+// calling an out-of-line function instead of a noreturn inline macro prevents
+// compiler optimizations.
 #define CHECK(condition)                                                \
-  !(condition) ? ::base::debug::BreakDebugger() : EAT_STREAM_PARAMETERS
+  !(condition) ? LOGGING_CRASH() : EAT_STREAM_PARAMETERS
 
 #define PCHECK(condition) CHECK(condition)
 
 #define CHECK_OP(name, op, val1, val2) CHECK((val1) op (val2))
 
-#else
+#else  // !(OFFICIAL_BUILD && NDEBUG)
 
 #if defined(_PREFAST_) && defined(OS_WIN)
 // Use __analysis_assume to tell the VC++ static analysis engine that
 // assert conditions are true, to suppress warnings.  The LAZY_STREAM
 // parameter doesn't reference 'condition' in /analyze builds because
 // this evaluation confuses /analyze. The !! before condition is because
 // __analysis_assume gets confused on some conditions:
 // http://randomascii.wordpress.com/2011/09/13/analyze-for-visual-studio-the-ugly-part-5/
@@ -486,51 +491,79 @@ class CheckOpResult {
 #define PCHECK(condition)                \
   __analysis_assume(!!(condition)),      \
   LAZY_STREAM(PLOG_STREAM(FATAL), false) \
   << "Check failed: " #condition ". "
 
 #else  // _PREFAST_
 
 // Do as much work as possible out of line to reduce inline code size.
-#define CHECK(condition)                                                    \
-  LAZY_STREAM(logging::LogMessage(__FILE__, __LINE__, #condition).stream(), \
+#define CHECK(condition)                                                      \
+  LAZY_STREAM(::logging::LogMessage(__FILE__, __LINE__, #condition).stream(), \
               !(condition))
 
 #define PCHECK(condition)                       \
   LAZY_STREAM(PLOG_STREAM(FATAL), !(condition)) \
   << "Check failed: " #condition ". "
 
 #endif  // _PREFAST_
 
 // Helper macro for binary operators.
 // Don't use this macro directly in your code, use CHECK_EQ et al below.
 // The 'switch' is used to prevent the 'else' from being ambiguous when the
 // macro is used in an 'if' clause such as:
 // if (a == 1)
 //   CHECK_EQ(2, a);
 #define CHECK_OP(name, op, val1, val2)                                         \
   switch (0) case 0: default:                                                  \
-  if (logging::CheckOpResult true_if_passed =                                  \
-      logging::Check##name##Impl((val1), (val2),                               \
-                                 #val1 " " #op " " #val2))                     \
+  if (::logging::CheckOpResult true_if_passed =                                \
+      ::logging::Check##name##Impl((val1), (val2),                             \
+                                   #val1 " " #op " " #val2))                   \
    ;                                                                           \
   else                                                                         \
-    logging::LogMessage(__FILE__, __LINE__, true_if_passed.message()).stream()
+    ::logging::LogMessage(__FILE__, __LINE__, true_if_passed.message()).stream()
+
+#endif  // !(OFFICIAL_BUILD && NDEBUG)
+
+// This formats a value for a failing CHECK_XX statement.  Ordinarily,
+// it uses the definition for operator<<, with a few special cases below.
+template <typename T>
+inline typename std::enable_if<
+    base::internal::SupportsOstreamOperator<const T&>::value,
+    void>::type
+MakeCheckOpValueString(std::ostream* os, const T& v) {
+  (*os) << v;
+}
 
-#endif
+// We need overloads for enums that don't support operator<<.
+// (i.e. scoped enums where no operator<< overload was declared).
+template <typename T>
+inline typename std::enable_if<
+    !base::internal::SupportsOstreamOperator<const T&>::value &&
+        std::is_enum<T>::value,
+    void>::type
+MakeCheckOpValueString(std::ostream* os, const T& v) {
+  (*os) << static_cast<typename base::underlying_type<T>::type>(v);
+}
+
+// We need an explicit overload for std::nullptr_t.
+BASE_EXPORT void MakeCheckOpValueString(std::ostream* os, std::nullptr_t p);
 
 // Build the error message string.  This is separate from the "Impl"
 // function template because it is not performance critical and so can
 // be out of line, while the "Impl" code should be inline.  Caller
 // takes ownership of the returned string.
 template<class t1, class t2>
 std::string* MakeCheckOpString(const t1& v1, const t2& v2, const char* names) {
   std::ostringstream ss;
-  ss << names << " (" << v1 << " vs. " << v2 << ")";
+  ss << names << " (";
+  MakeCheckOpValueString(&ss, v1);
+  ss << " vs. ";
+  MakeCheckOpValueString(&ss, v2);
+  ss << ")";
   std::string* msg = new std::string(ss.str());
   return msg;
 }
 
 // Commonly used instantiations of MakeCheckOpString<>. Explicitly instantiated
 // in logging.cc.
 extern template BASE_EXPORT std::string* MakeCheckOpString<int, int>(
     const int&, const int&, const char* names);
@@ -551,87 +584,75 @@ std::string* MakeCheckOpString<std::stri
 // The (int, int) specialization works around the issue that the compiler
 // will not instantiate the template version of the function on values of
 // unnamed enum type - see comment below.
 #define DEFINE_CHECK_OP_IMPL(name, op) \
   template <class t1, class t2> \
   inline std::string* Check##name##Impl(const t1& v1, const t2& v2, \
                                         const char* names) { \
     if (v1 op v2) return NULL; \
-    else return MakeCheckOpString(v1, v2, names); \
+    else return ::logging::MakeCheckOpString(v1, v2, names);    \
   } \
   inline std::string* Check##name##Impl(int v1, int v2, const char* names) { \
     if (v1 op v2) return NULL; \
-    else return MakeCheckOpString(v1, v2, names); \
+    else return ::logging::MakeCheckOpString(v1, v2, names);    \
   }
 DEFINE_CHECK_OP_IMPL(EQ, ==)
 DEFINE_CHECK_OP_IMPL(NE, !=)
 DEFINE_CHECK_OP_IMPL(LE, <=)
 DEFINE_CHECK_OP_IMPL(LT, < )
 DEFINE_CHECK_OP_IMPL(GE, >=)
 DEFINE_CHECK_OP_IMPL(GT, > )
 #undef DEFINE_CHECK_OP_IMPL
 
 #define CHECK_EQ(val1, val2) CHECK_OP(EQ, ==, val1, val2)
 #define CHECK_NE(val1, val2) CHECK_OP(NE, !=, val1, val2)
 #define CHECK_LE(val1, val2) CHECK_OP(LE, <=, val1, val2)
 #define CHECK_LT(val1, val2) CHECK_OP(LT, < , val1, val2)
 #define CHECK_GE(val1, val2) CHECK_OP(GE, >=, val1, val2)
 #define CHECK_GT(val1, val2) CHECK_OP(GT, > , val1, val2)
 
-#if defined(NDEBUG)
-#define ENABLE_DLOG 0
-#else
-#define ENABLE_DLOG 1
-#endif
-
 #if defined(NDEBUG) && !defined(DCHECK_ALWAYS_ON)
 #define DCHECK_IS_ON() 0
 #else
 #define DCHECK_IS_ON() 1
 #endif
 
 // Definitions for DLOG et al.
 
-#if ENABLE_DLOG
+#if DCHECK_IS_ON()
 
 #define DLOG_IS_ON(severity) LOG_IS_ON(severity)
 #define DLOG_IF(severity, condition) LOG_IF(severity, condition)
 #define DLOG_ASSERT(condition) LOG_ASSERT(condition)
 #define DPLOG_IF(severity, condition) PLOG_IF(severity, condition)
 #define DVLOG_IF(verboselevel, condition) VLOG_IF(verboselevel, condition)
 #define DVPLOG_IF(verboselevel, condition) VPLOG_IF(verboselevel, condition)
 
-#else  // ENABLE_DLOG
+#else  // DCHECK_IS_ON()
 
-// If ENABLE_DLOG is off, we want to avoid emitting any references to
-// |condition| (which may reference a variable defined only if NDEBUG
-// is not defined).  Contrast this with DCHECK et al., which has
-// different behavior.
+// If !DCHECK_IS_ON(), we want to avoid emitting any references to |condition|
+// (which may reference a variable defined only if DCHECK_IS_ON()).
+// Contrast this with DCHECK et al., which has different behavior.
 
 #define DLOG_IS_ON(severity) false
 #define DLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
 #define DLOG_ASSERT(condition) EAT_STREAM_PARAMETERS
 #define DPLOG_IF(severity, condition) EAT_STREAM_PARAMETERS
 #define DVLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
 #define DVPLOG_IF(verboselevel, condition) EAT_STREAM_PARAMETERS
 
-#endif  // ENABLE_DLOG
+#endif  // DCHECK_IS_ON()
 
-// DEBUG_MODE is for uses like
+// DEBUG_MODE is for runtime uses like
 //   if (DEBUG_MODE) foo.CheckThatFoo();
-// instead of
-//   #ifndef NDEBUG
-//     foo.CheckThatFoo();
-//   #endif
+// We tie its state to DCHECK_IS_ON().
 //
-// We tie its state to ENABLE_DLOG.
-enum { DEBUG_MODE = ENABLE_DLOG };
-
-#undef ENABLE_DLOG
+// For compile-time checks, #if DCHECK_IS_ON() can be used.
+enum { DEBUG_MODE = DCHECK_IS_ON() };
 
 #define DLOG(severity)                                          \
   LAZY_STREAM(LOG_STREAM(severity), DLOG_IS_ON(severity))
 
 #define DPLOG(severity)                                         \
   LAZY_STREAM(PLOG_STREAM(severity), DLOG_IS_ON(severity))
 
 #define DVLOG(verboselevel) DVLOG_IF(verboselevel, VLOG_IS_ON(verboselevel))
@@ -688,45 +709,46 @@ const LogSeverity LOG_DCHECK = LOG_INFO;
 #endif  // _PREFAST_
 
 // Helper macro for binary operators.
 // Don't use this macro directly in your code, use DCHECK_EQ et al below.
 // The 'switch' is used to prevent the 'else' from being ambiguous when the
 // macro is used in an 'if' clause such as:
 // if (a == 1)
 //   DCHECK_EQ(2, a);
-#define DCHECK_OP(name, op, val1, val2)                               \
-  switch (0) case 0: default:                                         \
-  if (logging::CheckOpResult true_if_passed =                         \
-      DCHECK_IS_ON() ?                                                \
-      logging::Check##name##Impl((val1), (val2),                      \
-                                 #val1 " " #op " " #val2) : nullptr)  \
-   ;                                                                  \
-  else                                                                \
-    logging::LogMessage(__FILE__, __LINE__, ::logging::LOG_DCHECK,    \
-                        true_if_passed.message()).stream()
+#define DCHECK_OP(name, op, val1, val2)                                \
+  switch (0) case 0: default:                                          \
+  if (::logging::CheckOpResult true_if_passed =                        \
+      DCHECK_IS_ON() ?                                                 \
+      ::logging::Check##name##Impl((val1), (val2),                     \
+                                   #val1 " " #op " " #val2) : nullptr) \
+   ;                                                                   \
+  else                                                                 \
+    ::logging::LogMessage(__FILE__, __LINE__, ::logging::LOG_DCHECK,   \
+                          true_if_passed.message()).stream()
 
 // Equality/Inequality checks - compare two values, and log a
 // LOG_DCHECK message including the two values when the result is not
 // as expected.  The values must have operator<<(ostream, ...)
 // defined.
 //
 // You may append to the error message like so:
-//   DCHECK_NE(1, 2) << ": The world must be ending!";
+//   DCHECK_NE(1, 2) << "The world must be ending!";
 //
 // We are very careful to ensure that each argument is evaluated exactly
 // once, and that anything which is legal to pass as a function argument is
 // legal here.  In particular, the arguments may be temporary expressions
 // which will end up being destroyed at the end of the apparent statement,
 // for example:
 //   DCHECK_EQ(string("abc")[1], 'b');
 //
-// WARNING: These may not compile correctly if one of the arguments is a pointer
-// and the other is NULL. To work around this, simply static_cast NULL to the
-// type of the desired pointer.
+// WARNING: These don't compile correctly if one of the arguments is a pointer
+// and the other is NULL.  In new code, prefer nullptr instead.  To
+// work around this for C++98, simply static_cast NULL to the type of the
+// desired pointer.
 
 #define DCHECK_EQ(val1, val2) DCHECK_OP(EQ, ==, val1, val2)
 #define DCHECK_NE(val1, val2) DCHECK_OP(NE, !=, val1, val2)
 #define DCHECK_LE(val1, val2) DCHECK_OP(LE, <=, val1, val2)
 #define DCHECK_LT(val1, val2) DCHECK_OP(LT, < , val1, val2)
 #define DCHECK_GE(val1, val2) DCHECK_OP(GE, >=, val1, val2)
 #define DCHECK_GT(val1, val2) DCHECK_OP(GT, > , val1, val2)
 
@@ -768,16 +790,19 @@ class BASE_EXPORT LogMessage {
   // Used for DCHECK_EQ(), etc. Takes ownership of the given string.
   LogMessage(const char* file, int line, LogSeverity severity,
              std::string* result);
 
   ~LogMessage();
 
   std::ostream& stream() { return stream_; }
 
+  LogSeverity severity() { return severity_; }
+  std::string str() { return stream_.str(); }
+
  private:
   void Init(const char* file, int line);
 
   LogSeverity severity_;
   std::ostringstream stream_;
   size_t message_start_;  // Offset of the start of the message (past prefix
                           // info).
   // The file and line information passed in to the constructor.
@@ -802,22 +827,16 @@ class BASE_EXPORT LogMessage {
   };
 
   SaveLastError last_error_;
 #endif
 
   DISALLOW_COPY_AND_ASSIGN(LogMessage);
 };
 
-// A non-macro interface to the log facility; (useful
-// when the logging level is not a compile-time constant).
-inline void LogAtLevel(int log_level, const std::string& msg) {
-  LogMessage(__FILE__, __LINE__, log_level).stream() << msg;
-}
-
 // This class is used to explicitly ignore values in the conditional
 // logging macros.  This avoids compiler warnings like "value computed
 // is not used" and "statement has no effect".
 class LogMessageVoidify {
  public:
   LogMessageVoidify() { }
   // This has to be an operator with a precedence lower than << but
   // higher than ?:
@@ -881,22 +900,24 @@ class BASE_EXPORT ErrnoLogMessage {
 // NOTE: Since the log file is opened as necessary by the action of logging
 //       statements, there's no guarantee that it will stay closed
 //       after this call.
 BASE_EXPORT void CloseLogFile();
 
 // Async signal safe logging mechanism.
 BASE_EXPORT void RawLog(int level, const char* message);
 
-#define RAW_LOG(level, message) logging::RawLog(logging::LOG_ ## level, message)
+#define RAW_LOG(level, message) \
+  ::logging::RawLog(::logging::LOG_##level, message)
 
-#define RAW_CHECK(condition)                                                   \
-  do {                                                                         \
-    if (!(condition))                                                          \
-      logging::RawLog(logging::LOG_FATAL, "Check failed: " #condition "\n");   \
+#define RAW_CHECK(condition)                               \
+  do {                                                     \
+    if (!(condition))                                      \
+      ::logging::RawLog(::logging::LOG_FATAL,              \
+                        "Check failed: " #condition "\n"); \
   } while (0)
 
 #if defined(OS_WIN)
 // Returns true if logging to file is enabled.
 BASE_EXPORT bool IsLoggingToFileEnabled();
 
 // Returns the default log file path.
 BASE_EXPORT std::wstring GetLogFileFullPath();
--- a/security/sandbox/chromium/base/macros.h
+++ b/security/sandbox/chromium/base/macros.h
@@ -15,21 +15,21 @@
 // Put this in the declarations for a class to be uncopyable.
 #define DISALLOW_COPY(TypeName) \
   TypeName(const TypeName&) = delete
 
 // Put this in the declarations for a class to be unassignable.
 #define DISALLOW_ASSIGN(TypeName) \
   void operator=(const TypeName&) = delete
 
-// A macro to disallow the copy constructor and operator= functions
-// This should be used in the private: declarations for a class
+// A macro to disallow the copy constructor and operator= functions.
+// This should be used in the private: declarations for a class.
 #define DISALLOW_COPY_AND_ASSIGN(TypeName) \
-  TypeName(const TypeName&);               \
-  void operator=(const TypeName&)
+  TypeName(const TypeName&) = delete;      \
+  void operator=(const TypeName&) = delete
 
 // A macro to disallow all the implicit constructors, namely the
 // default constructor, copy constructor and operator= functions.
 //
 // This should be used in the private: declarations for a class
 // that wants to prevent anyone from instantiating it. This is
 // especially useful for classes containing only static methods.
 #define DISALLOW_IMPLICIT_CONSTRUCTORS(TypeName) \
@@ -47,17 +47,17 @@
 // use its type.
 template <typename T, size_t N> char (&ArraySizeHelper(T (&array)[N]))[N];
 #define arraysize(array) (sizeof(ArraySizeHelper(array)))
 
 // Used to explicitly mark the return value of a function as unused. If you are
 // really sure you don't want to do anything with the return value of a function
 // that has been marked WARN_UNUSED_RESULT, wrap it with this. Example:
 //
-//   scoped_ptr<MyType> my_var = ...;
+//   std::unique_ptr<MyType> my_var = ...;
 //   if (TakeOwnership(my_var.get()) == SUCCESS)
 //     ignore_result(my_var.release());
 //
 template<typename T>
 inline void ignore_result(const T&) {
 }
 
 // The following enum should be used only as a constructor argument to indicate
--- a/security/sandbox/chromium/base/memory/aligned_memory.h
+++ b/security/sandbox/chromium/base/memory/aligned_memory.h
@@ -21,19 +21,19 @@
 //
 // Alternatively, a runtime sized aligned allocation can be created:
 //
 //   float* my_array = static_cast<float*>(AlignedAlloc(size, alignment));
 //
 //   // ... later, to release the memory:
 //   AlignedFree(my_array);
 //
-// Or using scoped_ptr:
+// Or using unique_ptr:
 //
-//   scoped_ptr<float, AlignedFreeDeleter> my_array(
+//   std::unique_ptr<float, AlignedFreeDeleter> my_array(
 //       static_cast<float*>(AlignedAlloc(size, alignment)));
 
 #ifndef BASE_MEMORY_ALIGNED_MEMORY_H_
 #define BASE_MEMORY_ALIGNED_MEMORY_H_
 
 #include <stddef.h>
 #include <stdint.h>
 
@@ -99,18 +99,18 @@ BASE_EXPORT void* AlignedAlloc(size_t si
 inline void AlignedFree(void* ptr) {
 #if defined(COMPILER_MSVC)
   _aligned_free(ptr);
 #else
   free(ptr);
 #endif
 }
 
-// Deleter for use with scoped_ptr. E.g., use as
-//   scoped_ptr<Foo, base::AlignedFreeDeleter> foo;
+// Deleter for use with unique_ptr. E.g., use as
+//   std::unique_ptr<Foo, base::AlignedFreeDeleter> foo;
 struct AlignedFreeDeleter {
   inline void operator()(void* ptr) const {
     AlignedFree(ptr);
   }
 };
 
 }  // namespace base
 
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium/base/memory/free_deleter.h
@@ -0,0 +1,25 @@
+// Copyright 2016 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef BASE_MEMORY_FREE_DELETER_H_
+#define BASE_MEMORY_FREE_DELETER_H_
+
+#include <stdlib.h>
+
+namespace base {
+
+// Function object which invokes 'free' on its parameter, which must be
+// a pointer. Can be used to store malloc-allocated pointers in std::unique_ptr:
+//
+// std::unique_ptr<int, base::FreeDeleter> foo_ptr(
+//     static_cast<int*>(malloc(sizeof(int))));
+struct FreeDeleter {
+  inline void operator()(void* ptr) const {
+    free(ptr);
+  }
+};
+
+}  // namespace base
+
+#endif  // BASE_MEMORY_FREE_DELETER_H_
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium/base/memory/ptr_util.h
@@ -0,0 +1,74 @@
+// Copyright 2015 The Chromium Authors. All rights reserved.
+// Use of this source code is governed by a BSD-style license that can be
+// found in the LICENSE file.
+
+#ifndef BASE_MEMORY_PTR_UTIL_H_
+#define BASE_MEMORY_PTR_UTIL_H_
+
+#include <memory>
+#include <utility>
+
+namespace base {
+
+// Helper to transfer ownership of a raw pointer to a std::unique_ptr<T>.
+// Note that std::unique_ptr<T> has very different semantics from
+// std::unique_ptr<T[]>: do not use this helper for array allocations.
+template <typename T>
+std::unique_ptr<T> WrapUnique(T* ptr) {
+  return std::unique_ptr<T>(ptr);
+}
+
+namespace internal {
+
+template <typename T>
+struct MakeUniqueResult {
+  using Scalar = std::unique_ptr<T>;
+};
+
+template <typename T>
+struct MakeUniqueResult<T[]> {
+  using Array = std::unique_ptr<T[]>;
+};
+
+template <typename T, size_t N>
+struct MakeUniqueResult<T[N]> {
+  using Invalid = void;
+};
+
+}  // namespace internal
+
+// Helper to construct an object wrapped in a std::unique_ptr. This is an
+// implementation of C++14's std::make_unique that can be used in Chrome.
+//
+// MakeUnique<T>(args) should be preferred over WrapUnique(new T(args)): bare
+// calls to `new` should be treated with scrutiny.
+//
+// Usage:
+//   // ptr is a std::unique_ptr<std::string>
+//   auto ptr = MakeUnique<std::string>("hello world!");
+//
+//   // arr is a std::unique_ptr<int[]>
+//   auto arr = MakeUnique<int[]>(5);
+
+// Overload for non-array types. Arguments are forwarded to T's constructor.
+template <typename T, typename... Args>
+typename internal::MakeUniqueResult<T>::Scalar MakeUnique(Args&&... args) {
+  return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
+}
+
+// Overload for array types of unknown bound, e.g. T[]. The array is allocated
+// with `new T[n]()` and value-initialized: note that this is distinct from
+// `new T[n]`, which default-initializes.
+template <typename T>
+typename internal::MakeUniqueResult<T>::Array MakeUnique(size_t size) {
+  return std::unique_ptr<T>(new typename std::remove_extent<T>::type[size]());
+}
+
+// Overload to reject array types of known bound, e.g. T[n].
+template <typename T, typename... Args>
+typename internal::MakeUniqueResult<T>::Invalid MakeUnique(Args&&... args) =
+    delete;
+
+}  // namespace base
+
+#endif  // BASE_MEMORY_PTR_UTIL_H_
--- a/security/sandbox/chromium/base/memory/raw_scoped_refptr_mismatch_checker.h
+++ b/security/sandbox/chromium/base/memory/raw_scoped_refptr_mismatch_checker.h
@@ -1,64 +1,58 @@
 // 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_MEMORY_RAW_SCOPED_REFPTR_MISMATCH_CHECKER_H_
 #define BASE_MEMORY_RAW_SCOPED_REFPTR_MISMATCH_CHECKER_H_
 
+#include <tuple>
+#include <type_traits>
+
 #include "base/memory/ref_counted.h"
-#include "base/template_util.h"
-#include "base/tuple.h"
-#include "build/build_config.h"
 
 // It is dangerous to post a task with a T* argument where T is a subtype of
 // RefCounted(Base|ThreadSafeBase), since by the time the parameter is used, the
 // object may already have been deleted since it was not held with a
 // scoped_refptr. Example: http://crbug.com/27191
 // The following set of traits are designed to generate a compile error
 // whenever this antipattern is attempted.
 
 namespace base {
 
 // This is a base internal implementation file used by task.h and callback.h.
 // Not for public consumption, so we wrap it in namespace internal.
 namespace internal {
 
 template <typename T>
 struct NeedsScopedRefptrButGetsRawPtr {
-#if defined(OS_WIN)
-  enum {
-    value = base::false_type::value
-  };
-#else
   enum {
     // Human readable translation: you needed to be a scoped_refptr if you are a
     // raw pointer type and are convertible to a RefCounted(Base|ThreadSafeBase)
     // type.
-    value = (is_pointer<T>::value &&
-             (is_convertible<T, subtle::RefCountedBase*>::value ||
-              is_convertible<T, subtle::RefCountedThreadSafeBase*>::value))
+    value = (std::is_pointer<T>::value &&
+             (std::is_convertible<T, subtle::RefCountedBase*>::value ||
+              std::is_convertible<T, subtle::RefCountedThreadSafeBase*>::value))
   };
-#endif
 };
 
 template <typename Params>
 struct ParamsUseScopedRefptrCorrectly {
   enum { value = 0 };
 };
 
 template <>
-struct ParamsUseScopedRefptrCorrectly<Tuple<>> {
+struct ParamsUseScopedRefptrCorrectly<std::tuple<>> {
   enum { value = 1 };
 };
 
 template <typename Head, typename... Tail>
-struct ParamsUseScopedRefptrCorrectly<Tuple<Head, Tail...>> {
+struct ParamsUseScopedRefptrCorrectly<std::tuple<Head, Tail...>> {
   enum { value = !NeedsScopedRefptrButGetsRawPtr<Head>::value &&
-                 ParamsUseScopedRefptrCorrectly<Tuple<Tail...>>::value };
+                  ParamsUseScopedRefptrCorrectly<std::tuple<Tail...>>::value };
 };
 
 }  // namespace internal
 
 }  // namespace base
 
 #endif  // BASE_MEMORY_RAW_SCOPED_REFPTR_MISMATCH_CHECKER_H_
--- a/security/sandbox/chromium/base/memory/ref_counted.cc
+++ b/security/sandbox/chromium/base/memory/ref_counted.cc
@@ -10,42 +10,42 @@ namespace base {
 namespace subtle {
 
 bool RefCountedThreadSafeBase::HasOneRef() const {
   return AtomicRefCountIsOne(
       &const_cast<RefCountedThreadSafeBase*>(this)->ref_count_);
 }
 
 RefCountedThreadSafeBase::RefCountedThreadSafeBase() : ref_count_(0) {
-#ifndef NDEBUG
+#if DCHECK_IS_ON()
   in_dtor_ = false;
 #endif
 }
 
 RefCountedThreadSafeBase::~RefCountedThreadSafeBase() {
-#ifndef NDEBUG
+#if DCHECK_IS_ON()
   DCHECK(in_dtor_) << "RefCountedThreadSafe object deleted without "
                       "calling Release()";
 #endif
 }
 
 void RefCountedThreadSafeBase::AddRef() const {
-#ifndef NDEBUG
+#if DCHECK_IS_ON()
   DCHECK(!in_dtor_);
 #endif
   AtomicRefCountInc(&ref_count_);
 }
 
 bool RefCountedThreadSafeBase::Release() const {
-#ifndef NDEBUG
+#if DCHECK_IS_ON()
   DCHECK(!in_dtor_);
   DCHECK(!AtomicRefCountIsZero(&ref_count_));
 #endif
   if (!AtomicRefCountDec(&ref_count_)) {
-#ifndef NDEBUG
+#if DCHECK_IS_ON()
     in_dtor_ = true;
 #endif
     return true;
   }
   return false;
 }
 
 }  // namespace subtle
--- a/security/sandbox/chromium/base/memory/ref_counted.h
+++ b/security/sandbox/chromium/base/memory/ref_counted.h
@@ -1,84 +1,85 @@
 // 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_MEMORY_REF_COUNTED_H_
 #define BASE_MEMORY_REF_COUNTED_H_
 
+#include <stddef.h>
+
 #include <cassert>
 #include <iosfwd>
+#include <type_traits>
 
 #include "base/atomic_ref_count.h"
 #include "base/base_export.h"
 #include "base/compiler_specific.h"
+#include "base/logging.h"
 #include "base/macros.h"
-#ifndef NDEBUG
-#include "base/logging.h"
-#endif
 #include "base/threading/thread_collision_warner.h"
 #include "build/build_config.h"
 
 namespace base {
 
 namespace subtle {
 
 class BASE_EXPORT RefCountedBase {
  public:
   bool HasOneRef() const { return ref_count_ == 1; }
 
  protected:
   RefCountedBase()
       : ref_count_(0)
-  #ifndef NDEBUG
-      , in_dtor_(false)
-  #endif
-      {
+#if DCHECK_IS_ON()
+        , in_dtor_(false)
+#endif
+  {
   }
 
   ~RefCountedBase() {
-  #ifndef NDEBUG
+#if DCHECK_IS_ON()
     DCHECK(in_dtor_) << "RefCounted object deleted without calling Release()";
-  #endif
+#endif
   }
 
 
   void AddRef() const {
     // TODO(maruel): Add back once it doesn't assert 500 times/sec.
     // Current thread books the critical section "AddRelease"
     // without release it.
     // DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_);
-  #ifndef NDEBUG
+#if DCHECK_IS_ON()
     DCHECK(!in_dtor_);
-  #endif
+#endif
     ++ref_count_;
   }
 
   // Returns true if the object should self-delete.
   bool Release() const {
     // TODO(maruel): Add back once it doesn't assert 500 times/sec.
     // Current thread books the critical section "AddRelease"
     // without release it.
     // DFAKE_SCOPED_LOCK_THREAD_LOCKED(add_release_);
-  #ifndef NDEBUG
+#if DCHECK_IS_ON()
     DCHECK(!in_dtor_);
-  #endif
+#endif
     if (--ref_count_ == 0) {
-  #ifndef NDEBUG
+#if DCHECK_IS_ON()
       in_dtor_ = true;
-  #endif
+#endif
       return true;
     }
     return false;
   }
 
  private:
-  mutable int ref_count_;
-#ifndef NDEBUG
+  mutable size_t ref_count_;
+#if DCHECK_IS_ON()
   mutable bool in_dtor_;
 #endif
 
   DFAKE_MUTEX(add_release_);
 
   DISALLOW_COPY_AND_ASSIGN(RefCountedBase);
 };
 
@@ -92,56 +93,56 @@ class BASE_EXPORT RefCountedThreadSafeBa
 
   void AddRef() const;
 
   // Returns true if the object should self-delete.
   bool Release() const;
 
  private:
   mutable AtomicRefCount ref_count_;
-#ifndef NDEBUG
+#if DCHECK_IS_ON()
   mutable bool in_dtor_;
 #endif
 
   DISALLOW_COPY_AND_ASSIGN(RefCountedThreadSafeBase);
 };
 
 }  // namespace subtle
 
 //
 // A base class for reference counted classes.  Otherwise, known as a cheap
-// knock-off of WebKit's RefCounted<T> class.  To use this guy just extend your
+// knock-off of WebKit's RefCounted<T> class.  To use this, just extend your
 // class from it like so:
 //
 //   class MyFoo : public base::RefCounted<MyFoo> {
 //    ...
 //    private:
 //     friend class base::RefCounted<MyFoo>;
 //     ~MyFoo();
 //   };
 //
 // You should always make your destructor non-public, to avoid any code deleting
 // the object accidently while there are references to it.
 template <class T>
 class RefCounted : public subtle::RefCountedBase {
  public:
-  RefCounted() {}
+  RefCounted() = default;
 
   void AddRef() const {
     subtle::RefCountedBase::AddRef();
   }
 
   void Release() const {
     if (subtle::RefCountedBase::Release()) {
       delete static_cast<const T*>(this);
     }
   }
 
  protected:
-  ~RefCounted() {}
+  ~RefCounted() = default;
 
  private:
   DISALLOW_COPY_AND_ASSIGN(RefCounted<T>);