Merge inbound to mozilla-central. a=merge
authorCiure Andrei <aciure@mozilla.com>
Thu, 13 Jun 2019 00:42:10 +0300
changeset 478508 848ce760ba38b646edf21040f6dbb1c1b7fd4ba2
parent 478507 32de23ddd8e2dd5efceec60f658bda00555e3852 (current diff)
parent 478412 dc5fcf3f2806d8b99e26fe2091ea2eb69da05fc6 (diff)
child 478509 ff20c8ec74645f965c2e492be408ff3c7341eda9
child 478540 9e7f207a57e5bbd57b3fb0991c4c30c85259f410
push id113422
push useraciure@mozilla.com
push dateWed, 12 Jun 2019 21:46:30 +0000
treeherdermozilla-inbound@ff20c8ec7464 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmerge
milestone69.0a1
first release with
nightly linux32
848ce760ba38 / 69.0a1 / 20190612214235 / files
nightly linux64
848ce760ba38 / 69.0a1 / 20190612214235 / files
nightly mac
848ce760ba38 / 69.0a1 / 20190612214235 / files
nightly win32
848ce760ba38 / 69.0a1 / 20190612214235 / files
nightly win64
848ce760ba38 / 69.0a1 / 20190612214235 / 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 mozilla-central. a=merge
js/src/jsapi.h
security/sandbox/chromium-shim/base/debug/debugging_flags.h
security/sandbox/chromium-shim/base/win/base_features.h
security/sandbox/chromium-shim/patches/after_update/remove_dynamic_GetUserDefaultLocaleName_call.patch
security/sandbox/chromium-shim/patches/after_update/use_STARTF_FORCEOFFFEEDBACK_flag.patch
security/sandbox/chromium-shim/patches/with_update/add_aarch64_windows_support.patch
security/sandbox/chromium-shim/patches/with_update/apply_upstream_alternate_desktop_fix.patch
security/sandbox/chromium-shim/patches/with_update/fix_Wcomma_warning_in_time_cc.patch
security/sandbox/chromium-shim/patches/with_update/mingw_duplicate_instatinations.patch
security/sandbox/chromium-shim/patches/with_update/mingw_noexports_casts.patch
security/sandbox/chromium-shim/patches/with_update/revert_c++14_index_sequence_usage.patch
security/sandbox/chromium-shim/patches/with_update/revert_c++14_typename_alias_usage.patch
security/sandbox/chromium/base/containers/hash_tables.h
security/sandbox/chromium/base/lazy_instance.cc
security/sandbox/chromium/base/memory/singleton.cc
security/sandbox/chromium/base/scoped_clear_errno.h
security/sandbox/chromium/base/task_scheduler/task_traits.h
security/sandbox/chromium/base/threading/sequenced_worker_pool.h
security/sandbox/chromium/sandbox/linux/system_headers/x86_64_linux_ucontext.h
--- a/js/public/MemoryFunctions.h
+++ b/js/public/MemoryFunctions.h
@@ -63,17 +63,25 @@ extern JS_PUBLIC_API void JS_freeop(JSFr
 
 namespace JS {
 
 /**
  * The different possible memory uses to pass to Add/RemoveAssociatedMemory.
  */
 #define JS_FOR_EACH_PUBLIC_MEMORY_USE(_) \
   _(XPCWrappedNative)                    \
-  _(DOMBinding)
+  _(DOMBinding)                          \
+  _(CTypeFFIType)                        \
+  _(CTypeFFITypeElements)                \
+  _(CTypeFunctionInfo)                   \
+  _(CTypeFieldInfo)                      \
+  _(CDataBufferPtr)                      \
+  _(CDataBuffer)                         \
+  _(CClosureInfo)                        \
+  _(CTypesInt64)
 
 enum class MemoryUse : uint8_t {
 #define DEFINE_MEMORY_USE(Name) Name,
   JS_FOR_EACH_PUBLIC_MEMORY_USE(DEFINE_MEMORY_USE)
 #undef DEFINE_MEMORY_USE
 };
 
 /**
--- a/js/src/builtin/MapObject.cpp
+++ b/js/src/builtin/MapObject.cpp
@@ -609,40 +609,45 @@ MapObject* MapObject::create(JSContext* 
   }
 
   bool insideNursery = IsInsideNursery(mapObj);
   if (insideNursery && !cx->nursery().addMapWithNurseryMemory(mapObj)) {
     ReportOutOfMemory(cx);
     return nullptr;
   }
 
-  mapObj->initPrivate(map.release());
+  InitObjectPrivate(mapObj, map.release(), MemoryUse::MapObjectTable);
   mapObj->initReservedSlot(NurseryKeysSlot, PrivateValue(nullptr));
   mapObj->initReservedSlot(HasNurseryMemorySlot,
                            JS::BooleanValue(insideNursery));
   return mapObj;
 }
 
 void MapObject::finalize(FreeOp* fop, JSObject* obj) {
   MOZ_ASSERT(fop->onMainThread());
   if (ValueMap* map = obj->as<MapObject>().getData()) {
-    fop->delete_(map);
+    fop->delete_(obj, map, MemoryUse::MapObjectTable);
   }
 }
 
 /* static */
 void MapObject::sweepAfterMinorGC(FreeOp* fop, MapObject* mapobj) {
-  if (IsInsideNursery(mapobj) && !IsForwarded(mapobj)) {
+  bool wasInsideNursery = IsInsideNursery(mapobj);
+  if (wasInsideNursery && !IsForwarded(mapobj)) {
     finalize(fop, mapobj);
     return;
   }
 
   mapobj = MaybeForwarded(mapobj);
   mapobj->getData()->destroyNurseryRanges();
   SetHasNurseryMemory(mapobj, false);
+
+  if (wasInsideNursery) {
+    AddCellMemory(mapobj, sizeof(ValueMap), MemoryUse::MapObjectTable);
+  }
 }
 
 bool MapObject::construct(JSContext* cx, unsigned argc, Value* vp) {
   CallArgs args = CallArgsFromVp(argc, vp);
 
   if (!ThrowIfNotConstructing(cx, args, "Map")) {
     return false;
   }
@@ -1218,17 +1223,17 @@ SetObject* SetObject::create(JSContext* 
   }
 
   bool insideNursery = IsInsideNursery(obj);
   if (insideNursery && !cx->nursery().addSetWithNurseryMemory(obj)) {
     ReportOutOfMemory(cx);
     return nullptr;
   }
 
-  obj->initPrivate(set.release());
+  InitObjectPrivate(obj, set.release(), MemoryUse::MapObjectTable);
   obj->initReservedSlot(NurseryKeysSlot, PrivateValue(nullptr));
   obj->initReservedSlot(HasNurseryMemorySlot, JS::BooleanValue(insideNursery));
   return obj;
 }
 
 void SetObject::trace(JSTracer* trc, JSObject* obj) {
   SetObject* setobj = static_cast<SetObject*>(obj);
   if (ValueSet* set = setobj->getData()) {
@@ -1237,30 +1242,35 @@ void SetObject::trace(JSTracer* trc, JSO
     }
   }
 }
 
 void SetObject::finalize(FreeOp* fop, JSObject* obj) {
   MOZ_ASSERT(fop->onMainThread());
   SetObject* setobj = static_cast<SetObject*>(obj);
   if (ValueSet* set = setobj->getData()) {
-    fop->delete_(set);
+    fop->delete_(obj, set, MemoryUse::MapObjectTable);
   }
 }
 
 /* static */
 void SetObject::sweepAfterMinorGC(FreeOp* fop, SetObject* setobj) {
-  if (IsInsideNursery(setobj) && !IsForwarded(setobj)) {
+  bool wasInsideNursery = IsInsideNursery(setobj);
+  if (wasInsideNursery && !IsForwarded(setobj)) {
     finalize(fop, setobj);
     return;
   }
 
   setobj = MaybeForwarded(setobj);
   setobj->getData()->destroyNurseryRanges();
   SetHasNurseryMemory(setobj, false);
+
+  if (wasInsideNursery) {
+    AddCellMemory(setobj, sizeof(ValueSet), MemoryUse::MapObjectTable);
+  }
 }
 
 bool SetObject::isBuiltinAdd(HandleValue add) {
   return IsNativeFunction(add, SetObject::add);
 }
 
 bool SetObject::construct(JSContext* cx, unsigned argc, Value* vp) {
   CallArgs args = CallArgsFromVp(argc, vp);
--- a/js/src/builtin/ModuleObject.cpp
+++ b/js/src/builtin/ModuleObject.cpp
@@ -390,16 +390,18 @@ ModuleNamespaceObject* ModuleNamespaceOb
       cx, NewProxyObject(cx, &proxyHandler, priv, nullptr, options));
   if (!object) {
     return nullptr;
   }
 
   SetProxyReservedSlot(object, ExportsSlot, ObjectValue(*exports));
   SetProxyReservedSlot(object, BindingsSlot,
                        PrivateValue(rootedBindings.release()));
+  AddCellMemory(object, sizeof(IndirectBindingMap),
+                MemoryUse::ModuleBindingMap);
 
   return &object->as<ModuleNamespaceObject>();
 }
 
 ModuleObject& ModuleNamespaceObject::module() {
   return GetProxyPrivate(this).toObject().as<ModuleObject>();
 }
 
@@ -678,17 +680,17 @@ void ModuleNamespaceObject::ProxyHandler
 }
 
 void ModuleNamespaceObject::ProxyHandler::finalize(JSFreeOp* fopArg,
                                                    JSObject* proxy) const {
   FreeOp* fop = FreeOp::get(fopArg);
   auto& self = proxy->as<ModuleNamespaceObject>();
 
   if (self.hasBindings()) {
-    fop->delete_(&self.bindings());
+    fop->delete_(proxy, &self.bindings(), MemoryUse::ModuleBindingMap);
   }
 }
 
 ///////////////////////////////////////////////////////////////////////////
 // FunctionDeclaration
 
 FunctionDeclaration::FunctionDeclaration(HandleAtom name, HandleFunction fun)
     : name(name), fun(fun) {}
@@ -752,35 +754,37 @@ ModuleObject* ModuleObject::create(JSCon
     return nullptr;
   }
 
   IndirectBindingMap* bindings = cx->new_<IndirectBindingMap>();
   if (!bindings) {
     return nullptr;
   }
 
-  self->initReservedSlot(ImportBindingsSlot, PrivateValue(bindings));
+  InitReservedSlot(self, ImportBindingsSlot, bindings,
+                   MemoryUse::ModuleBindingMap);
 
   FunctionDeclarationVector* funDecls = cx->new_<FunctionDeclarationVector>();
   if (!funDecls) {
     return nullptr;
   }
 
   self->initReservedSlot(FunctionDeclarationsSlot, PrivateValue(funDecls));
   return self;
 }
 
 /* static */
 void ModuleObject::finalize(js::FreeOp* fop, JSObject* obj) {
   MOZ_ASSERT(fop->maybeOnHelperThread());
   ModuleObject* self = &obj->as<ModuleObject>();
   if (self->hasImportBindings()) {
-    fop->delete_(&self->importBindings());
+    fop->delete_(obj, &self->importBindings(), MemoryUse::ModuleBindingMap);
   }
   if (FunctionDeclarationVector* funDecls = self->functionDeclarations()) {
+    // Not tracked as these may move between zones on merge.
     fop->delete_(funDecls);
   }
 }
 
 ModuleEnvironmentObject& ModuleObject::initialEnvironment() const {
   Value value = getReservedSlot(EnvironmentSlot);
   return value.toObject().as<ModuleEnvironmentObject>();
 }
--- a/js/src/builtin/WeakMapObject-inl.h
+++ b/js/src/builtin/WeakMapObject-inl.h
@@ -32,17 +32,17 @@ static MOZ_ALWAYS_INLINE bool WeakCollec
     HandleValue value) {
   ObjectValueMap* map = obj->getMap();
   if (!map) {
     auto newMap = cx->make_unique<ObjectValueMap>(cx, obj.get());
     if (!newMap) {
       return false;
     }
     map = newMap.release();
-    obj->setPrivate(map);
+    InitObjectPrivate(obj, map, MemoryUse::WeakMapObject);
   }
 
   // Preserve wrapped native keys to prevent wrapper optimization.
   if (!TryPreserveReflector(cx, key)) {
     return false;
   }
 
   RootedObject delegate(cx, UncheckedUnwrapWithoutExpose(key));
--- a/js/src/builtin/WeakMapObject.cpp
+++ b/js/src/builtin/WeakMapObject.cpp
@@ -176,17 +176,17 @@ static void WeakCollection_trace(JSTrace
   if (ObjectValueMap* map = obj->as<WeakCollectionObject>().getMap()) {
     map->trace(trc);
   }
 }
 
 static void WeakCollection_finalize(FreeOp* fop, JSObject* obj) {
   MOZ_ASSERT(fop->maybeOnHelperThread());
   if (ObjectValueMap* map = obj->as<WeakCollectionObject>().getMap()) {
-    fop->delete_(map);
+    fop->delete_(obj, map, MemoryUse::WeakMapObject);
   }
 }
 
 JS_PUBLIC_API JSObject* JS::NewWeakMapObject(JSContext* cx) {
   return NewBuiltinClassInstance<WeakMapObject>(cx);
 }
 
 JS_PUBLIC_API bool JS::IsWeakMapObject(JSObject* obj) {
--- a/js/src/ctypes/CTypes.cpp
+++ b/js/src/ctypes/CTypes.cpp
@@ -4288,16 +4288,19 @@ JSObject* CType::Create(JSContext* cx, H
   if (!typeObj) {
     return nullptr;
   }
 
   // Set up the reserved slots.
   JS_SetReservedSlot(typeObj, SLOT_TYPECODE, Int32Value(type));
   if (ffiType) {
     JS_SetReservedSlot(typeObj, SLOT_FFITYPE, PrivateValue(ffiType));
+    if (type == TYPE_struct || type == TYPE_array) {
+      AddCellMemory(typeObj, sizeof(ffi_type), MemoryUse::CTypeFFIType);
+    }
   }
   if (name) {
     JS_SetReservedSlot(typeObj, SLOT_NAME, StringValue(name));
   }
   JS_SetReservedSlot(typeObj, SLOT_SIZE, size);
   JS_SetReservedSlot(typeObj, SLOT_ALIGN, align);
 
   if (dataProto) {
@@ -4353,56 +4356,76 @@ JSObject* CType::DefineBuiltin(JSContext
   // Define the CType as a 'propName' property on 'ctypesObj'.
   if (!JS_DefineProperty(cx, ctypesObj, propName, typeObj,
                          JSPROP_ENUMERATE | JSPROP_READONLY | JSPROP_PERMANENT))
     return nullptr;
 
   return typeObj;
 }
 
+static void FinalizeFFIType(JSFreeOp* fop, JSObject* obj, const Value& slot,
+                            size_t elementCount) {
+  ffi_type* ffiType = static_cast<ffi_type*>(slot.toPrivate());
+  size_t size = elementCount * sizeof(ffi_type*);
+  FreeOp::get(fop)->free_(obj, ffiType->elements, size,
+                          MemoryUse::CTypeFFITypeElements);
+  FreeOp::get(fop)->delete_(obj, ffiType, MemoryUse::CTypeFFIType);
+}
+
 void CType::Finalize(JSFreeOp* fop, JSObject* obj) {
   // Make sure our TypeCode slot is legit. If it's not, bail.
   Value slot = JS_GetReservedSlot(obj, SLOT_TYPECODE);
   if (slot.isUndefined()) {
     return;
   }
 
   // The contents of our slots depends on what kind of type we are.
   switch (TypeCode(slot.toInt32())) {
     case TYPE_function: {
       // Free the FunctionInfo.
       slot = JS_GetReservedSlot(obj, SLOT_FNINFO);
       if (!slot.isUndefined()) {
-        FreeOp::get(fop)->delete_(static_cast<FunctionInfo*>(slot.toPrivate()));
+        auto fninfo = static_cast<FunctionInfo*>(slot.toPrivate());
+        FreeOp::get(fop)->delete_(obj, fninfo, MemoryUse::CTypeFunctionInfo);
       }
       break;
     }
 
     case TYPE_struct: {
+      size_t fieldCount = 0;
+
       // Free the FieldInfoHash table.
       slot = JS_GetReservedSlot(obj, SLOT_FIELDINFO);
       if (!slot.isUndefined()) {
-        void* info = slot.toPrivate();
-        FreeOp::get(fop)->delete_(static_cast<FieldInfoHash*>(info));
+        auto info = static_cast<FieldInfoHash*>(slot.toPrivate());
+        fieldCount = info->count();
+        FreeOp::get(fop)->delete_(obj, info, MemoryUse::CTypeFieldInfo);
       }
-    }
-
-      MOZ_FALLTHROUGH;
+
+      // Free the ffi_type info.
+      Value slot = JS_GetReservedSlot(obj, SLOT_FFITYPE);
+      if (!slot.isUndefined()) {
+        size_t elementCount = fieldCount != 0 ? fieldCount + 1 : 2;
+        FinalizeFFIType(fop, obj, slot, elementCount);
+      }
+
+      // Free the ffi_type info.
+      break;
+    }
 
     case TYPE_array: {
       // Free the ffi_type info.
-      slot = JS_GetReservedSlot(obj, SLOT_FFITYPE);
+      Value slot = JS_GetReservedSlot(obj, SLOT_FFITYPE);
       if (!slot.isUndefined()) {
-        ffi_type* ffiType = static_cast<ffi_type*>(slot.toPrivate());
-        FreeOp::get(fop)->free_(ffiType->elements);
-        FreeOp::get(fop)->delete_(ffiType);
+        size_t elementCount = ArrayType::GetLength(obj);
+        FinalizeFFIType(fop, obj, slot, elementCount);
       }
-
       break;
     }
+
     default:
       // Nothing to do here.
       break;
   }
 }
 
 void CType::Trace(JSTracer* trc, JSObject* obj) {
   // Make sure our TypeCode slot is legit. If it's not, bail.
@@ -4610,17 +4633,18 @@ ffi_type* CType::GetFFIType(JSContext* c
 
     default:
       MOZ_CRASH("simple types must have an ffi_type");
   }
 
   if (!result) {
     return nullptr;
   }
-  JS_SetReservedSlot(obj, SLOT_FFITYPE, PrivateValue(result.get()));
+  JS_InitReservedSlot(obj, SLOT_FFITYPE, result.get(),
+                      JS::MemoryUse::CTypeFFIType);
   return result.release();
 }
 
 JSString* CType::GetName(JSContext* cx, HandleObject obj) {
   MOZ_ASSERT(CType::IsCType(obj));
 
   Value string = JS_GetReservedSlot(obj, SLOT_NAME);
   if (!string.isUndefined()) {
@@ -5951,18 +5975,18 @@ bool StructType::DefineInternal(JSContex
   }
 
   // Move the field hash to the heap and store it in the typeObj.
   FieldInfoHash* heapHash = cx->new_<FieldInfoHash>(std::move(fields.get()));
   if (!heapHash) {
     JS_ReportOutOfMemory(cx);
     return false;
   }
-  JS_SetReservedSlot(typeObj, SLOT_FIELDINFO, PrivateValue(heapHash));
-
+  JS_InitReservedSlot(typeObj, SLOT_FIELDINFO, heapHash,
+                      JS::MemoryUse::CTypeFieldInfo);
   JS_SetReservedSlot(typeObj, SLOT_SIZE, sizeVal);
   JS_SetReservedSlot(typeObj, SLOT_ALIGN, Int32Value(structAlign));
   // if (!JS_FreezeObject(cx, prototype)0 // XXX fixme - see bug 541212!
   //  return false;
   JS_SetReservedSlot(typeObj, SLOT_PROTO, ObjectValue(*prototype));
   return true;
 }
 
@@ -6004,16 +6028,18 @@ UniquePtrFFIType StructType::BuildFFITyp
     // Represent an empty struct as having a size of 1 byte, just like C++.
     MOZ_ASSERT(structSize == 1);
     MOZ_ASSERT(structAlign == 1);
     elements[0] = &ffi_type_uint8;
     elements[1] = nullptr;
   }
 
   ffiType->elements = elements.release();
+  AddCellMemory(obj, count * sizeof(ffi_type*),
+                MemoryUse::CTypeFFITypeElements);
 
 #ifdef DEBUG
   // Perform a sanity check: the result of our struct size and alignment
   // calculations should match libffi's. We force it to do this calculation
   // by calling ffi_prep_cif.
   ffi_cif cif;
   ffiType->size = 0;
   ffiType->alignment = 0;
@@ -6629,17 +6655,18 @@ static bool CreateFunctionInfo(JSContext
                                HandleValue abiType, HandleObject returnType,
                                const HandleValueArray& args) {
   FunctionInfo* fninfo(cx->new_<FunctionInfo>());
   if (!fninfo) {
     return false;
   }
 
   // Stash the FunctionInfo in a reserved slot.
-  JS_SetReservedSlot(typeObj, SLOT_FNINFO, PrivateValue(fninfo));
+  JS_InitReservedSlot(typeObj, SLOT_FNINFO, fninfo,
+                      JS::MemoryUse::CTypeFunctionInfo);
 
   ffi_abi abi;
   if (!GetABI(cx, abiType, &abi)) {
     JS_ReportErrorASCII(cx, "Invalid ABI specification");
     return false;
   }
   fninfo->mABI = abiType.toObjectOrNull();
 
@@ -7188,17 +7215,18 @@ JSObject* CClosure::Create(JSContext* cx
   // Copy the important bits of context into cinfo.
   cinfo->errResult = errResult.release();
   cinfo->closureObj = result;
   cinfo->typeObj = typeObj;
   cinfo->thisObj = thisObj;
   cinfo->jsfnObj = fnObj;
 
   // Stash the ClosureInfo struct on our new object.
-  JS_SetReservedSlot(result, SLOT_CLOSUREINFO, PrivateValue(cinfo));
+  JS_InitReservedSlot(result, SLOT_CLOSUREINFO, cinfo,
+                      JS::MemoryUse::CClosureInfo);
 
   // Create an ffi_closure object and initialize it.
   void* code;
   cinfo->closure =
       static_cast<ffi_closure*>(ffi_closure_alloc(sizeof(ffi_closure), &code));
   if (!cinfo->closure || !code) {
     JS_ReportErrorASCII(cx, "couldn't create closure - libffi error");
     return nullptr;
@@ -7235,17 +7263,17 @@ void CClosure::Trace(JSTracer* trc, JSOb
 void CClosure::Finalize(JSFreeOp* fop, JSObject* obj) {
   // Make sure our ClosureInfo slot is legit. If it's not, bail.
   Value slot = JS_GetReservedSlot(obj, SLOT_CLOSUREINFO);
   if (slot.isUndefined()) {
     return;
   }
 
   ClosureInfo* cinfo = static_cast<ClosureInfo*>(slot.toPrivate());
-  FreeOp::get(fop)->delete_(cinfo);
+  FreeOp::get(fop)->delete_(obj, cinfo, MemoryUse::CClosureInfo);
 }
 
 void CClosure::ClosureStub(ffi_cif* cif, void* result, void** args,
                            void* userData) {
   MOZ_ASSERT(cif);
   MOZ_ASSERT(result);
   MOZ_ASSERT(args);
   MOZ_ASSERT(userData);
@@ -7459,20 +7487,23 @@ JSObject* CData::Create(JSContext* cx, H
       return nullptr;
     }
 
     if (!source) {
       memset(data, 0, size);
     } else {
       memcpy(data, source, size);
     }
+
+    AddCellMemory(dataObj, size, MemoryUse::CDataBuffer);
   }
 
   *buffer.get() = data;
-  JS_SetReservedSlot(dataObj, SLOT_DATA, PrivateValue(buffer.release()));
+  JS_InitReservedSlot(dataObj, SLOT_DATA, buffer.release(),
+                      JS::MemoryUse::CDataBufferPtr);
 
   // If this is an array, wrap it in a proxy so we can intercept element
   // gets/sets.
 
   if (CType::GetTypeCode(typeObj) != TYPE_array) {
     return dataObj;
   }
 
@@ -7494,19 +7525,21 @@ void CData::Finalize(JSFreeOp* fop, JSOb
 
   slot = JS_GetReservedSlot(obj, SLOT_DATA);
   if (slot.isUndefined()) {
     return;
   }
   char** buffer = static_cast<char**>(slot.toPrivate());
 
   if (owns) {
-    FreeOp::get(fop)->free_(*buffer);
-  }
-  FreeOp::get(fop)->delete_(buffer);
+    JSObject* typeObj = &JS_GetReservedSlot(obj, SLOT_CTYPE).toObject();
+    size_t size = CType::GetSize(typeObj);
+    FreeOp::get(fop)->free_(obj, *buffer, size, MemoryUse::CDataBuffer);
+  }
+  FreeOp::get(fop)->delete_(obj, buffer, MemoryUse::CDataBufferPtr);
 }
 
 JSObject* CData::GetCType(JSObject* dataObj) {
   dataObj = MaybeUnwrapArrayWrapper(dataObj);
   MOZ_ASSERT(CData::IsCData(dataObj));
 
   Value slot = JS_GetReservedSlot(dataObj, SLOT_CTYPE);
   JSObject* typeObj = slot.toObjectOrNull();
@@ -8409,32 +8442,33 @@ JSObject* Int64Base::Construct(JSContext
   }
 
   // attach the Int64's data
   uint64_t* buffer = cx->new_<uint64_t>(data);
   if (!buffer) {
     return nullptr;
   }
 
-  JS_SetReservedSlot(result, SLOT_INT64, PrivateValue(buffer));
+  JS_InitReservedSlot(result, SLOT_INT64, buffer, JS::MemoryUse::CTypesInt64);
 
   if (!JS_FreezeObject(cx, result)) {
     return nullptr;
   }
 
   return result;
 }
 
 void Int64Base::Finalize(JSFreeOp* fop, JSObject* obj) {
   Value slot = JS_GetReservedSlot(obj, SLOT_INT64);
   if (slot.isUndefined()) {
     return;
   }
 
-  FreeOp::get(fop)->delete_(static_cast<uint64_t*>(slot.toPrivate()));
+  uint64_t* buffer = static_cast<uint64_t*>(slot.toPrivate());
+  FreeOp::get(fop)->delete_(obj, buffer, MemoryUse::CTypesInt64);
 }
 
 uint64_t Int64Base::GetInt(JSObject* obj) {
   MOZ_ASSERT(Int64::IsInt64(obj) || UInt64::IsUInt64(obj));
 
   Value slot = JS_GetReservedSlot(obj, SLOT_INT64);
   return *static_cast<uint64_t*>(slot.toPrivate());
 }
--- a/js/src/gc/GC.cpp
+++ b/js/src/gc/GC.cpp
@@ -4435,17 +4435,17 @@ static void RelazifyFunctionsForShrinkin
 static void PurgeShapeCachesForShrinkingGC(JSRuntime* rt) {
   gcstats::AutoPhase ap(rt->gc.stats(), gcstats::PhaseKind::PURGE_SHAPE_CACHES);
   for (GCZonesIter zone(rt); !zone.done(); zone.next()) {
     if (!CanRelocateZone(zone) || zone->keepShapeCaches()) {
       continue;
     }
     for (auto baseShape = zone->cellIterUnsafe<BaseShape>(); !baseShape.done();
          baseShape.next()) {
-      baseShape->maybePurgeCache();
+      baseShape->maybePurgeCache(rt->defaultFreeOp());
     }
   }
 }
 
 static void UnmarkCollectedZones(GCParallelTask* task) {
   JSRuntime* rt = task->runtime();
   for (GCZonesIter zone(rt); !zone.done(); zone.next()) {
     /* Unmark everything in the zones being collected. */
--- a/js/src/gc/GCEnum.h
+++ b/js/src/gc/GCEnum.h
@@ -92,17 +92,24 @@ enum class ZealMode {
 } /* namespace gc */
 
 #define JS_FOR_EACH_INTERNAL_MEMORY_USE(_) \
   _(ArrayBufferContents)                   \
   _(StringContents)                        \
   _(ObjectElements)                        \
   _(ObjectSlots)                           \
   _(ScriptPrivateData)                     \
-  _(LazyScriptData)
+  _(LazyScriptData)                        \
+  _(MapObjectTable)                        \
+  _(BigIntDigits)                          \
+  _(ScopeData)                             \
+  _(WeakMapObject)                         \
+  _(ShapeKids)                             \
+  _(ShapeCache)                            \
+  _(ModuleBindingMap)
 
 #define JS_FOR_EACH_MEMORY_USE(_)  \
   JS_FOR_EACH_PUBLIC_MEMORY_USE(_) \
   JS_FOR_EACH_INTERNAL_MEMORY_USE(_)
 
 enum class MemoryUse : uint8_t {
 #define DEFINE_MEMORY_USE(Name) Name,
   JS_FOR_EACH_MEMORY_USE(DEFINE_MEMORY_USE)
--- a/js/src/jsapi.cpp
+++ b/js/src/jsapi.cpp
@@ -3029,16 +3029,22 @@ JS_PUBLIC_API Value JS_GetReservedSlot(J
   return obj->as<NativeObject>().getReservedSlot(index);
 }
 
 JS_PUBLIC_API void JS_SetReservedSlot(JSObject* obj, uint32_t index,
                                       const Value& value) {
   obj->as<NativeObject>().setReservedSlot(index, value);
 }
 
+JS_PUBLIC_API void JS_InitReservedSlot(JSObject* obj, uint32_t index, void* ptr,
+                                       size_t nbytes, JS::MemoryUse use) {
+  InitReservedSlot(&obj->as<NativeObject>(), index, ptr, nbytes,
+                   js::MemoryUse(use));
+}
+
 JS_PUBLIC_API JSObject* JS_NewArrayObject(
     JSContext* cx, const JS::HandleValueArray& contents) {
   MOZ_ASSERT(!cx->zone()->isAtomsZone());
   AssertHeapIsIdle();
   CHECK_THREAD(cx);
 
   cx->check(contents);
   return NewDenseCopiedArray(cx, contents.length(), contents.begin());
--- a/js/src/jsapi.h
+++ b/js/src/jsapi.h
@@ -29,16 +29,17 @@
 #include "js/CallArgs.h"
 #include "js/CharacterEncoding.h"
 #include "js/Class.h"
 #include "js/CompileOptions.h"
 #include "js/ErrorReport.h"
 #include "js/GCVector.h"
 #include "js/HashTable.h"
 #include "js/Id.h"
+#include "js/MemoryFunctions.h"
 #include "js/OffThreadScriptCompilation.h"
 #include "js/Principals.h"
 #include "js/PropertyDescriptor.h"
 #include "js/PropertySpec.h"
 #include "js/Realm.h"
 #include "js/RealmOptions.h"
 #include "js/RefCounted.h"
 #include "js/RootingAPI.h"
@@ -1761,16 +1762,26 @@ extern JS_PUBLIC_API bool IsSetObject(JS
 JS_PUBLIC_API void JS_SetAllNonReservedSlotsToUndefined(JS::HandleObject obj);
 
 extern JS_PUBLIC_API JS::Value JS_GetReservedSlot(JSObject* obj,
                                                   uint32_t index);
 
 extern JS_PUBLIC_API void JS_SetReservedSlot(JSObject* obj, uint32_t index,
                                              const JS::Value& v);
 
+extern JS_PUBLIC_API void JS_InitReservedSlot(JSObject* obj, uint32_t index,
+                                              void* ptr, size_t nbytes,
+                                              JS::MemoryUse use);
+
+template <typename T>
+void JS_InitReservedSlot(JSObject* obj, uint32_t index, T* ptr,
+                         JS::MemoryUse use) {
+  JS_InitReservedSlot(obj, index, ptr, sizeof(T), use);
+}
+
 /************************************************************************/
 
 /* native that can be called as a ctor */
 static constexpr unsigned JSFUN_CONSTRUCTOR = 0x400;
 
 /* | of all the JSFUN_* flags */
 static constexpr unsigned JSFUN_FLAGS_MASK = 0x400;
 
--- a/js/src/vm/BigIntType.cpp
+++ b/js/src/vm/BigIntType.cpp
@@ -91,23 +91,23 @@
 #include <math.h>
 #include <memory>
 
 #include "jsapi.h"
 #include "jsnum.h"
 
 #include "builtin/BigInt.h"
 #include "gc/Allocator.h"
-#include "gc/FreeOp.h"
 #include "js/Initialization.h"
 #include "js/StableStringChars.h"
 #include "js/Utility.h"
 #include "vm/JSContext.h"
 #include "vm/SelfHosting.h"
 
+#include "gc/FreeOp-inl.h"
 #include "vm/JSContext-inl.h"
 
 using namespace js;
 
 using JS::AutoStableStringChars;
 using mozilla::Abs;
 using mozilla::AssertedCast;
 using mozilla::BitwiseCast;
@@ -151,29 +151,31 @@ BigInt* BigInt::createUninitialized(JSCo
 
   x->lengthSignAndReservedBits_ =
       (length << LengthShift) | (isNegative ? SignBit : 0);
   MOZ_ASSERT(x->digitLength() == length);
   MOZ_ASSERT(x->isNegative() == isNegative);
 
   if (heapDigits) {
     x->heapDigits_ = heapDigits.release();
+    AddCellMemory(x, length * sizeof(Digit), js::MemoryUse::BigIntDigits);
   }
 
   return x;
 }
 
 void BigInt::initializeDigitsToZero() {
   auto digs = digits();
   std::uninitialized_fill_n(digs.begin(), digs.Length(), 0);
 }
 
 void BigInt::finalize(js::FreeOp* fop) {
   if (hasHeapDigits()) {
-    fop->free_(heapDigits_);
+    size_t size = digitLength() * sizeof(Digit);
+    fop->free_(this, heapDigits_, size, js::MemoryUse::BigIntDigits);
   }
 }
 
 js::HashNumber BigInt::hash() {
   js::HashNumber h =
       mozilla::HashBytes(digits().data(), digitLength() * sizeof(Digit));
   return mozilla::AddToHash(h, isNegative());
 }
--- a/js/src/vm/Scope.cpp
+++ b/js/src/vm/Scope.cpp
@@ -8,22 +8,22 @@
 
 #include "mozilla/ScopeExit.h"
 
 #include <memory>
 #include <new>
 
 #include "builtin/ModuleObject.h"
 #include "gc/Allocator.h"
-#include "gc/FreeOp.h"
 #include "util/StringBuffer.h"
 #include "vm/EnvironmentObject.h"
 #include "vm/JSScript.h"
 #include "wasm/WasmInstance.h"
 
+#include "gc/FreeOp-inl.h"
 #include "gc/ObjectKind-inl.h"
 #include "vm/Shape-inl.h"
 
 using namespace js;
 
 using mozilla::Maybe;
 
 const char* js::BindingKindString(BindingKind kind) {
@@ -136,30 +136,35 @@ static Shape* CreateEnvironmentShape(JSC
         return nullptr;
       }
     }
   }
 
   return shape;
 }
 
+template <class Data>
+inline size_t SizeOfAllocatedData(Data* data) {
+  return SizeOfData<Data>(data->length);
+}
+
 template <typename ConcreteScope>
 static UniquePtr<typename ConcreteScope::Data> CopyScopeData(
     JSContext* cx, typename ConcreteScope::Data* data) {
   // Make sure the binding names are marked in the context's zone, if we are
   // copying data from another zone.
   BindingName* names = data->trailingNames.start();
   uint32_t length = data->length;
   for (size_t i = 0; i < length; i++) {
     if (JSAtom* name = names[i].name()) {
       cx->markAtom(name);
     }
   }
 
-  size_t size = SizeOfData<typename ConcreteScope::Data>(data->length);
+  size_t size = SizeOfAllocatedData(data);
   void* bytes = cx->pod_malloc<char>(size);
   if (!bytes) {
     return nullptr;
   }
 
   auto* dataCopy = new (bytes) typename ConcreteScope::Data(*data);
 
   std::uninitialized_copy_n(names, length, dataCopy->trailingNames.start());
@@ -329,16 +334,20 @@ ConcreteScope* Scope::create(
 
   return &scope->as<ConcreteScope>();
 }
 
 template <typename ConcreteScope>
 inline void Scope::initData(
     MutableHandle<UniquePtr<typename ConcreteScope::Data>> data) {
   MOZ_ASSERT(!data_);
+
+  AddCellMemory(this, SizeOfAllocatedData(data.get().get()),
+                MemoryUse::ScopeData);
+
   data_ = data.get().release();
 }
 
 uint32_t Scope::chainLength() const {
   uint32_t length = 0;
   for (ScopeIter si(const_cast<Scope*>(this)); si; si++) {
     length++;
   }
@@ -448,17 +457,19 @@ Scope* Scope::clone(JSContext* cx, Handl
       break;
   }
 
   return nullptr;
 }
 
 void Scope::finalize(FreeOp* fop) {
   MOZ_ASSERT(CurrentThreadIsGCSweeping());
-  applyScopeDataTyped([fop](auto data) { fop->delete_(data); });
+  applyScopeDataTyped([this, fop](auto data) {
+    fop->delete_(this, data, SizeOfAllocatedData(data), MemoryUse::ScopeData);
+  });
   data_ = nullptr;
 }
 
 size_t Scope::sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
   if (data_) {
     return mallocSizeOf(data_);
   }
   return 0;
--- a/js/src/vm/Shape.cpp
+++ b/js/src/vm/Shape.cpp
@@ -167,20 +167,38 @@ bool Shape::hashify(JSContext* cx, Shape
   if (!table) {
     return false;
   }
 
   if (!table->init(cx, shape)) {
     return false;
   }
 
-  shape->base()->setTable(table.release());
+  BaseShape* base = shape->base();
+  base->maybePurgeCache(cx->defaultFreeOp());
+  base->setTable(table.release());
+  // TODO: The contents of ShapeTable is not currently tracked, only the object
+  // itself.
+  AddCellMemory(base, sizeof(ShapeTable), MemoryUse::ShapeCache);
   return true;
 }
 
+void ShapeCachePtr::maybePurgeCache(FreeOp* fop, BaseShape* base) {
+  if (isTable()) {
+    ShapeTable* table = getTablePointer();
+    if (table->freeList() == SHAPE_INVALID_SLOT) {
+      fop->delete_(base, getTablePointer(), MemoryUse::ShapeCache);
+      p = 0;
+    }
+  } else if (isIC()) {
+    fop->delete_<ShapeIC>(base, getICPointer(), MemoryUse::ShapeCache);
+    p = 0;
+  }
+}
+
 /* static */
 bool Shape::cachify(JSContext* cx, Shape* shape) {
   MOZ_ASSERT(!shape->hasTable() && !shape->hasIC());
 
   if (!shape->ensureOwnBaseShape(cx)) {
     return false;
   }
 
@@ -189,16 +207,17 @@ bool Shape::cachify(JSContext* cx, Shape
     return false;
   }
 
   if (!ic->init(cx)) {
     return false;
   }
 
   shape->base()->setIC(ic.release());
+  AddCellMemory(shape->base(), sizeof(ShapeIC), MemoryUse::ShapeCache);
   return true;
 }
 
 bool ShapeTable::change(JSContext* cx, int log2Delta) {
   MOZ_ASSERT(entries_);
   MOZ_ASSERT(-1 <= log2Delta && log2Delta <= 1);
 
   /*
@@ -281,16 +300,25 @@ void ShapeTable::trace(JSTracer* trc) {
       TraceManuallyBarrieredEdge(trc, &shape, "ShapeTable shape");
       if (shape != entry.shape()) {
         entry.setPreservingCollision(shape);
       }
     }
   }
 }
 
+inline void ShapeCachePtr::destroy(FreeOp* fop, BaseShape* base) {
+  if (isTable()) {
+    fop->delete_(base, getTablePointer(), MemoryUse::ShapeCache);
+  } else if (isIC()) {
+    fop->delete_(base, getICPointer(), MemoryUse::ShapeCache);
+  }
+  p = 0;
+}
+
 #ifdef JSGC_HASH_TABLE_CHECKS
 
 void ShapeCachePtr::checkAfterMovingGC() {
   if (isIC()) {
     getICPointer()->checkAfterMovingGC();
   } else if (isTable()) {
     getTablePointer()->checkAfterMovingGC();
   }
@@ -1651,17 +1679,17 @@ void Zone::checkBaseShapeTableAfterMovin
     MOZ_RELEASE_ASSERT(ptr.found() && &*ptr == &r.front());
   }
 }
 
 #endif  // JSGC_HASH_TABLE_CHECKS
 
 void BaseShape::finalize(FreeOp* fop) {
   if (cache_.isInitialized()) {
-    cache_.destroy(fop);
+    cache_.destroy(fop, this);
   }
 }
 
 inline InitialShapeEntry::InitialShapeEntry() : shape(nullptr), proto() {}
 
 inline InitialShapeEntry::InitialShapeEntry(Shape* shape,
                                             const TaggedProto& proto)
     : shape(shape), proto(proto) {}
@@ -1746,16 +1774,17 @@ bool PropertyTree::insertChild(JSContext
     MOZ_ASSERT(!shape->matches(child));
 
     KidsHash* hash = HashChildren(shape, child);
     if (!hash) {
       ReportOutOfMemory(cx);
       return false;
     }
     kidp->setHash(hash);
+    AddCellMemory(parent, sizeof(KidsHash), MemoryUse::ShapeKids);
     child->setParent(parent);
     return true;
   }
 
   if (!kidp->toHash()->putNew(StackShape(child), child)) {
     ReportOutOfMemory(cx);
     return false;
   }
@@ -1791,16 +1820,17 @@ void Shape::removeChild(Shape* child) {
 
   if (hash->count() == 1) {
     /* Convert from HASH form back to SHAPE form. */
     KidsHash::Range r = hash->all();
     Shape* otherChild = r.front();
     MOZ_ASSERT((r.popFront(), r.empty())); /* No more elements! */
     kidp->setShape(otherChild);
     js_delete(hash);
+    RemoveCellMemory(this, sizeof(KidsHash), MemoryUse::ShapeKids);
   }
 }
 
 MOZ_ALWAYS_INLINE Shape* PropertyTree::inlinedGetChild(
     JSContext* cx, Shape* parent, Handle<StackShape> child) {
   MOZ_ASSERT(parent);
 
   Shape* existingShape = nullptr;
@@ -1870,17 +1900,17 @@ void Shape::sweep() {
     } else {
       parent->removeChild(this);
     }
   }
 }
 
 void Shape::finalize(FreeOp* fop) {
   if (!inDictionary() && kids.isHash()) {
-    fop->delete_(kids.toHash());
+    fop->delete_(this, kids.toHash(), MemoryUse::ShapeKids);
   }
 }
 
 void Shape::fixupDictionaryShapeAfterMovingGC() {
   if (!listp) {
     return;
   }
 
--- a/js/src/vm/Shape.h
+++ b/js/src/vm/Shape.h
@@ -483,20 +483,19 @@ class ShapeCachePtr {
   }
 
   ShapeIC* getICPointer() const {
     MOZ_ASSERT(isIC());
     return reinterpret_cast<ShapeIC*>(getPointer());
   }
 
   // Use ShapeTable implementation.
-  // This will clobber an existing IC implementation.
+  // The caller must have purged any existing IC implementation.
   void initializeTable(ShapeTable* table) {
-    MOZ_ASSERT(!isTable());
-    maybePurgeCache();
+    MOZ_ASSERT(!isTable() && !isIC());
 
     uintptr_t tableptr = uintptr_t(table);
 
     // Double check that pointer is 4 byte aligned.
     MOZ_ASSERT((tableptr & CACHETYPE_MASK) == 0);
 
     tableptr |= static_cast<uintptr_t>(CacheType::Table);
     p = tableptr;
@@ -511,37 +510,19 @@ class ShapeCachePtr {
 
     // Double check that pointer is 4 byte aligned.
     MOZ_ASSERT((icptr & CACHETYPE_MASK) == 0);
 
     icptr |= static_cast<uintptr_t>(CacheType::IC);
     p = icptr;
   }
 
-  void destroy(FreeOp* fop) {
-    if (isTable()) {
-      fop->delete_<ShapeTable>(getTablePointer());
-    } else if (isIC()) {
-      fop->delete_<ShapeIC>(getICPointer());
-    }
-    p = 0;
-  }
+  void destroy(FreeOp* fop, BaseShape* base);
 
-  void maybePurgeCache() {
-    if (isTable()) {
-      ShapeTable* table = getTablePointer();
-      if (table->freeList() == SHAPE_INVALID_SLOT) {
-        js_delete<ShapeTable>(getTablePointer());
-        p = 0;
-      }
-    } else if (isIC()) {
-      js_delete<ShapeIC>(getICPointer());
-      p = 0;
-    }
-  }
+  void maybePurgeCache(FreeOp* fop, BaseShape* base);
 
   void trace(JSTracer* trc);
 
   size_t sizeOfExcludingThis(mozilla::MallocSizeOf mallocSizeOf) const {
     size_t size = 0;
     if (isIC()) {
       size = getICPointer()->sizeOfIncludingThis(mallocSizeOf);
     } else if (isTable()) {
@@ -754,17 +735,17 @@ class BaseShape : public gc::TenuredCell
     return (cache_.isIC()) ? cache_.getICPointer() : nullptr;
   }
 
   ShapeIC* maybeIC(const JS::AutoCheckCannotGC&) const {
     MOZ_ASSERT_IF(cache_.isInitialized(), isOwned());
     return (cache_.isIC()) ? cache_.getICPointer() : nullptr;
   }
 
-  void maybePurgeCache() { cache_.maybePurgeCache(); }
+  void maybePurgeCache(FreeOp* fop) { cache_.maybePurgeCache(fop, this); }
 
   uint32_t slotSpan() const {
     MOZ_ASSERT(isOwned());
     return slotSpan_;
   }
   void setSlotSpan(uint32_t slotSpan) {
     MOZ_ASSERT(isOwned());
     slotSpan_ = slotSpan;
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/allocator/buildflags.h
@@ -0,0 +1,18 @@
+/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* vim: set ts=8 sts=2 et sw=2 tw=80: */
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+// This is a copy of a file that is generated by the chromium build, with
+// only the build flags we require.
+
+// Generated by build/write_buildflag_header.py
+// From "//base/allocator:buildflags"
+
+#ifndef BASE_ALLOCATOR_BUILDFLAGS_H_
+#define BASE_ALLOCATOR_BUILDFLAGS_H_
+
+#include "build/buildflag.h"
+
+#endif  // BASE_ALLOCATOR_BUILDFLAGS_H_
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/allocator/partition_allocator/page_allocator.h
@@ -0,0 +1,21 @@
+/* -*- 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/allocator/partition_allocator/page_allocator.h.
+// To provide to an empty ReleaseReservation function, because we never call
+// ReserveAddressSpace.
+
+#ifndef BASE_ALLOCATOR_PARTITION_ALLOCATOR_PAGE_ALLOCATOR_H_
+#define BASE_ALLOCATOR_PARTITION_ALLOCATOR_PAGE_ALLOCATOR_H_
+
+namespace base {
+
+BASE_EXPORT void ReleaseReservation() {}
+
+}  // namespace base
+
+#endif  // BASE_ALLOCATOR_PARTITION_ALLOCATOR_PAGE_ALLOCATOR_H_
--- a/security/sandbox/chromium-shim/base/debug/activity_tracker.h
+++ b/security/sandbox/chromium-shim/base/debug/activity_tracker.h
@@ -20,16 +20,22 @@ class PlatformThreadHandle;
 class WaitableEvent;
 
 namespace internal {
 class LockImpl;
 }
 
 namespace debug {
 
+class BASE_EXPORT GlobalActivityTracker {
+ public:
+  static bool IsEnabled() { return false; }
+  DISALLOW_COPY_AND_ASSIGN(GlobalActivityTracker);
+};
+
 class BASE_EXPORT ScopedLockAcquireActivity
 {
  public:
   ALWAYS_INLINE
   explicit ScopedLockAcquireActivity(const base::internal::LockImpl* lock) {}
   DISALLOW_COPY_AND_ASSIGN(ScopedLockAcquireActivity);
 };
 
@@ -44,13 +50,12 @@ class BASE_EXPORT ScopedEventWaitActivit
 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_
rename from security/sandbox/chromium-shim/base/debug/debugging_flags.h
rename to security/sandbox/chromium-shim/base/debug/debugging_buildflags.h
--- a/security/sandbox/chromium-shim/base/debug/debugging_flags.h
+++ b/security/sandbox/chromium-shim/base/debug/debugging_buildflags.h
@@ -1,19 +1,21 @@
 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
 /* This Source Code Form is subject to the terms of the Mozilla Public
  * License, v. 2.0. If a copy of the MPL was not distributed with this
  * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
 
-// This is a copy of a file that is generated by the chromium build.
+// This is a copy of a file that is generated by the chromium build, with
+// only the build flags we require.
 
 // Generated by build/write_buildflag_header.py
-// From "//base:debugging_flags"
+// From "//base:debugging_buildflags"
 
-#ifndef BASE_DEBUG_DEBUGGING_FLAGS_H_
-#define BASE_DEBUG_DEBUGGING_FLAGS_H_
+#ifndef BASE_DEBUG_DEBUGGING_BUILDFLAGS_H_ 
+#define BASE_DEBUG_DEBUGGING_BUILDFLAGS_H_
 
 #include "build/buildflag.h"
 
+#define BUILDFLAG_INTERNAL_ENABLE_LOCATION_SOURCE() (1)
 #define BUILDFLAG_INTERNAL_ENABLE_PROFILING() (0)
 
-#endif  // BASE_DEBUG_DEBUGGING_FLAGS_H_
+#endif  // BASE_DEBUG_DEBUGGING_BUILDFLAGS_H_
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/feature_list.h
@@ -0,0 +1,50 @@
+/* -*- 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 base/feature_list.h.
+// This just returns the default state for a feature.
+
+#ifndef BASE_FEATURE_LIST_H_
+#define BASE_FEATURE_LIST_H_
+
+namespace base {
+
+// Specifies whether a given feature is enabled or disabled by default.
+enum FeatureState {
+  FEATURE_DISABLED_BY_DEFAULT,
+  FEATURE_ENABLED_BY_DEFAULT,
+};
+
+// The Feature struct is used to define the default state for a feature. See
+// comment below for more details. There must only ever be one struct instance
+// for a given feature name - generally defined as a constant global variable or
+// file static. It should never be used as a constexpr as it breaks
+// pointer-based identity lookup.
+struct BASE_EXPORT Feature {
+  // The name of the feature. This should be unique to each feature and is used
+  // for enabling/disabling features via command line flags and experiments.
+  // It is strongly recommended to use CamelCase style for feature names, e.g.
+  // "MyGreatFeature".
+  const char* const name;
+
+  // The default state (i.e. enabled or disabled) for this feature.
+  const FeatureState default_state;
+};
+
+class BASE_EXPORT FeatureList {
+ public:
+  static bool IsEnabled(const Feature& feature) {
+    return feature.default_state == FEATURE_ENABLED_BY_DEFAULT;
+  }
+
+  static FeatureList* GetInstance() { return nullptr; }
+
+  DISALLOW_COPY_AND_ASSIGN(FeatureList);
+};
+
+}  // namespace base
+
+#endif  // BASE_FEATURE_LIST_H_
--- a/security/sandbox/chromium-shim/base/file_version_info_win.h
+++ b/security/sandbox/chromium-shim/base/file_version_info_win.h
@@ -17,15 +17,15 @@ struct tagVS_FIXEDFILEINFO;
 typedef tagVS_FIXEDFILEINFO VS_FIXEDFILEINFO;
 
 namespace base {
 class FilePath;
 }
 
 class FileVersionInfoWin {
  public:
-  static FileVersionInfoWin*
-    CreateFileVersionInfo(const base::FilePath& file_path) { MOZ_CRASH(); }
+  static std::unique_ptr<FileVersionInfoWin> CreateFileVersionInfoWin(
+      const base::FilePath& file_path) { MOZ_CRASH(); }
 
   VS_FIXEDFILEINFO* fixed_file_info() { MOZ_CRASH(); }
 };
 
 #endif  // BASE_FILE_VERSION_INFO_WIN_H_
--- a/security/sandbox/chromium-shim/base/logging.cpp
+++ b/security/sandbox/chromium-shim/base/logging.cpp
@@ -82,25 +82,16 @@ template std::string* MakeCheckOpString<
     const unsigned long&, const unsigned long&, const char* names);
 template std::string* MakeCheckOpString<unsigned long, unsigned int>(
     const unsigned long&, const unsigned int&, const char* names);
 template std::string* MakeCheckOpString<unsigned int, unsigned long>(
     const unsigned int&, const unsigned long&, const char* names);
 template std::string* MakeCheckOpString<std::string, std::string>(
     const std::string&, const std::string&, const char* name);
 
-#if defined(OS_WIN)
-LogMessage::SaveLastError::SaveLastError() : last_error_(::GetLastError()) {
-}
-
-LogMessage::SaveLastError::~SaveLastError() {
-  ::SetLastError(last_error_);
-}
-#endif  // defined(OS_WIN)
-
 LogMessage::LogMessage(const char* file, int line, LogSeverity severity)
     : severity_(severity), file_(file), line_(line) {
 }
 
 LogMessage::LogMessage(const char* file, int line, const char* condition)
     : severity_(LOG_FATAL), file_(file), line_(line) {
 }
 
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/metrics/histogram_functions.h
@@ -0,0 +1,20 @@
+/* -*- 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_functions.h.
+// To provide to empty histogram functions required for compilation.
+// We don't require Chromiums histogram collection code.
+
+#ifndef BASE_METRICS_HISTOGRAM_FUNCTIONS_H_
+#define BASE_METRICS_HISTOGRAM_FUNCTIONS_H_
+
+namespace base {
+
+BASE_EXPORT void UmaHistogramSparse(const std::string& name, int sample) {}
+
+}  // namespace base
+
+#endif  // BASE_METRICS_HISTOGRAM_FUNCTIONS_H_
--- a/security/sandbox/chromium-shim/base/metrics/histogram_macros.h
+++ b/security/sandbox/chromium-shim/base/metrics/histogram_macros.h
@@ -1,18 +1,17 @@
 /* -*- 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.
+// To provide empty histogram macros required for compilation.
 // 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)
+#define SCOPED_UMA_HISTOGRAM_TIMER(name) do { } while (0)
 
 #endif  // BASE_METRICS_HISTOGRAM_MACROS_H_
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/synchronization/synchronization_buildflags.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/BUILD.gn.
+
+#ifndef BASE_SYNCHRONIZATION_SYNCHRONIZATION_BUILDFLAGS_H_
+#define BASE_SYNCHRONIZATION_SYNCHRONIZATION_BUILDFLAGS_H_
+
+#include "build/buildflag.h"
+
+#define BUILDFLAG_INTERNAL_ENABLE_MUTEX_PRIORITY_INHERITANCE() (0)
+
+#endif  // BASE_SYNCHRONIZATION_SYNCHRONIZATION_BUILDFLAGS_H_
--- a/security/sandbox/chromium-shim/base/threading/platform_thread_linux.cpp
+++ b/security/sandbox/chromium-shim/base/threading/platform_thread_linux.cpp
@@ -23,31 +23,36 @@ const struct sched_param kRealTimePrio =
 
 const ThreadPriorityToNiceValuePair kThreadPriorityToNiceValueMap[4] = {
     {ThreadPriority::BACKGROUND, 10},
     {ThreadPriority::NORMAL, 0},
     {ThreadPriority::DISPLAY, -8},
     {ThreadPriority::REALTIME_AUDIO, -10},
 };
 
+
+Optional<bool> CanIncreaseCurrentThreadPriorityForPlatform(
+    ThreadPriority priority) {
+  MOZ_CRASH();
+}
+
 bool SetCurrentThreadPriorityForPlatform(ThreadPriority priority) {
   MOZ_CRASH();
 }
 
-bool GetCurrentThreadPriorityForPlatform(ThreadPriority* priority) {
+Optional<ThreadPriority> GetCurrentThreadPriorityForPlatform() {
   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 base::make_optional(ThreadPriority::REALTIME_AUDIO);
   }
-  return false;
+  return base::nullopt;
 }
 
 }  // namespace internal
 
 void InitThreading() {}
 
 void TerminateOnThread() {}
 
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/base/threading/scoped_blocking_call.h
@@ -0,0 +1,45 @@
+/* -*- 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/threading/scoped_blocking_call.h
+// To provide to a dummy ScopedBlockingCall class. This prevents dependency
+// creep and we don't use the rest of the blocking call checking.
+
+#ifndef BASE_THREADING_SCOPED_BLOCKING_CALL_H
+#define BASE_THREADING_SCOPED_BLOCKING_CALL_H
+
+#include "base/base_export.h"
+
+namespace base {
+
+enum class BlockingType {
+  // The call might block (e.g. file I/O that might hit in memory cache).
+  MAY_BLOCK,
+  // The call will definitely block (e.g. cache already checked and now pinging
+  // server synchronously).
+  WILL_BLOCK
+};
+
+class BASE_EXPORT ScopedBlockingCall {
+ public:
+  ScopedBlockingCall(BlockingType blocking_type) {};
+  ~ScopedBlockingCall() {};
+};
+
+namespace internal {
+
+class BASE_EXPORT ScopedBlockingCallWithBaseSyncPrimitives {
+ public:
+  ScopedBlockingCallWithBaseSyncPrimitives(BlockingType blocking_type) {};
+  ~ScopedBlockingCallWithBaseSyncPrimitives() {};
+};
+
+}  // namespace internal
+
+}  // namespace base
+
+#endif  // BASE_THREADING_SCOPED_BLOCKING_CALL_H
rename from security/sandbox/chromium-shim/base/win/base_features.h
rename to security/sandbox/chromium-shim/base/win/base_win_buildflags.h
--- a/security/sandbox/chromium-shim/base/win/base_features.h
+++ b/security/sandbox/chromium-shim/base/win/base_win_buildflags.h
@@ -2,16 +2,16 @@
 /* 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_
+#ifndef BASE_WIN_BASE_WIN_BUILDFLAGS_H_ 
+#define BASE_WIN_BASE_WIN_BUILDFLAGS_H_
 
 #include "build/buildflag.h"
 
-#define BUILDFLAG_INTERNAL_SINGLE_MODULE_MODE_HANDLE_VERIFIER() (false)
+#define BUILDFLAG_INTERNAL_SINGLE_MODULE_MODE_HANDLE_VERIFIER() (0)
 
-#endif  // BASE_WIN_BASE_FEATURES_H_
+#endif  // BASE_WIN_BASE_WIN_BUILDFLAGS_H_
--- a/security/sandbox/chromium-shim/base/win/sdkdecls.h
+++ b/security/sandbox/chromium-shim/base/win/sdkdecls.h
@@ -7,82 +7,16 @@
 #ifndef _SECURITY_SANDBOX_BASE_SHIM_SDKDECLS_H_
 #define _SECURITY_SANDBOX_BASE_SHIM_SDKDECLS_H_
 
 #include <windows.h>
 
 // This file contains definitions required for things dynamically loaded
 // while building or targetting lower platform versions or lower SDKs.
 
-#if (_WIN32_WINNT < 0x0600)
-typedef struct _STARTUPINFOEXA {
-    STARTUPINFOA StartupInfo;
-    LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
-} STARTUPINFOEXA, *LPSTARTUPINFOEXA;
-typedef struct _STARTUPINFOEXW {
-    STARTUPINFOW StartupInfo;
-    LPPROC_THREAD_ATTRIBUTE_LIST lpAttributeList;
-} STARTUPINFOEXW, *LPSTARTUPINFOEXW;
-#ifdef UNICODE
-typedef STARTUPINFOEXW STARTUPINFOEX;
-typedef LPSTARTUPINFOEXW LPSTARTUPINFOEX;
-#else
-typedef STARTUPINFOEXA STARTUPINFOEX;
-typedef LPSTARTUPINFOEXA LPSTARTUPINFOEX;
-#endif // UNICODE
-
-#define PROC_THREAD_ATTRIBUTE_NUMBER    0x0000FFFF
-#define PROC_THREAD_ATTRIBUTE_THREAD    0x00010000  // Attribute may be used with thread creation
-#define PROC_THREAD_ATTRIBUTE_INPUT     0x00020000  // Attribute is input only
-#define PROC_THREAD_ATTRIBUTE_ADDITIVE  0x00040000  // Attribute may be "accumulated," e.g. bitmasks, counters, etc.
-
-#define ProcThreadAttributeValue(Number, Thread, Input, Additive) \
-    (((Number) & PROC_THREAD_ATTRIBUTE_NUMBER) | \
-     ((Thread != FALSE) ? PROC_THREAD_ATTRIBUTE_THREAD : 0) | \
-     ((Input != FALSE) ? PROC_THREAD_ATTRIBUTE_INPUT : 0) | \
-     ((Additive != FALSE) ? PROC_THREAD_ATTRIBUTE_ADDITIVE : 0))
-
-#define ProcThreadAttributeHandleList 2
-
-#define PROC_THREAD_ATTRIBUTE_HANDLE_LIST \
-    ProcThreadAttributeValue (ProcThreadAttributeHandleList, FALSE, TRUE, FALSE)
-
-#define PROCESS_DEP_ENABLE                          0x00000001
-#define PROCESS_DEP_DISABLE_ATL_THUNK_EMULATION     0x00000002
-
-// They dynamically load these, but they still use the functions to describe the
-// function pointers!
-WINBASEAPI
-int
-WINAPI
-GetUserDefaultLocaleName(
-    _Out_writes_(cchLocaleName) LPWSTR lpLocaleName,
-    _In_ int cchLocaleName
-);
-
-WINBASEAPI
-BOOL
-WINAPI
-QueryThreadCycleTime(
-    _In_ HANDLE ThreadHandle,
-    _Out_ PULONG64 CycleTime
-    );
-
-#endif // (_WIN32_WINNT >= 0x0600)
-
-#if (_WIN32_WINNT < 0x0601)
-#define ProcThreadAttributeMitigationPolicy 7
-#define PROC_THREAD_ATTRIBUTE_MITIGATION_POLICY \
-    ProcThreadAttributeValue (ProcThreadAttributeMitigationPolicy, FALSE, TRUE, FALSE)
-
-#define PROCESS_CREATION_MITIGATION_POLICY_DEP_ENABLE            0x01
-#define PROCESS_CREATION_MITIGATION_POLICY_DEP_ATL_THUNK_ENABLE  0x02
-#define PROCESS_CREATION_MITIGATION_POLICY_SEHOP_ENABLE          0x04
-#endif // (_WIN32_WINNT >= 0x0601)
-
 #if (_WIN32_WINNT < 0x0602)
 #define ProcThreadAttributeSecurityCapabilities 9
 #define PROC_THREAD_ATTRIBUTE_SECURITY_CAPABILITIES \
     ProcThreadAttributeValue (ProcThreadAttributeSecurityCapabilities, FALSE, TRUE, FALSE)
 
 #define PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_MASK                     (0x00000003 <<  8)
 #define PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_DEFER                    (0x00000000 <<  8)
 #define PROCESS_CREATION_MITIGATION_POLICY_FORCE_RELOCATE_IMAGES_ALWAYS_ON                (0x00000001 <<  8)
@@ -114,16 +48,30 @@ QueryThreadCycleTime(
 #define PROCESS_CREATION_MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_ALWAYS_OFF          (0x00000002 << 28)
 #define PROCESS_CREATION_MITIGATION_POLICY_WIN32K_SYSTEM_CALL_DISABLE_RESERVED            (0x00000003 << 28)
 #define PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_MASK                   (0x00000003uLL << 32)
 #define PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_DEFER                  (0x00000000uLL << 32)
 #define PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_ALWAYS_ON              (0x00000001uLL << 32)
 #define PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_ALWAYS_OFF             (0x00000002uLL << 32)
 #define PROCESS_CREATION_MITIGATION_POLICY_EXTENSION_POINT_DISABLE_RESERVED               (0x00000003uLL << 32)
 
+typedef struct _MEMORY_PRIORITY_INFORMATION {
+    ULONG MemoryPriority;
+} MEMORY_PRIORITY_INFORMATION, *PMEMORY_PRIORITY_INFORMATION;
+
+WINBASEAPI
+BOOL
+WINAPI
+GetThreadInformation(
+    _In_ HANDLE hThread,
+    _In_ THREAD_INFORMATION_CLASS ThreadInformationClass,
+    _Out_writes_bytes_(ThreadInformationSize) LPVOID ThreadInformation,
+    _In_ DWORD ThreadInformationSize
+    );
+
 WINBASEAPI
 BOOL
 WINAPI
 SetThreadInformation(
   _In_ HANDLE hThread,
   _In_ THREAD_INFORMATION_CLASS ThreadInformationClass,
   _In_reads_bytes_(ThreadInformationSize) LPVOID ThreadInformation,
   _In_ DWORD ThreadInformationSize
@@ -192,16 +140,80 @@ typedef struct _PROCESS_MITIGATION_EXTEN
     struct {
       DWORD DisableExtensionPoints : 1;
       DWORD ReservedFlags : 31;
     };
   };
 } PROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY, *PPROCESS_MITIGATION_EXTENSION_POINT_DISABLE_POLICY;
 
 #endif // NTDDI_WIN8
+
+WINBASEAPI
+BOOL
+WINAPI
+GetProcessMitigationPolicy(
+    _In_ HANDLE hProcess,
+    _In_ PROCESS_MITIGATION_POLICY MitigationPolicy,
+    _Out_writes_bytes_(dwLength) PVOID lpBuffer,
+    _In_ SIZE_T dwLength
+    );
+
+WINBASEAPI
+BOOL
+WINAPI
+SetProcessMitigationPolicy(
+    _In_ PROCESS_MITIGATION_POLICY MitigationPolicy,
+    _In_reads_bytes_(dwLength) PVOID lpBuffer,
+    _In_ SIZE_T dwLength
+    );
+
+#if !defined(_USERENV_)
+#define USERENVAPI DECLSPEC_IMPORT
+#else
+#define USERENVAPI
+#endif
+
+USERENVAPI
+HRESULT
+WINAPI
+CreateAppContainerProfile(_In_ PCWSTR pszAppContainerName,
+                          _In_ PCWSTR pszDisplayName,
+                          _In_ PCWSTR pszDescription,
+                          _In_reads_opt_(dwCapabilityCount)
+                              PSID_AND_ATTRIBUTES pCapabilities,
+                          _In_ DWORD dwCapabilityCount,
+                          _Outptr_ PSID* ppSidAppContainerSid);
+
+USERENVAPI
+HRESULT
+WINAPI
+DeleteAppContainerProfile(
+    _In_ PCWSTR pszAppContainerName);
+
+USERENVAPI
+HRESULT
+WINAPI
+GetAppContainerRegistryLocation(
+    _In_ REGSAM desiredAccess,
+    _Outptr_ PHKEY phAppContainerKey);
+
+USERENVAPI
+HRESULT
+WINAPI
+GetAppContainerFolderPath(
+    _In_ PCWSTR pszAppContainerSid,
+    _Outptr_ PWSTR *ppszPath);
+
+USERENVAPI
+HRESULT
+WINAPI
+DeriveAppContainerSidFromAppContainerName(
+    _In_ PCWSTR pszAppContainerName,
+    _Outptr_ PSID *ppsidAppContainerSid);
+
 #endif // (_WIN32_WINNT < 0x0602)
 
 #if (_WIN32_WINNT < 0x0603)
 //
 // Define dynamic code options.
 //
 
 #define PROCESS_CREATION_MITIGATION_POLICY_PROHIBIT_DYNAMIC_CODE_MASK                     (0x00000003uLL << 36)
@@ -273,16 +285,27 @@ typedef struct _PROCESS_MITIGATION_EXTEN
 // will prefer loading images from system32 folder.
 //
 
 #define PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_PREFER_SYSTEM32_MASK                (0x00000003uLL << 60)
 #define PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_PREFER_SYSTEM32_DEFER               (0x00000000uLL << 60)
 #define PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_PREFER_SYSTEM32_ALWAYS_ON           (0x00000001uLL << 60)
 #define PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_PREFER_SYSTEM32_ALWAYS_OFF          (0x00000002uLL << 60)
 #define PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_PREFER_SYSTEM32_RESERVED            (0x00000003uLL << 60)
+
+//
+// Define the restricted indirect branch prediction mitigation policy options.
+//
+
+#define PROCESS_CREATION_MITIGATION_POLICY2_RESTRICT_INDIRECT_BRANCH_PREDICTION_MASK        (0x00000003ui64 << 16)
+#define PROCESS_CREATION_MITIGATION_POLICY2_RESTRICT_INDIRECT_BRANCH_PREDICTION_DEFER       (0x00000000ui64 << 16)
+#define PROCESS_CREATION_MITIGATION_POLICY2_RESTRICT_INDIRECT_BRANCH_PREDICTION_ALWAYS_ON   (0x00000001ui64 << 16)
+#define PROCESS_CREATION_MITIGATION_POLICY2_RESTRICT_INDIRECT_BRANCH_PREDICTION_ALWAYS_OFF  (0x00000002ui64 << 16)
+#define PROCESS_CREATION_MITIGATION_POLICY2_RESTRICT_INDIRECT_BRANCH_PREDICTION_RESERVED    (0x00000003ui64 << 16)
+
 //
 // Define Attribute to disable creation of child process
 //
 
 #define PROCESS_CREATION_CHILD_PROCESS_RESTRICTED                                         0x01
 #define PROCESS_CREATION_CHILD_PROCESS_OVERRIDE                                           0x02
 
 //
@@ -291,10 +314,39 @@ typedef struct _PROCESS_MITIGATION_EXTEN
 
 #define PROCESS_CREATION_DESKTOP_APPX_OVERRIDE                                            0x04
 
 #define ProcThreadAttributeChildProcessPolicy 14
 
 #define PROC_THREAD_ATTRIBUTE_CHILD_PROCESS_POLICY \
     ProcThreadAttributeValue (ProcThreadAttributeChildProcessPolicy, FALSE, TRUE, FALSE)
 
+//
+// Define Attribute to opt out of matching All Application Packages
+//
+
+#define PROCESS_CREATION_ALL_APPLICATION_PACKAGES_OPT_OUT                                 0x01
+
+#define ProcThreadAttributeAllApplicationPackagesPolicy 15
+
+#define PROC_THREAD_ATTRIBUTE_ALL_APPLICATION_PACKAGES_POLICY \
+    ProcThreadAttributeValue (ProcThreadAttributeAllApplicationPackagesPolicy, FALSE, TRUE, FALSE)
+
 #endif // (_WIN32_WINNT >= 0x0A00)
+
+#if defined(__MINGW32__)
+// Required defines from winnt.h that are currently missing from MinGW.
+// Bug 1552706 tracks adding these to MinGW, so these can be removed.
+#define MEMORY_PRIORITY_VERY_LOW         1
+#define MEMORY_PRIORITY_NORMAL           5
+
+#define PROCESSOR_ARCHITECTURE_NEUTRAL          11
+#define PROCESSOR_ARCHITECTURE_ARM64            12
+#define PROCESSOR_ARCHITECTURE_ARM32_ON_WIN64   13
+#define PROCESSOR_ARCHITECTURE_IA32_ON_ARM64    14
+
+#define SECURITY_CAPABILITY_APPOINTMENTS                        (0x0000000BL)
+#define SECURITY_CAPABILITY_CONTACTS                            (0x0000000CL)
+
+#define SECURITY_BUILTIN_PACKAGE_ANY_RESTRICTED_PACKAGE (0x00000002L)
+#endif
+
 #endif // _SECURITY_SANDBOX_BASE_SHIM_SDKDECLS_H_
--- a/security/sandbox/chromium-shim/patches/after_update/add_interception_logging.patch
+++ b/security/sandbox/chromium-shim/patches/after_update/add_interception_logging.patch
@@ -1,242 +1,237 @@
 # HG changeset patch
 # User Bob Owen <bobowencode@gmail.com>
 # Date 1417281138 0
 #      Sat Nov 29 17:12:18 2014 +0000
-# Node ID 6f0003647b90c4196fa349813baaaaf425900bf5
-# Parent  4cf17a52d84ad44e38c91c9f4106241f85f7bf9e
+# Node ID 4ea2e332affe4b74bd37fbf2fee8da0b1c94e115
+# Parent  5eec91873c96c2cbfc856ba86335fa068c89d6ce
 Re-apply - Logging changes to the Chromium interception code. r=tabraldes
 
 Originally landed as changset:
 https://hg.mozilla.org/mozilla-central/rev/0f763c186855
 
 diff --git a/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc b/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc
 --- a/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc
-@@ -9,16 +9,17 @@
- #include "sandbox/win/src/crosscall_client.h"
+@@ -10,16 +10,17 @@
+ #include "sandbox/win/src/filesystem_policy.h"
  #include "sandbox/win/src/ipc_tags.h"
  #include "sandbox/win/src/policy_params.h"
  #include "sandbox/win/src/policy_target.h"
  #include "sandbox/win/src/sandbox_factory.h"
  #include "sandbox/win/src/sandbox_nt_util.h"
  #include "sandbox/win/src/sharedmem_ipc_client.h"
  #include "sandbox/win/src/target_services.h"
 +#include "mozilla/sandboxing/sandboxLogging.h"
  
  // This status occurs when trying to access a network share on the machine from
  // which it is shared.
  #define STATUS_NETWORK_OPEN_RESTRICTION ((NTSTATUS)0xC0000201L)
  
  namespace sandbox {
  
  NTSTATUS WINAPI TargetNtCreateFile(NtCreateFileFunction orig_CreateFile,
-@@ -33,16 +34,20 @@ NTSTATUS WINAPI TargetNtCreateFile(NtCre
-   NTSTATUS status = orig_CreateFile(file, desired_access, object_attributes,
-                                     io_status, allocation_size,
-                                     file_attributes, sharing, disposition,
-                                     options, ea_buffer, ea_length);
+@@ -37,16 +38,20 @@ NTSTATUS WINAPI TargetNtCreateFile(NtCre
+   // Check if the process can open it first.
+   NTSTATUS status = orig_CreateFile(
+       file, desired_access, object_attributes, io_status, allocation_size,
+       file_attributes, sharing, disposition, options, ea_buffer, ea_length);
    if (STATUS_ACCESS_DENIED != status &&
        STATUS_NETWORK_OPEN_RESTRICTION != status)
      return status;
  
 +  mozilla::sandboxing::LogBlocked("NtCreateFile",
 +                                  object_attributes->ObjectName->Buffer,
 +                                  object_attributes->ObjectName->Length);
 +
    // We don't trust that the IPC can work this early.
    if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
      return status;
  
-   wchar_t* name = NULL;
    do {
      if (!ValidParameter(file, sizeof(HANDLE), WRITE))
        break;
-@@ -90,16 +95,19 @@ NTSTATUS WINAPI TargetNtCreateFile(NtCre
+     if (!ValidParameter(io_status, sizeof(IO_STATUS_BLOCK), WRITE))
+@@ -96,16 +101,19 @@ NTSTATUS WINAPI TargetNtCreateFile(NtCre
  
      __try {
        *file = answer.handle;
        io_status->Status = answer.nt_status;
        io_status->Information = answer.extended[0].ulong_ptr;
-     } __except(EXCEPTION_EXECUTE_HANDLER) {
+     } __except (EXCEPTION_EXECUTE_HANDLER) {
        break;
      }
 +    mozilla::sandboxing::LogAllowed("NtCreateFile",
 +                                    object_attributes->ObjectName->Buffer,
 +                                    object_attributes->ObjectName->Length);
    } while (false);
  
-   if (name)
-     operator delete(name, NT_ALLOC);
- 
    return status;
  }
  
-@@ -110,16 +118,20 @@ NTSTATUS WINAPI TargetNtOpenFile(NtOpenF
+ NTSTATUS WINAPI TargetNtOpenFile(NtOpenFileFunction orig_OpenFile,
+                                  PHANDLE file,
+                                  ACCESS_MASK desired_access,
+@@ -115,16 +123,20 @@ NTSTATUS WINAPI TargetNtOpenFile(NtOpenF
                                   ULONG options) {
    // Check if the process can open it first.
    NTSTATUS status = orig_OpenFile(file, desired_access, object_attributes,
                                    io_status, sharing, options);
    if (STATUS_ACCESS_DENIED != status &&
        STATUS_NETWORK_OPEN_RESTRICTION != status)
      return status;
  
 +  mozilla::sandboxing::LogBlocked("NtOpenFile",
 +                                  object_attributes->ObjectName->Buffer,
 +                                  object_attributes->ObjectName->Length);
 +
    // We don't trust that the IPC can work this early.
    if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
      return status;
  
-   wchar_t* name = NULL;
    do {
      if (!ValidParameter(file, sizeof(HANDLE), WRITE))
        break;
-@@ -165,16 +177,19 @@ NTSTATUS WINAPI TargetNtOpenFile(NtOpenF
+     if (!ValidParameter(io_status, sizeof(IO_STATUS_BLOCK), WRITE))
+@@ -171,31 +183,38 @@ NTSTATUS WINAPI TargetNtOpenFile(NtOpenF
  
      __try {
        *file = answer.handle;
        io_status->Status = answer.nt_status;
        io_status->Information = answer.extended[0].ulong_ptr;
-     } __except(EXCEPTION_EXECUTE_HANDLER) {
+     } __except (EXCEPTION_EXECUTE_HANDLER) {
        break;
      }
 +    mozilla::sandboxing::LogAllowed("NtOpenFile",
 +                                    object_attributes->ObjectName->Buffer,
 +                                    object_attributes->ObjectName->Length);
    } while (false);
  
-   if (name)
-     operator delete(name, NT_ALLOC);
- 
    return status;
  }
  
-@@ -183,16 +198,20 @@ NTSTATUS WINAPI TargetNtQueryAttributesF
-     POBJECT_ATTRIBUTES object_attributes,
-     PFILE_BASIC_INFORMATION file_attributes) {
+ NTSTATUS WINAPI
+ TargetNtQueryAttributesFile(NtQueryAttributesFileFunction orig_QueryAttributes,
+                             POBJECT_ATTRIBUTES object_attributes,
+                             PFILE_BASIC_INFORMATION file_attributes) {
    // Check if the process can query it first.
    NTSTATUS status = orig_QueryAttributes(object_attributes, file_attributes);
    if (STATUS_ACCESS_DENIED != status &&
        STATUS_NETWORK_OPEN_RESTRICTION != status)
      return status;
  
 +  mozilla::sandboxing::LogBlocked("NtQueryAttributesFile",
 +                                  object_attributes->ObjectName->Buffer,
 +                                  object_attributes->ObjectName->Length);
 +
    // We don't trust that the IPC can work this early.
    if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
      return status;
  
-   wchar_t* name = NULL;
    do {
      if (!ValidParameter(file_attributes, sizeof(FILE_BASIC_INFORMATION), WRITE))
        break;
-@@ -223,16 +242,19 @@ NTSTATUS WINAPI TargetNtQueryAttributesF
-     ResultCode code = CrossCall(ipc, IPC_NTQUERYATTRIBUTESFILE_TAG, name,
+ 
+@@ -227,32 +246,39 @@ TargetNtQueryAttributesFile(NtQueryAttri
+     ResultCode code = CrossCall(ipc, IPC_NTQUERYATTRIBUTESFILE_TAG, name.get(),
                                  attributes, file_info, &answer);
  
      if (SBOX_ALL_OK != code)
        break;
  
      status = answer.nt_status;
  
 +    mozilla::sandboxing::LogAllowed("NtQueryAttributesFile",
 +                                    object_attributes->ObjectName->Buffer,
 +                                    object_attributes->ObjectName->Length);
    } while (false);
  
-   if (name)
-     operator delete(name, NT_ALLOC);
- 
    return status;
  }
  
-@@ -242,16 +264,20 @@ NTSTATUS WINAPI TargetNtQueryFullAttribu
+ NTSTATUS WINAPI TargetNtQueryFullAttributesFile(
+     NtQueryFullAttributesFileFunction orig_QueryFullAttributes,
+     POBJECT_ATTRIBUTES object_attributes,
      PFILE_NETWORK_OPEN_INFORMATION file_attributes) {
    // Check if the process can query it first.
-   NTSTATUS status = orig_QueryFullAttributes(object_attributes,
-                                              file_attributes);
+   NTSTATUS status =
+       orig_QueryFullAttributes(object_attributes, file_attributes);
    if (STATUS_ACCESS_DENIED != status &&
        STATUS_NETWORK_OPEN_RESTRICTION != status)
      return status;
  
 +  mozilla::sandboxing::LogBlocked("NtQueryFullAttributesFile",
 +                                  object_attributes->ObjectName->Buffer,
 +                                  object_attributes->ObjectName->Length);
 +
    // We don't trust that the IPC can work this early.
    if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
      return status;
  
-   wchar_t* name = NULL;
    do {
      if (!ValidParameter(file_attributes, sizeof(FILE_NETWORK_OPEN_INFORMATION),
                          WRITE))
-@@ -282,16 +308,20 @@ NTSTATUS WINAPI TargetNtQueryFullAttribu
+       break;
+@@ -284,16 +310,20 @@ NTSTATUS WINAPI TargetNtQueryFullAttribu
      CrossCallReturn answer = {0};
-     ResultCode code = CrossCall(ipc, IPC_NTQUERYFULLATTRIBUTESFILE_TAG, name,
-                                 attributes, file_info, &answer);
+     ResultCode code = CrossCall(ipc, IPC_NTQUERYFULLATTRIBUTESFILE_TAG,
+                                 name.get(), attributes, file_info, &answer);
  
      if (SBOX_ALL_OK != code)
        break;
  
      status = answer.nt_status;
 +
 +    mozilla::sandboxing::LogAllowed("NtQueryFullAttributesFile",
 +                                    object_attributes->ObjectName->Buffer,
 +                                    object_attributes->ObjectName->Length);
    } while (false);
  
-   if (name)
-     operator delete(name, NT_ALLOC);
- 
    return status;
  }
  
-@@ -300,16 +330,18 @@ NTSTATUS WINAPI TargetNtSetInformationFi
-     PIO_STATUS_BLOCK io_status, PVOID file_info, ULONG length,
-     FILE_INFORMATION_CLASS file_info_class) {
+ NTSTATUS WINAPI
+ TargetNtSetInformationFile(NtSetInformationFileFunction orig_SetInformationFile,
+                            HANDLE file,
+@@ -302,16 +332,18 @@ TargetNtSetInformationFile(NtSetInformat
+                            ULONG length,
+                            FILE_INFORMATION_CLASS file_info_class) {
    // Check if the process can open it first.
    NTSTATUS status = orig_SetInformationFile(file, io_status, file_info, length,
                                              file_info_class);
    if (STATUS_ACCESS_DENIED != status)
      return status;
  
 +  mozilla::sandboxing::LogBlocked("NtSetInformationFile");
 +
    // We don't trust that the IPC can work this early.
    if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
      return status;
  
-   wchar_t* name = NULL;
    do {
      void* memory = GetGlobalIPCMemory();
-     if (NULL == memory)
-@@ -361,16 +393,17 @@ NTSTATUS WINAPI TargetNtSetInformationFi
-     ResultCode code = CrossCall(ipc, IPC_NTSETINFO_RENAME_TAG, file,
-                                 io_status_buffer, file_info_buffer, length,
-                                 file_info_class, &answer);
+     if (!memory)
+       break;
+@@ -366,14 +398,15 @@ TargetNtSetInformationFile(NtSetInformat
+     ResultCode code =
+         CrossCall(ipc, IPC_NTSETINFO_RENAME_TAG, file, io_status_buffer,
+                   file_info_buffer, length, file_info_class, &answer);
  
      if (SBOX_ALL_OK != code)
        break;
  
      status = answer.nt_status;
 +    mozilla::sandboxing::LogAllowed("NtSetInformationFile");
    } while (false);
  
-   if (name)
-     operator delete(name, NT_ALLOC);
- 
    return status;
  }
  
+ }  // namespace sandbox
 diff --git a/security/sandbox/chromium/sandbox/win/src/handle_interception.cc b/security/sandbox/chromium/sandbox/win/src/handle_interception.cc
 --- a/security/sandbox/chromium/sandbox/win/src/handle_interception.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/handle_interception.cc
 @@ -5,16 +5,17 @@
  #include "sandbox/win/src/handle_interception.h"
  
  #include "sandbox/win/src/crosscall_client.h"
  #include "sandbox/win/src/ipc_tags.h"
@@ -271,52 +266,54 @@ diff --git a/security/sandbox/chromium/s
    return SBOX_ALL_OK;
  }
  
  }  // namespace sandbox
  
 diff --git a/security/sandbox/chromium/sandbox/win/src/named_pipe_interception.cc b/security/sandbox/chromium/sandbox/win/src/named_pipe_interception.cc
 --- a/security/sandbox/chromium/sandbox/win/src/named_pipe_interception.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/named_pipe_interception.cc
-@@ -7,31 +7,34 @@
+@@ -7,16 +7,17 @@
  #include "sandbox/win/src/crosscall_client.h"
  #include "sandbox/win/src/ipc_tags.h"
  #include "sandbox/win/src/policy_params.h"
  #include "sandbox/win/src/policy_target.h"
  #include "sandbox/win/src/sandbox_factory.h"
  #include "sandbox/win/src/sandbox_nt_util.h"
  #include "sandbox/win/src/sharedmem_ipc_client.h"
  #include "sandbox/win/src/target_services.h"
 +#include "mozilla/sandboxing/sandboxLogging.h"
  
  namespace sandbox {
  
- HANDLE WINAPI TargetCreateNamedPipeW(
-     CreateNamedPipeWFunction orig_CreateNamedPipeW, LPCWSTR pipe_name,
-     DWORD open_mode, DWORD pipe_mode, DWORD max_instance, DWORD out_buffer_size,
-     DWORD in_buffer_size, DWORD default_timeout,
-     LPSECURITY_ATTRIBUTES security_attributes) {
-   HANDLE pipe = orig_CreateNamedPipeW(pipe_name, open_mode, pipe_mode,
-                                       max_instance, out_buffer_size,
-                                       in_buffer_size, default_timeout,
-                                       security_attributes);
+ HANDLE WINAPI
+ TargetCreateNamedPipeW(CreateNamedPipeWFunction orig_CreateNamedPipeW,
+                        LPCWSTR pipe_name,
+                        DWORD open_mode,
+                        DWORD pipe_mode,
+@@ -26,16 +27,18 @@ TargetCreateNamedPipeW(CreateNamedPipeWF
+                        DWORD default_timeout,
+                        LPSECURITY_ATTRIBUTES security_attributes) {
+   HANDLE pipe = orig_CreateNamedPipeW(
+       pipe_name, open_mode, pipe_mode, max_instance, out_buffer_size,
+       in_buffer_size, default_timeout, security_attributes);
    if (INVALID_HANDLE_VALUE != pipe)
      return pipe;
  
 +  mozilla::sandboxing::LogBlocked("CreateNamedPipeW", pipe_name);
 +
    // We don't trust that the IPC can work this early.
    if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
      return INVALID_HANDLE_VALUE;
  
    DWORD original_error = ::GetLastError();
  
    // We don't support specific Security Attributes.
    if (security_attributes)
-@@ -57,16 +60,17 @@ HANDLE WINAPI TargetCreateNamedPipeW(
+@@ -61,16 +64,17 @@ TargetCreateNamedPipeW(CreateNamedPipeWF
      if (SBOX_ALL_OK != code)
        break;
  
      ::SetLastError(answer.win32_result);
  
      if (ERROR_SUCCESS != answer.win32_result)
        return INVALID_HANDLE_VALUE;
  
@@ -327,17 +324,17 @@ diff --git a/security/sandbox/chromium/s
    ::SetLastError(original_error);
    return INVALID_HANDLE_VALUE;
  }
  
  }  // namespace sandbox
 diff --git a/security/sandbox/chromium/sandbox/win/src/process_thread_interception.cc b/security/sandbox/chromium/sandbox/win/src/process_thread_interception.cc
 --- a/security/sandbox/chromium/sandbox/win/src/process_thread_interception.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/process_thread_interception.cc
-@@ -9,32 +9,34 @@
+@@ -10,16 +10,17 @@
  #include "sandbox/win/src/crosscall_client.h"
  #include "sandbox/win/src/ipc_tags.h"
  #include "sandbox/win/src/policy_params.h"
  #include "sandbox/win/src/policy_target.h"
  #include "sandbox/win/src/sandbox_factory.h"
  #include "sandbox/win/src/sandbox_nt_util.h"
  #include "sandbox/win/src/sharedmem_ipc_client.h"
  #include "sandbox/win/src/target_services.h"
@@ -345,219 +342,225 @@ diff --git a/security/sandbox/chromium/s
  
  namespace sandbox {
  
  SANDBOX_INTERCEPT NtExports g_nt;
  
  // Hooks NtOpenThread and proxy the call to the broker if it's trying to
  // open a thread in the same process.
  NTSTATUS WINAPI TargetNtOpenThread(NtOpenThreadFunction orig_OpenThread,
-                                    PHANDLE thread, ACCESS_MASK desired_access,
+@@ -27,16 +28,17 @@ NTSTATUS WINAPI TargetNtOpenThread(NtOpe
+                                    ACCESS_MASK desired_access,
                                     POBJECT_ATTRIBUTES object_attributes,
                                     PCLIENT_ID client_id) {
-   NTSTATUS status = orig_OpenThread(thread, desired_access, object_attributes,
-                                     client_id);
+   NTSTATUS status =
+       orig_OpenThread(thread, desired_access, object_attributes, client_id);
    if (NT_SUCCESS(status))
      return status;
  
 +  mozilla::sandboxing::LogBlocked("NtOpenThread");
    do {
      if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
        break;
      if (!client_id)
        break;
  
      uint32_t thread_id = 0;
      bool should_break = false;
-@@ -90,16 +92,17 @@ NTSTATUS WINAPI TargetNtOpenThread(NtOpe
+@@ -91,16 +93,17 @@ NTSTATUS WINAPI TargetNtOpenThread(NtOpe
  
      __try {
        // Write the output parameters.
        *thread = answer.handle;
-     } __except(EXCEPTION_EXECUTE_HANDLER) {
+     } __except (EXCEPTION_EXECUTE_HANDLER) {
        break;
      }
  
 +    mozilla::sandboxing::LogAllowed("NtOpenThread");
      return answer.nt_status;
    } while (false);
  
    return status;
  }
  
  // Hooks NtOpenProcess and proxy the call to the broker if it's trying to
  // open the current process.
-@@ -174,16 +177,17 @@ NTSTATUS WINAPI TargetNtOpenProcess(NtOp
- 
- NTSTATUS WINAPI TargetNtOpenProcessToken(
-     NtOpenProcessTokenFunction orig_OpenProcessToken, HANDLE process,
-     ACCESS_MASK desired_access, PHANDLE token) {
+@@ -176,16 +179,17 @@ NTSTATUS WINAPI
+ TargetNtOpenProcessToken(NtOpenProcessTokenFunction orig_OpenProcessToken,
+                          HANDLE process,
+                          ACCESS_MASK desired_access,
+                          PHANDLE token) {
    NTSTATUS status = orig_OpenProcessToken(process, desired_access, token);
    if (NT_SUCCESS(status))
      return status;
  
 +  mozilla::sandboxing::LogBlocked("NtOpenProcessToken");
    do {
      if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
        break;
  
      if (CURRENT_PROCESS != process)
        break;
  
      if (!ValidParameter(token, sizeof(HANDLE), WRITE))
-@@ -205,30 +209,32 @@ NTSTATUS WINAPI TargetNtOpenProcessToken
+@@ -207,16 +211,17 @@ TargetNtOpenProcessToken(NtOpenProcessTo
  
      __try {
        // Write the output parameters.
        *token = answer.handle;
-     } __except(EXCEPTION_EXECUTE_HANDLER) {
+     } __except (EXCEPTION_EXECUTE_HANDLER) {
        break;
      }
  
 +    mozilla::sandboxing::LogAllowed("NtOpenProcessToken");
      return answer.nt_status;
    } while (false);
  
    return status;
  }
  
- NTSTATUS WINAPI TargetNtOpenProcessTokenEx(
-     NtOpenProcessTokenExFunction orig_OpenProcessTokenEx, HANDLE process,
-     ACCESS_MASK desired_access, ULONG handle_attributes, PHANDLE token) {
+ NTSTATUS WINAPI
+ TargetNtOpenProcessTokenEx(NtOpenProcessTokenExFunction orig_OpenProcessTokenEx,
+@@ -224,16 +229,17 @@ TargetNtOpenProcessTokenEx(NtOpenProcess
+                            ACCESS_MASK desired_access,
+                            ULONG handle_attributes,
+                            PHANDLE token) {
    NTSTATUS status = orig_OpenProcessTokenEx(process, desired_access,
                                              handle_attributes, token);
    if (NT_SUCCESS(status))
      return status;
  
 +  mozilla::sandboxing::LogBlocked("NtOpenProcessTokenEx");
    do {
      if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
        break;
  
      if (CURRENT_PROCESS != process)
        break;
  
      if (!ValidParameter(token, sizeof(HANDLE), WRITE))
-@@ -250,16 +256,17 @@ NTSTATUS WINAPI TargetNtOpenProcessToken
+@@ -255,16 +261,17 @@ TargetNtOpenProcessTokenEx(NtOpenProcess
  
      __try {
        // Write the output parameters.
        *token = answer.handle;
-     } __except(EXCEPTION_EXECUTE_HANDLER) {
+     } __except (EXCEPTION_EXECUTE_HANDLER) {
        break;
      }
  
 +    mozilla::sandboxing::LogAllowed("NtOpenProcessTokenEx");
      return answer.nt_status;
    } while (false);
  
    return status;
  }
  
  BOOL WINAPI TargetCreateProcessW(CreateProcessWFunction orig_CreateProcessW,
-                                  LPCWSTR application_name, LPWSTR command_line,
-@@ -272,16 +279,18 @@ BOOL WINAPI TargetCreateProcessW(CreateP
+                                  LPCWSTR application_name,
+@@ -280,16 +287,18 @@ BOOL WINAPI TargetCreateProcessW(CreateP
    if (SandboxFactory::GetTargetServices()->GetState()->IsCsrssConnected() &&
        orig_CreateProcessW(application_name, command_line, process_attributes,
                            thread_attributes, inherit_handles, flags,
                            environment, current_directory, startup_info,
                            process_information)) {
-     return TRUE;
+     return true;
    }
  
 +  mozilla::sandboxing::LogBlocked("CreateProcessW", application_name);
 +
    // We don't trust that the IPC can work this early.
    if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
-     return FALSE;
+     return false;
  
    // Don't call GetLastError before InitCalled() succeeds because kernel32 may
    // not be mapped yet.
    DWORD original_error = ::GetLastError();
  
-@@ -312,16 +321,17 @@ BOOL WINAPI TargetCreateProcessW(CreateP
-                                 proc_info, &answer);
+@@ -320,16 +329,17 @@ BOOL WINAPI TargetCreateProcessW(CreateP
+                   cur_dir, current_directory, proc_info, &answer);
      if (SBOX_ALL_OK != code)
        break;
  
      ::SetLastError(answer.win32_result);
      if (ERROR_SUCCESS != answer.win32_result)
-       return FALSE;
+       return false;
  
 +    mozilla::sandboxing::LogAllowed("CreateProcessW", application_name);
-     return TRUE;
+     return true;
    } while (false);
  
    ::SetLastError(original_error);
-   return FALSE;
+   return false;
  }
  
  BOOL WINAPI TargetCreateProcessA(CreateProcessAFunction orig_CreateProcessA,
-@@ -335,16 +345,18 @@ BOOL WINAPI TargetCreateProcessA(CreateP
+@@ -346,16 +356,18 @@ BOOL WINAPI TargetCreateProcessA(CreateP
    if (SandboxFactory::GetTargetServices()->GetState()->IsCsrssConnected() &&
        orig_CreateProcessA(application_name, command_line, process_attributes,
                            thread_attributes, inherit_handles, flags,
                            environment, current_directory, startup_info,
                            process_information)) {
-     return TRUE;
+     return true;
    }
  
 +  mozilla::sandboxing::LogBlocked("CreateProcessA", application_name);
 +
    // We don't trust that the IPC can work this early.
    if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
-     return FALSE;
+     return false;
  
    // Don't call GetLastError before InitCalled() succeeds because kernel32 may
    // not be mapped yet.
    DWORD original_error = ::GetLastError();
  
-@@ -409,16 +421,17 @@ BOOL WINAPI TargetCreateProcessA(CreateP
+@@ -420,16 +432,17 @@ BOOL WINAPI TargetCreateProcessA(CreateP
  
      if (SBOX_ALL_OK != code)
        break;
  
      ::SetLastError(answer.win32_result);
      if (ERROR_SUCCESS != answer.win32_result)
-       return FALSE;
+       return false;
  
 +    mozilla::sandboxing::LogAllowed("CreateProcessA", application_name);
-     return TRUE;
+     return true;
    } while (false);
  
    ::SetLastError(original_error);
-   return FALSE;
+   return false;
  }
  
  HANDLE WINAPI TargetCreateThread(CreateThreadFunction orig_CreateThread,
 diff --git a/security/sandbox/chromium/sandbox/win/src/registry_interception.cc b/security/sandbox/chromium/sandbox/win/src/registry_interception.cc
 --- a/security/sandbox/chromium/sandbox/win/src/registry_interception.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/registry_interception.cc
-@@ -9,31 +9,38 @@
+@@ -9,16 +9,17 @@
  #include "sandbox/win/src/crosscall_client.h"
  #include "sandbox/win/src/ipc_tags.h"
  #include "sandbox/win/src/policy_params.h"
  #include "sandbox/win/src/policy_target.h"
  #include "sandbox/win/src/sandbox_factory.h"
  #include "sandbox/win/src/sandbox_nt_util.h"
  #include "sandbox/win/src/sharedmem_ipc_client.h"
  #include "sandbox/win/src/target_services.h"
 +#include "mozilla/sandboxing/sandboxLogging.h"
  
  namespace sandbox {
  
  NTSTATUS WINAPI TargetNtCreateKey(NtCreateKeyFunction orig_CreateKey,
-                                   PHANDLE key, ACCESS_MASK desired_access,
+                                   PHANDLE key,
+                                   ACCESS_MASK desired_access,
                                    POBJECT_ATTRIBUTES object_attributes,
-                                   ULONG title_index, PUNICODE_STRING class_name,
-                                   ULONG create_options, PULONG disposition) {
+                                   ULONG title_index,
+@@ -27,16 +28,22 @@ NTSTATUS WINAPI TargetNtCreateKey(NtCrea
+                                   PULONG disposition) {
    // Check if the process can create it first.
-   NTSTATUS status = orig_CreateKey(key, desired_access, object_attributes,
-                                    title_index, class_name, create_options,
-                                    disposition);
+   NTSTATUS status =
+       orig_CreateKey(key, desired_access, object_attributes, title_index,
+                      class_name, create_options, disposition);
    if (NT_SUCCESS(status))
      return status;
  
 +  if (STATUS_OBJECT_NAME_NOT_FOUND != status) {
 +    mozilla::sandboxing::LogBlocked("NtCreateKey",
 +                                    object_attributes->ObjectName->Buffer,
 +                                    object_attributes->ObjectName->Length);
 +  }
@@ -565,54 +568,55 @@ diff --git a/security/sandbox/chromium/s
    // We don't trust that the IPC can work this early.
    if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
      return status;
  
    do {
      if (!ValidParameter(key, sizeof(HANDLE), WRITE))
        break;
  
-@@ -109,16 +116,19 @@ NTSTATUS WINAPI TargetNtCreateKey(NtCrea
+@@ -114,16 +121,19 @@ NTSTATUS WINAPI TargetNtCreateKey(NtCrea
  
        if (disposition)
-        *disposition = answer.extended[0].unsigned_int;
+         *disposition = answer.extended[0].unsigned_int;
  
        status = answer.nt_status;
-     } __except(EXCEPTION_EXECUTE_HANDLER) {
+     } __except (EXCEPTION_EXECUTE_HANDLER) {
        break;
      }
 +    mozilla::sandboxing::LogAllowed("NtCreateKey",
 +                                    object_attributes->ObjectName->Buffer,
 +                                    object_attributes->ObjectName->Length);
    } while (false);
  
    return status;
  }
  
- NTSTATUS WINAPI CommonNtOpenKey(NTSTATUS status, PHANDLE key,
+ NTSTATUS WINAPI CommonNtOpenKey(NTSTATUS status,
+                                 PHANDLE key,
                                  ACCESS_MASK desired_access,
-                                 POBJECT_ATTRIBUTES object_attributes) {
-@@ -185,29 +195,38 @@ NTSTATUS WINAPI CommonNtOpenKey(NTSTATUS
-         break;
+@@ -193,30 +203,39 @@ NTSTATUS WINAPI CommonNtOpenKey(NTSTATUS
+       break;
  
      __try {
        *key = answer.handle;
        status = answer.nt_status;
-     } __except(EXCEPTION_EXECUTE_HANDLER) {
+     } __except (EXCEPTION_EXECUTE_HANDLER) {
        break;
      }
 +    mozilla::sandboxing::LogAllowed("NtOpenKey[Ex]",
 +                                    object_attributes->ObjectName->Buffer,
 +                                    object_attributes->ObjectName->Length);
    } while (false);
  
    return status;
  }
  
- NTSTATUS WINAPI TargetNtOpenKey(NtOpenKeyFunction orig_OpenKey, PHANDLE key,
+ NTSTATUS WINAPI TargetNtOpenKey(NtOpenKeyFunction orig_OpenKey,
+                                 PHANDLE key,
                                  ACCESS_MASK desired_access,
                                  POBJECT_ATTRIBUTES object_attributes) {
    // Check if the process can open it first.
    NTSTATUS status = orig_OpenKey(key, desired_access, object_attributes);
    if (NT_SUCCESS(status))
      return status;
  
 +  if (STATUS_OBJECT_NAME_NOT_FOUND != status) {
@@ -620,22 +624,22 @@ diff --git a/security/sandbox/chromium/s
 +                                    object_attributes->ObjectName->Buffer,
 +                                    object_attributes->ObjectName->Length);
 +  }
 +
    return CommonNtOpenKey(status, key, desired_access, object_attributes);
  }
  
  NTSTATUS WINAPI TargetNtOpenKeyEx(NtOpenKeyExFunction orig_OpenKeyEx,
-                                   PHANDLE key, ACCESS_MASK desired_access,
+                                   PHANDLE key,
+                                   ACCESS_MASK desired_access,
                                    POBJECT_ATTRIBUTES object_attributes,
                                    ULONG open_options) {
-   // Check if the process can open it first.
-@@ -215,12 +234,18 @@ NTSTATUS WINAPI TargetNtOpenKeyEx(NtOpen
-                                    open_options);
+@@ -225,12 +244,18 @@ NTSTATUS WINAPI TargetNtOpenKeyEx(NtOpen
+       orig_OpenKeyEx(key, desired_access, object_attributes, open_options);
  
    // We do not support open_options at this time. The 2 current known values
    // are REG_OPTION_CREATE_LINK, to open a symbolic link, and
    // REG_OPTION_BACKUP_RESTORE to open the key with special privileges.
    if (NT_SUCCESS(status) || open_options != 0)
      return status;
  
 +  if (STATUS_OBJECT_NAME_NOT_FOUND != status) {
@@ -667,79 +671,79 @@ diff --git a/security/sandbox/chromium/s
  ResultCode ProxyCreateEvent(LPCWSTR name,
                              uint32_t initial_state,
                              EVENT_TYPE event_type,
                              void* ipc_memory,
                              CrossCallReturn* answer) {
 @@ -59,16 +60,20 @@ NTSTATUS WINAPI TargetNtCreateEvent(NtCr
                                      EVENT_TYPE event_type,
                                      BOOLEAN initial_state) {
-   NTSTATUS status = orig_CreateEvent(event_handle, desired_access,
-                                      object_attributes, event_type,
-                                      initial_state);
+   NTSTATUS status =
+       orig_CreateEvent(event_handle, desired_access, object_attributes,
+                        event_type, initial_state);
    if (status != STATUS_ACCESS_DENIED || !object_attributes)
      return status;
  
 +  mozilla::sandboxing::LogBlocked("NtCreatEvent",
 +                                  object_attributes->ObjectName->Buffer,
 +                                  object_attributes->ObjectName->Length);
 +
    // We don't trust that the IPC can work this early.
    if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
      return status;
  
    do {
      if (!ValidParameter(event_handle, sizeof(HANDLE), WRITE))
        break;
  
-@@ -98,30 +103,37 @@ NTSTATUS WINAPI TargetNtCreateEvent(NtCr
+@@ -97,30 +102,37 @@ NTSTATUS WINAPI TargetNtCreateEvent(NtCr
        break;
      }
      __try {
        *event_handle = answer.handle;
        status = STATUS_SUCCESS;
-     } __except(EXCEPTION_EXECUTE_HANDLER) {
+     } __except (EXCEPTION_EXECUTE_HANDLER) {
        break;
      }
 +    mozilla::sandboxing::LogAllowed("NtCreateEvent",
 +                                    object_attributes->ObjectName->Buffer,
 +                                    object_attributes->ObjectName->Length);
    } while (false);
  
    return status;
  }
  
  NTSTATUS WINAPI TargetNtOpenEvent(NtOpenEventFunction orig_OpenEvent,
                                    PHANDLE event_handle,
                                    ACCESS_MASK desired_access,
                                    POBJECT_ATTRIBUTES object_attributes) {
-   NTSTATUS status = orig_OpenEvent(event_handle, desired_access,
-                                    object_attributes);
+   NTSTATUS status =
+       orig_OpenEvent(event_handle, desired_access, object_attributes);
    if (status != STATUS_ACCESS_DENIED || !object_attributes)
      return status;
  
 +  mozilla::sandboxing::LogBlocked("NtOpenEvent",
 +                                  object_attributes->ObjectName->Buffer,
 +                                  object_attributes->ObjectName->Length);
-+  //
++
    // We don't trust that the IPC can work this early.
    if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
      return status;
  
    do {
      if (!ValidParameter(event_handle, sizeof(HANDLE), WRITE))
        break;
  
-@@ -150,14 +162,17 @@ NTSTATUS WINAPI TargetNtOpenEvent(NtOpen
+@@ -149,14 +161,17 @@ NTSTATUS WINAPI TargetNtOpenEvent(NtOpen
        break;
      }
      __try {
        *event_handle = answer.handle;
        status = STATUS_SUCCESS;
-     } __except(EXCEPTION_EXECUTE_HANDLER) {
+     } __except (EXCEPTION_EXECUTE_HANDLER) {
        break;
      }
 +    mozilla::sandboxing::LogAllowed("NtOpenEvent",
 +                                    object_attributes->ObjectName->Buffer,
 +                                    object_attributes->ObjectName->Length);
    } while (false);
  
    return status;
--- a/security/sandbox/chromium-shim/patches/after_update/allow_flash_temporary_files.patch
+++ b/security/sandbox/chromium-shim/patches/after_update/allow_flash_temporary_files.patch
@@ -15,144 +15,144 @@ diff --git a/security/sandbox/chromium/s
 --- a/security/sandbox/chromium/sandbox/win/src/filesystem_dispatcher.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/filesystem_dispatcher.cc
 @@ -221,16 +221,25 @@ bool FilesystemDispatcher::NtQueryAttrib
    params[FileName::BROKER] = ParamPickerMake(broker);
  
    // To evaluate the policy we need to call back to the policy object. We
    // are just middlemen in the operation since is the FileSystemPolicy which
    // knows what to do.
-   EvalResult result = policy_base_->EvalPolicy(IPC_NTQUERYATTRIBUTESFILE_TAG,
-                                                params.GetBase());
+   EvalResult result =
+       policy_base_->EvalPolicy(IPC_NTQUERYATTRIBUTESFILE_TAG, params.GetBase());
  
 +  // If the policies forbid access (any result other than ASK_BROKER),
 +  // then check for user-granted access to file.
 +  if (ASK_BROKER != result &&
 +      mozilla::sandboxing::PermissionsService::GetInstance()->
 +        UserGrantedFileAccess(ipc->client_info->process_id, filename,
 +                              0, 0)) {
 +    result = ASK_BROKER;
 +  }
 +
    FILE_BASIC_INFORMATION* information =
-         reinterpret_cast<FILE_BASIC_INFORMATION*>(info->Buffer());
+       reinterpret_cast<FILE_BASIC_INFORMATION*>(info->Buffer());
    NTSTATUS nt_status;
    if (!FileSystemPolicy::QueryAttributesFileAction(result, *ipc->client_info,
                                                     *name, attributes,
                                                     information, &nt_status)) {
      ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
      return true;
 @@ -261,16 +270,25 @@ bool FilesystemDispatcher::NtQueryFullAt
    params[FileName::BROKER] = ParamPickerMake(broker);
  
    // To evaluate the policy we need to call back to the policy object. We
    // are just middlemen in the operation since is the FileSystemPolicy which
    // knows what to do.
    EvalResult result = policy_base_->EvalPolicy(
-                           IPC_NTQUERYFULLATTRIBUTESFILE_TAG, params.GetBase());
+       IPC_NTQUERYFULLATTRIBUTESFILE_TAG, params.GetBase());
  
 +  // If the policies forbid access (any result other than ASK_BROKER),
 +  // then check for user-granted access to file.
 +  if (ASK_BROKER != result &&
 +      mozilla::sandboxing::PermissionsService::GetInstance()->
 +        UserGrantedFileAccess(ipc->client_info->process_id, filename,
 +                              0, 0)) {
 +    result = ASK_BROKER;
 +  }
 +
    FILE_NETWORK_OPEN_INFORMATION* information =
-         reinterpret_cast<FILE_NETWORK_OPEN_INFORMATION*>(info->Buffer());
+       reinterpret_cast<FILE_NETWORK_OPEN_INFORMATION*>(info->Buffer());
    NTSTATUS nt_status;
-   if (!FileSystemPolicy::QueryFullAttributesFileAction(result,
-                                                        *ipc->client_info,
-                                                        *name, attributes,
-                                                        information,
-                                                        &nt_status)) {
+   if (!FileSystemPolicy::QueryFullAttributesFileAction(
+           result, *ipc->client_info, *name, attributes, information,
+           &nt_status)) {
+     ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
+     return true;
 @@ -316,16 +334,26 @@ bool FilesystemDispatcher::NtSetInformat
    params[FileName::BROKER] = ParamPickerMake(broker);
  
    // To evaluate the policy we need to call back to the policy object. We
    // are just middlemen in the operation since is the FileSystemPolicy which
    // knows what to do.
-   EvalResult result = policy_base_->EvalPolicy(IPC_NTSETINFO_RENAME_TAG,
-                                                params.GetBase());
+   EvalResult result =
+       policy_base_->EvalPolicy(IPC_NTSETINFO_RENAME_TAG, params.GetBase());
  
 +  // If the policies forbid access (any result other than ASK_BROKER),
 +  // then check for user-granted write access to file.  We only permit
 +  // the FileRenameInformation action.
 +  if (ASK_BROKER != result && info_class == FileRenameInformation &&
 +      mozilla::sandboxing::PermissionsService::GetInstance()->
 +        UserGrantedFileAccess(ipc->client_info->process_id, filename,
 +                              FILE_WRITE_ATTRIBUTES, 0)) {
 +    result = ASK_BROKER;
 +  }
 +
    IO_STATUS_BLOCK* io_status =
-         reinterpret_cast<IO_STATUS_BLOCK*>(status->Buffer());
+       reinterpret_cast<IO_STATUS_BLOCK*>(status->Buffer());
    NTSTATUS nt_status;
-   if (!FileSystemPolicy::SetInformationFileAction(result, *ipc->client_info,
-                                                   handle, rename_info, length,
-                                                   info_class, io_status,
-                                                   &nt_status)) {
+   if (!FileSystemPolicy::SetInformationFileAction(
+           result, *ipc->client_info, handle, rename_info, length, info_class,
+           io_status, &nt_status)) {
      ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
+     return true;
 diff --git a/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc b/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc
 --- a/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc
 @@ -223,19 +223,16 @@ NTSTATUS WINAPI TargetNtQueryAttributesF
-     InOutCountedBuffer file_info(file_attributes,
                                   sizeof(FILE_BASIC_INFORMATION));
  
-     uint32_t broker = FALSE;
+     uint32_t broker = BROKER_FALSE;
      CountedParameterSet<FileName> params;
-     params[FileName::NAME] = ParamPickerMake(name);
+     const wchar_t* name_ptr = name.get();
+     params[FileName::NAME] = ParamPickerMake(name_ptr);
      params[FileName::BROKER] = ParamPickerMake(broker);
  
 -    if (!QueryBroker(IPC_NTQUERYATTRIBUTESFILE_TAG, params.GetBase()))
 -      break;
 -
      SharedMemIPCClient ipc(memory);
      CrossCallReturn answer = {0};
-     ResultCode code = CrossCall(ipc, IPC_NTQUERYATTRIBUTESFILE_TAG, name,
+     ResultCode code = CrossCall(ipc, IPC_NTQUERYATTRIBUTESFILE_TAG, name.get(),
                                  attributes, file_info, &answer);
  
      if (SBOX_ALL_OK != code)
        break;
  
 @@ -290,19 +287,16 @@ NTSTATUS WINAPI TargetNtQueryFullAttribu
-     InOutCountedBuffer file_info(file_attributes,
                                   sizeof(FILE_NETWORK_OPEN_INFORMATION));
  
-     uint32_t broker = FALSE;
+     uint32_t broker = BROKER_FALSE;
      CountedParameterSet<FileName> params;
-     params[FileName::NAME] = ParamPickerMake(name);
+     const wchar_t* name_ptr = name.get();
+     params[FileName::NAME] = ParamPickerMake(name_ptr);
      params[FileName::BROKER] = ParamPickerMake(broker);
  
 -    if (!QueryBroker(IPC_NTQUERYFULLATTRIBUTESFILE_TAG, params.GetBase()))
 -      break;
 -
      SharedMemIPCClient ipc(memory);
      CrossCallReturn answer = {0};
-     ResultCode code = CrossCall(ipc, IPC_NTQUERYFULLATTRIBUTESFILE_TAG, name,
-                                 attributes, file_info, &answer);
+     ResultCode code = CrossCall(ipc, IPC_NTQUERYFULLATTRIBUTESFILE_TAG,
+                                 name.get(), attributes, file_info, &answer);
  
      if (SBOX_ALL_OK != code)
        break;
  
 @@ -369,19 +363,16 @@ NTSTATUS WINAPI TargetNtSetInformationFi
-     if (!NT_SUCCESS(ret) || !name)
        break;
  
-     uint32_t broker = FALSE;
+     uint32_t broker = BROKER_FALSE;
      CountedParameterSet<FileName> params;
-     params[FileName::NAME] = ParamPickerMake(name);
+     const wchar_t* name_ptr = name.get();
+     params[FileName::NAME] = ParamPickerMake(name_ptr);
      params[FileName::BROKER] = ParamPickerMake(broker);
  
 -    if (!QueryBroker(IPC_NTSETINFO_RENAME_TAG, params.GetBase()))
 -      break;
 -
      InOutCountedBuffer io_status_buffer(io_status, sizeof(IO_STATUS_BLOCK));
      // This is actually not an InOut buffer, only In, but using InOut facility
      // really helps to simplify the code.
      InOutCountedBuffer file_info_buffer(file_info, length);
  
      SharedMemIPCClient ipc(memory);
      CrossCallReturn answer = {0};
-     ResultCode code = CrossCall(ipc, IPC_NTSETINFO_RENAME_TAG, file,
+     ResultCode code =
--- a/security/sandbox/chromium-shim/patches/after_update/allow_rules_for_network_drive_and_non_file_devices.patch
+++ b/security/sandbox/chromium-shim/patches/after_update/allow_rules_for_network_drive_and_non_file_devices.patch
@@ -7,17 +7,17 @@
 Change to allow network drives in sandbox rules with non-file device fix. r=aklotz
 
 Originally landed in changeset:
 https://hg.mozilla.org/mozilla-central/rev/c70d06fa5302
 
 diff --git a/security/sandbox/chromium/sandbox/win/src/win_utils.cc b/security/sandbox/chromium/sandbox/win/src/win_utils.cc
 --- a/security/sandbox/chromium/sandbox/win/src/win_utils.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/win_utils.cc
-@@ -190,63 +190,68 @@ bool ResolveRegistryName(base::string16 
+@@ -190,62 +190,67 @@ bool ResolveRegistryName(base::string16 
  
    return false;
  }
  
  // |full_path| can have any of the following forms:
  //    \??\c:\some\foo\bar
  //    \Device\HarddiskVolume0\some\foo\bar
  //    \??\HarddiskVolume0\some\foo\bar
@@ -32,18 +32,18 @@ diff --git a/security/sandbox/chromium/s
    bool has_drive = StartsWithDriveLetter(path);
    bool is_device_path = IsDevicePath(path, &path);
  
    if (!has_drive && !is_device_path && !nt_path)
      return ERROR_INVALID_NAME;
  
 -  bool added_implied_device = false;
    if (!has_drive) {
--      path = base::string16(kNTDotPrefix) + path;
--      added_implied_device = true;
+-    path = base::string16(kNTDotPrefix) + path;
+-    added_implied_device = true;
 +    // Add Win32 device namespace prefix, required for some Windows APIs.
 +    path.insert(0, kNTDotPrefix);
    }
  
 -  base::string16::size_type last_pos = base::string16::npos;
 -  bool passed_once = false;
 +  // Ensure that volume path matches start of path.
 +  wchar_t vol_path[MAX_PATH];
@@ -60,18 +60,17 @@ diff --git a/security/sandbox/chromium/s
 +  }
  
    do {
 -    path = path.substr(0, last_pos);
 -
      DWORD attributes = ::GetFileAttributes(path.c_str());
      if (INVALID_FILE_ATTRIBUTES == attributes) {
        DWORD error = ::GetLastError();
-       if (error != ERROR_FILE_NOT_FOUND &&
-           error != ERROR_PATH_NOT_FOUND &&
+       if (error != ERROR_FILE_NOT_FOUND && error != ERROR_PATH_NOT_FOUND &&
 +          error != ERROR_INVALID_FUNCTION &&
            error != ERROR_INVALID_NAME) {
          // Unexpected error.
 -        if (passed_once && added_implied_device &&
 -            (path.rfind(L'\\') == kNTDotPrefixLen - 1)) {
 -          break;
 -        }
          NOTREACHED_NT();
--- a/security/sandbox/chromium-shim/patches/after_update/arm64_set_LoaderThreads.patch
+++ b/security/sandbox/chromium-shim/patches/after_update/arm64_set_LoaderThreads.patch
@@ -26,41 +26,40 @@ diff --git a/security/sandbox/chromium/s
  
  typedef struct _PROCESS_BASIC_INFORMATION {
    union {
      NTSTATUS ExitStatus;
      PVOID padding_for_x64_0;
 diff --git a/security/sandbox/chromium/sandbox/win/src/win_utils.cc b/security/sandbox/chromium/sandbox/win/src/win_utils.cc
 --- a/security/sandbox/chromium/sandbox/win/src/win_utils.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/win_utils.cc
-@@ -453,21 +453,22 @@ bool GetNtPathFromWin32Path(const base::
-   if (file == INVALID_HANDLE_VALUE)
-     return false;
+@@ -453,20 +453,21 @@ bool GetNtPathFromWin32Path(const base::
    bool rv = GetPathFromHandle(file, nt_path);
    ::CloseHandle(file);
    return rv;
  }
  
- bool WriteProtectedChildMemory(HANDLE child_process, void* address,
--                               const void* buffer, size_t length) {
-+                               const void* buffer, size_t length,
+ bool WriteProtectedChildMemory(HANDLE child_process,
+                                void* address,
+                                const void* buffer,
+-                               size_t length) {
++                               size_t length,
 +                               DWORD writeProtection) {
    // First, remove the protections.
    DWORD old_protection;
-   if (!::VirtualProtectEx(child_process, address, length,
--                          PAGE_WRITECOPY, &old_protection))
-+                          writeProtection, &old_protection))
+-  if (!::VirtualProtectEx(child_process, address, length, PAGE_WRITECOPY,
++  if (!::VirtualProtectEx(child_process, address, length, writeProtection,
+                           &old_protection))
      return false;
  
    SIZE_T written;
-   bool ok = ::WriteProcessMemory(child_process, address, buffer, length,
-                                  &written) && (length == written);
+   bool ok =
+       ::WriteProcessMemory(child_process, address, buffer, length, &written) &&
+       (length == written);
  
-   // Always attempt to restore the original protection.
-   if (!::VirtualProtectEx(child_process, address, length,
 @@ -511,16 +512,40 @@ void* GetProcessBaseAddress(HANDLE proce
                             &bytes_read) ||
        (sizeof(magic) != bytes_read)) {
      return nullptr;
    }
  
    if (magic[0] != 'M' || magic[1] != 'Z')
      return nullptr;
@@ -96,26 +95,26 @@ diff --git a/security/sandbox/chromium/s
  
  void ResolveNTFunctionPtr(const char* name, void* ptr) {
    static volatile HMODULE ntdll = NULL;
  
 diff --git a/security/sandbox/chromium/sandbox/win/src/win_utils.h b/security/sandbox/chromium/sandbox/win/src/win_utils.h
 --- a/security/sandbox/chromium/sandbox/win/src/win_utils.h
 +++ b/security/sandbox/chromium/sandbox/win/src/win_utils.h
 @@ -102,17 +102,18 @@ HKEY GetReservedKeyFromName(const base::
- // \\registry\\machine\\software\\microsoft. Returns false if the path
- // cannot be resolved.
  bool ResolveRegistryName(base::string16 name, base::string16* resolved_name);
  
  // Writes |length| bytes from the provided |buffer| into the address space of
  // |child_process|, at the specified |address|, preserving the original write
  // protection attributes. Returns true on success.
- bool WriteProtectedChildMemory(HANDLE child_process, void* address,
--                               const void* buffer, size_t length);
-+                               const void* buffer, size_t length,
+ bool WriteProtectedChildMemory(HANDLE child_process,
+                                void* address,
+                                const void* buffer,
+-                               size_t length);
++                               size_t length,
 +                               DWORD writeProtection = PAGE_WRITECOPY);
  
  // Returns true if the provided path points to a pipe.
  bool IsPipe(const base::string16& path);
  
  // Converts a NTSTATUS code to a Win32 error code.
  DWORD GetLastErrorFromNtStatus(NTSTATUS status);
  
--- a/security/sandbox/chromium-shim/patches/after_update/consult_PermissionsService_for_file_access.patch
+++ b/security/sandbox/chromium-shim/patches/after_update/consult_PermissionsService_for_file_access.patch
@@ -35,98 +35,98 @@ diff --git a/security/sandbox/chromium/s
          UINT32_TYPE,
 @@ -110,16 +112,26 @@ bool FilesystemDispatcher::NtCreateFile(
    params[OpenFile::OPTIONS] = ParamPickerMake(create_options);
    params[OpenFile::BROKER] = ParamPickerMake(broker);
  
    // To evaluate the policy we need to call back to the policy object. We
    // are just middlemen in the operation since is the FileSystemPolicy which
    // knows what to do.
-   EvalResult result = policy_base_->EvalPolicy(IPC_NTCREATEFILE_TAG,
-                                                params.GetBase());
+   EvalResult result =
+       policy_base_->EvalPolicy(IPC_NTCREATEFILE_TAG, params.GetBase());
 +
 +  // If the policies forbid access (any result other than ASK_BROKER),
 +  // then check for user-granted access to file.
 +  if (ASK_BROKER != result &&
 +      mozilla::sandboxing::PermissionsService::GetInstance()->
 +        UserGrantedFileAccess(ipc->client_info->process_id, filename,
 +                              desired_access, create_disposition)) {
 +    result = ASK_BROKER;
 +  }
 +
    HANDLE handle;
    ULONG_PTR io_information = 0;
    NTSTATUS nt_status;
-   if (!FileSystemPolicy::CreateFileAction(result, *ipc->client_info, *name,
-                                           attributes, desired_access,
-                                           file_attributes, share_access,
-                                           create_disposition, create_options,
-                                           &handle, &nt_status,
+   if (!FileSystemPolicy::CreateFileAction(
+           result, *ipc->client_info, *name, attributes, desired_access,
+           file_attributes, share_access, create_disposition, create_options,
+           &handle, &nt_status, &io_information)) {
+     ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
 @@ -157,16 +169,26 @@ bool FilesystemDispatcher::NtOpenFile(IP
    params[OpenFile::OPTIONS] = ParamPickerMake(open_options);
    params[OpenFile::BROKER] = ParamPickerMake(broker);
  
    // To evaluate the policy we need to call back to the policy object. We
    // are just middlemen in the operation since is the FileSystemPolicy which
    // knows what to do.
-   EvalResult result = policy_base_->EvalPolicy(IPC_NTOPENFILE_TAG,
-                                                params.GetBase());
+   EvalResult result =
+       policy_base_->EvalPolicy(IPC_NTOPENFILE_TAG, params.GetBase());
 +
 +  // If the policies forbid access (any result other than ASK_BROKER),
 +  // then check for user-granted access to file.
 +  if (ASK_BROKER != result &&
 +      mozilla::sandboxing::PermissionsService::GetInstance()->UserGrantedFileAccess(
 +                                    ipc->client_info->process_id, filename,
 +                                    desired_access, create_disposition)) {
 +    result = ASK_BROKER;
 +  }
 +
    HANDLE handle;
    ULONG_PTR io_information = 0;
    NTSTATUS nt_status;
-   if (!FileSystemPolicy::OpenFileAction(result, *ipc->client_info, *name,
-                                         attributes, desired_access,
-                                         share_access, open_options, &handle,
-                                         &nt_status, &io_information)) {
+   if (!FileSystemPolicy::OpenFileAction(
+           result, *ipc->client_info, *name, attributes, desired_access,
+           share_access, open_options, &handle, &nt_status, &io_information)) {
      ipc->return_info.nt_status = STATUS_ACCESS_DENIED;
+     return true;
 diff --git a/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc b/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc
 --- a/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc
 @@ -70,19 +70,16 @@ NTSTATUS WINAPI TargetNtCreateFile(NtCre
-     uint32_t broker = FALSE;
      CountedParameterSet<OpenFile> params;
-     params[OpenFile::NAME] = ParamPickerMake(name);
+     const wchar_t* name_ptr = name.get();
+     params[OpenFile::NAME] = ParamPickerMake(name_ptr);
      params[OpenFile::ACCESS] = ParamPickerMake(desired_access_uint32);
      params[OpenFile::DISPOSITION] = ParamPickerMake(disposition_uint32);
      params[OpenFile::OPTIONS] = ParamPickerMake(options_uint32);
      params[OpenFile::BROKER] = ParamPickerMake(broker);
  
 -    if (!QueryBroker(IPC_NTCREATEFILE_TAG, params.GetBase()))
 -      break;
 -
      SharedMemIPCClient ipc(memory);
      CrossCallReturn answer = {0};
      // The following call must match in the parameters with
      // FilesystemDispatcher::ProcessNtCreateFile.
-     ResultCode code = CrossCall(ipc, IPC_NTCREATEFILE_TAG, name, attributes,
-                                 desired_access_uint32, file_attributes, sharing,
-                                 disposition, options_uint32, &answer);
-     if (SBOX_ALL_OK != code)
+     ResultCode code =
+         CrossCall(ipc, IPC_NTCREATEFILE_TAG, name.get(), attributes,
+                   desired_access_uint32, file_attributes, sharing, disposition,
+                   options_uint32, &answer);
 @@ -154,19 +151,16 @@ NTSTATUS WINAPI TargetNtOpenFile(NtOpenF
-     uint32_t broker = FALSE;
      CountedParameterSet<OpenFile> params;
-     params[OpenFile::NAME] = ParamPickerMake(name);
+     const wchar_t* name_ptr = name.get();
+     params[OpenFile::NAME] = ParamPickerMake(name_ptr);
      params[OpenFile::ACCESS] = ParamPickerMake(desired_access_uint32);
      params[OpenFile::DISPOSITION] = ParamPickerMake(disposition_uint32);
      params[OpenFile::OPTIONS] = ParamPickerMake(options_uint32);
      params[OpenFile::BROKER] = ParamPickerMake(broker);
  
 -    if (!QueryBroker(IPC_NTOPENFILE_TAG, params.GetBase()))
 -      break;
 -
      SharedMemIPCClient ipc(memory);
      CrossCallReturn answer = {0};
-     ResultCode code = CrossCall(ipc, IPC_NTOPENFILE_TAG, name, attributes,
-                                 desired_access_uint32, sharing, options_uint32,
-                                 &answer);
+     ResultCode code =
+         CrossCall(ipc, IPC_NTOPENFILE_TAG, name.get(), attributes,
+                   desired_access_uint32, sharing, options_uint32, &answer);
      if (SBOX_ALL_OK != code)
        break;
  
--- a/security/sandbox/chromium-shim/patches/after_update/patch_order.txt
+++ b/security/sandbox/chromium-shim/patches/after_update/patch_order.txt
@@ -1,8 +1,6 @@
 add_interception_logging.patch
 allow_rules_for_network_drive_and_non_file_devices.patch
 add_WOW64_flags_to_allowed_registry_read_flags.patch
 consult_PermissionsService_for_file_access.patch
 allow_flash_temporary_files.patch
-use_STARTF_FORCEOFFFEEDBACK_flag.patch
-remove_dynamic_GetUserDefaultLocaleName_call.patch
 arm64_set_LoaderThreads.patch
deleted file mode 100644
--- a/security/sandbox/chromium-shim/patches/after_update/remove_dynamic_GetUserDefaultLocaleName_call.patch
+++ /dev/null
@@ -1,66 +0,0 @@
-# HG changeset patch
-# User Bob Owen <bobowencode@gmail.com>
-# Date 1524480221 -3600
-#      Mon Apr 23 11:43:41 2018 +0100
-# Node ID c881904b6139ba0c6f5072f7577a94812021913a
-# Parent  e96685584bf7d3c1d7a4c1861716da89fd650c51
-Bug 1444699: Remove dynamic load and call for GetUserDefaultLocaleName. r=handyman
-
-This was only required because it is not available on Windows XP, which is no
-longer supported. Patch already landed upstream in chromium.
-
-diff --git a/security/sandbox/chromium/sandbox/win/src/target_services.cc b/security/sandbox/chromium/sandbox/win/src/target_services.cc
---- a/security/sandbox/chromium/sandbox/win/src/target_services.cc
-+++ b/security/sandbox/chromium/sandbox/win/src/target_services.cc
-@@ -75,50 +75,30 @@ bool CloseOpenHandles(bool* is_csrss_con
-       }
-     }
-     if (!handle_closer.CloseHandles())
-       return false;
-   }
-   return true;
- }
- 
--// GetUserDefaultLocaleName is not available on WIN XP.  So we'll
--// load it on-the-fly.
--const wchar_t kKernel32DllName[] = L"kernel32.dll";
--typedef decltype(GetUserDefaultLocaleName)* GetUserDefaultLocaleNameFunction;
--
- // Warm up language subsystems before the sandbox is turned on.
- // Tested on Win8.1 x64:
- // This needs to happen after RevertToSelf() is called, because (at least) in
- // the case of GetUserDefaultLCID() it checks the TEB to see if the process is
- // impersonating (TEB!IsImpersonating). If it is, the cached locale information
- // is not used, nor is it set. Therefore, calls after RevertToSelf() will not
- // have warmed-up values to use.
- bool WarmupWindowsLocales() {
-   // NOTE(liamjm): When last checked (Win 8.1 x64) it wasn't necessary to
-   // warmup all of these functions, but let's not assume that.
-   ::GetUserDefaultLangID();
-   ::GetUserDefaultLCID();
--  static GetUserDefaultLocaleNameFunction GetUserDefaultLocaleName_func =
--      NULL;
--  if (!GetUserDefaultLocaleName_func) {
--    HMODULE kernel32_dll = ::GetModuleHandle(kKernel32DllName);
--    if (!kernel32_dll) {
--      return false;
--    }
--    GetUserDefaultLocaleName_func =
--        reinterpret_cast<GetUserDefaultLocaleNameFunction>(
--            GetProcAddress(kernel32_dll, "GetUserDefaultLocaleName"));
--    if (!GetUserDefaultLocaleName_func) {
--      return false;
--    }
--  }
-   wchar_t localeName[LOCALE_NAME_MAX_LENGTH] = {0};
--  return (0 != GetUserDefaultLocaleName_func(
--                    localeName, LOCALE_NAME_MAX_LENGTH * sizeof(wchar_t)));
-+  return (0 != ::GetUserDefaultLocaleName(localeName, LOCALE_NAME_MAX_LENGTH));
- }
- 
- // Used as storage for g_target_services, because other allocation facilities
- // are not available early. We can't use a regular function static because on
- // VS2015, because the CRT tries to acquire a lock to guard initialization, but
- // this code runs before the CRT is initialized.
- char g_target_services_memory[sizeof(TargetServicesBase)];
- TargetServicesBase* g_target_services = nullptr;
deleted file mode 100644
--- a/security/sandbox/chromium-shim/patches/after_update/use_STARTF_FORCEOFFFEEDBACK_flag.patch
+++ /dev/null
@@ -1,32 +0,0 @@
-# HG changeset patch
-# User Bob Owen <bobowencode@gmail.com>
-# Date 1512580728 0
-#      Wed Dec 06 17:18:48 2017 +0000
-# Node ID e56684aa96bd963d4b94ed69b99a0359fa0479ae
-# Parent  785572419acc82b2cbdcd2e24ca59fdbf5d7255f
-Use STARTF_FORCEOFFFEEDBACK flag when starting Windows child processes to prevent app starting cursor. r=jimm
-
-diff --git a/security/sandbox/chromium/sandbox/win/src/broker_services.cc b/security/sandbox/chromium/sandbox/win/src/broker_services.cc
---- a/security/sandbox/chromium/sandbox/win/src/broker_services.cc
-+++ b/security/sandbox/chromium/sandbox/win/src/broker_services.cc
-@@ -346,16 +346,20 @@ ResultCode BrokerServicesBase::SpawnTarg
- 
-   base::win::ScopedHandle job;
-   result = policy_base->MakeJobObject(&job);
-   if (SBOX_ALL_OK != result)
-     return result;
- 
-   // Initialize the startup information from the policy.
-   base::win::StartupInformation startup_info;
-+
-+  // We don't want any child processes causing the IDC_APPSTARTING cursor.
-+  startup_info.startup_info()->dwFlags |= STARTF_FORCEOFFFEEDBACK;
-+
-   // The liftime of |mitigations|, |inherit_handle_list| and
-   // |child_process_creation| have to be at least as long as
-   // |startup_info| because |UpdateProcThreadAttribute| requires that
-   // its |lpValue| parameter persist until |DeleteProcThreadAttributeList| is
-   // called; StartupInformation's destructor makes such a call.
-   DWORD64 mitigations;
-   std::vector<HANDLE> inherited_handle_list;
-   DWORD child_process_creation = PROCESS_CREATION_CHILD_PROCESS_RESTRICTED;
--- a/security/sandbox/chromium-shim/patches/with_update/aarch64_control_flow_guard.patch
+++ b/security/sandbox/chromium-shim/patches/with_update/aarch64_control_flow_guard.patch
@@ -1,40 +1,61 @@
+# HG changeset patch
+# User David Major <dmajor@mozilla.com>
+# Date 1560264749 -3600
+#      Tue Jun 11 15:52:29 2019 +0100
+# Node ID 6acdba6bd34e773d5e2d6a8461e3679a33340f77
+# Parent  a0adb2e7f668ed430948ae1ffaa42ec011ffde50
 Bug 1523526: Don't allow CFG on old releases of Windows for arm64
 
 There's a bug in ole32.dll on arm64 versions of Windows prior to 1809, that crashes our content processes if we enable CFG. We've reported the issue, but even if it gets fixed, we can't assume users will have the update.
 
 This patch uses process mitigation policy flags to disable CFG on arm64 before 1809. Based on testing, we only need to do this in the sandbox for child processes, and it's not strictly necessary for the launcher stub to set the flag on the main process. But I've included that anyway as a guard against some yet-undiscovered scenario that might hit the issue and make the browser unusable.
 
 The effects of this patch won't be visible until we actually enable CFG in a subsequent landing.
 
 Differential Revision: https://phabricator.services.mozilla.com/D29474
 
 diff --git a/security/sandbox/chromium/sandbox/win/src/process_mitigations.cc b/security/sandbox/chromium/sandbox/win/src/process_mitigations.cc
 --- a/security/sandbox/chromium/sandbox/win/src/process_mitigations.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/process_mitigations.cc
-@@ -354,6 +354,11 @@ void ConvertProcessMitigationsToPolicy(M
-         PROCESS_CREATION_MITIGATION_POLICY_PROHIBIT_DYNAMIC_CODE_ALWAYS_ON;
+@@ -400,16 +400,21 @@ void ConvertProcessMitigationsToPolicy(M
+ 
+   // Mitigations >= Win8.1:
+   //----------------------------------------------------------------------------
+   if (version >= base::win::VERSION_WIN8_1) {
+     if (flags & MITIGATION_DYNAMIC_CODE_DISABLE) {
+       *policy_value_1 |=
+           PROCESS_CREATION_MITIGATION_POLICY_PROHIBIT_DYNAMIC_CODE_ALWAYS_ON;
+     }
++
++    if (flags & MITIGATION_CONTROL_FLOW_GUARD_DISABLE) {
++      *policy_value_1 |=
++          PROCESS_CREATION_MITIGATION_POLICY_CONTROL_FLOW_GUARD_ALWAYS_OFF;
++    }
    }
  
-+  if (flags & MITIGATION_CONTROL_FLOW_GUARD_DISABLE) {
-+    *policy_flags |=
-+        PROCESS_CREATION_MITIGATION_POLICY_CONTROL_FLOW_GUARD_ALWAYS_OFF;
-+  }
-+
-   if (version < base::win::VERSION_WIN10)
-     return;
- 
+   // Mitigations >= Win10:
+   //----------------------------------------------------------------------------
+   if (version >= base::win::VERSION_WIN10) {
+     if (flags & MITIGATION_NONSYSTEM_FONT_DISABLE) {
+       *policy_value_1 |=
+           PROCESS_CREATION_MITIGATION_POLICY_FONT_DISABLE_ALWAYS_ON;
 diff --git a/security/sandbox/chromium/sandbox/win/src/security_level.h b/security/sandbox/chromium/sandbox/win/src/security_level.h
 --- a/security/sandbox/chromium/sandbox/win/src/security_level.h
 +++ b/security/sandbox/chromium/sandbox/win/src/security_level.h
-@@ -255,6 +255,15 @@ const MitigationFlags MITIGATION_IMAGE_L
- // PROCESS_CREATION_MITIGATION_POLICY_IMAGE_LOAD_PREFER_SYSTEM32_ALWAYS_ON.
+@@ -273,11 +273,20 @@ const MitigationFlags MITIGATION_IMAGE_L
  const MitigationFlags MITIGATION_IMAGE_LOAD_PREFER_SYS32 = 0x00100000;
  
+ // Prevents hyperthreads from interfering with indirect branch predictions.
+ // (SPECTRE Variant 2 mitigation.)  Corresponds to
+ // PROCESS_CREATION_MITIGATION_POLICY2_RESTRICT_INDIRECT_BRANCH_PREDICTION_ALWAYS_ON.
+ const MitigationFlags MITIGATION_RESTRICT_INDIRECT_BRANCH_PREDICTION =
+     0x00200000;
+ 
 +// Begin Mozilla-added flags.
 +// Working down from the high bit to avoid conflict with new upstream flags.
 +
 +// Disable Control Flow Guard. This may seem more like an anti-mitigation, but
 +// this flag allows code to make targeted changes to CFG to avoid bugs, while
 +// leaving it enabled in the common case. Corresponds to
 +// PROCESS_CREATION_MITIGATION_POLICY_CONTROL_FLOW_GUARD_ALWAYS_ON.
 +const MitigationFlags MITIGATION_CONTROL_FLOW_GUARD_DISABLE = 0x80000000;
deleted file mode 100644
--- a/security/sandbox/chromium-shim/patches/with_update/add_aarch64_windows_support.patch
+++ /dev/null
@@ -1,349 +0,0 @@
-# HG changeset patch
-# User Bob Owen <bobowencode@gmail.com>
-# Date 1544459474 0
-#      Mon Dec 10 16:31:14 2018 +0000
-# Node ID 9f96df3ffc7d338b227e3bc94c2f615bd8bdea38
-# Parent  3386ff76878d83496bb822d09115c77472808b53
-Bug 1481518 part 1: Add aarch64 Windows support to the chromium sandbox code.
-
-This patch includes the changes that Microsoft landed for the sandbox along
-with other changes to the supporting base files that they depend upon.
-
-diff --git a/security/sandbox/chromium/base/atomicops.h b/security/sandbox/chromium/base/atomicops.h
---- a/security/sandbox/chromium/base/atomicops.h
-+++ b/security/sandbox/chromium/base/atomicops.h
-@@ -139,17 +139,17 @@ void Release_Store(volatile Atomic64* pt
- Atomic64 NoBarrier_Load(volatile const Atomic64* ptr);
- Atomic64 Acquire_Load(volatile const Atomic64* ptr);
- Atomic64 Release_Load(volatile const Atomic64* ptr);
- #endif  // ARCH_CPU_64_BITS
- 
- }  // namespace subtle
- }  // namespace base
- 
--#if defined(OS_WIN)
-+#if defined(OS_WIN) && defined(ARCH_CPU_X86_FAMILY)
- // TODO(jfb): The MSVC header includes windows.h, which other files end up
- //            relying on. Fix this as part of crbug.com/559247.
- #  include "base/atomicops_internals_x86_msvc.h"
- #else
- #  include "base/atomicops_internals_portable.h"
- #endif
- 
- // On some platforms we need additional declarations to make
-diff --git a/security/sandbox/chromium/base/bind_internal.h b/security/sandbox/chromium/base/bind_internal.h
---- a/security/sandbox/chromium/base/bind_internal.h
-+++ b/security/sandbox/chromium/base/bind_internal.h
-@@ -147,17 +147,17 @@ struct FunctorTraits<R (*)(Args...)> {
-   static constexpr bool is_nullable = true;
- 
-   template <typename... RunArgs>
-   static R Invoke(R (*function)(Args...), RunArgs&&... args) {
-     return function(std::forward<RunArgs>(args)...);
-   }
- };
- 
--#if defined(OS_WIN) && !defined(ARCH_CPU_X86_64)
-+#if defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
- 
- // 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;
- 
-@@ -175,17 +175,17 @@ struct FunctorTraits<R(__fastcall*)(Args
-   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)
-+#endif  // defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
- 
- // 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;
- 
-diff --git a/security/sandbox/chromium/base/time/time_win.cc b/security/sandbox/chromium/base/time/time_win.cc
---- a/security/sandbox/chromium/base/time/time_win.cc
-+++ b/security/sandbox/chromium/base/time/time_win.cc
-@@ -643,16 +643,22 @@ bool ThreadTicks::IsSupportedWin() {
- }
- 
- // static
- void ThreadTicks::WaitUntilInitializedWin() {
-   while (TSCTicksPerSecond() == 0)
-     ::Sleep(10);
- }
- 
-+#if defined(_M_ARM64)
-+#define ReadCycleCounter() _ReadStatusReg(ARM64_PMCCNTR_EL0)
-+#else
-+#define ReadCycleCounter() __rdtsc()
-+#endif
-+
- double ThreadTicks::TSCTicksPerSecond() {
-   DCHECK(IsSupported());
- 
-   // The value returned by QueryPerformanceFrequency() cannot be used as the TSC
-   // frequency, because there is no guarantee that the TSC frequency is equal to
-   // the performance counter frequency.
- 
-   // The TSC frequency is cached in a static variable because it takes some time
-@@ -663,22 +669,22 @@ double ThreadTicks::TSCTicksPerSecond() 
- 
-   // Increase the thread priority to reduces the chances of having a context
-   // switch during a reading of the TSC and the performance counter.
-   int previous_priority = ::GetThreadPriority(::GetCurrentThread());
-   ::SetThreadPriority(::GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
- 
-   // The first time that this function is called, make an initial reading of the
-   // TSC and the performance counter.
--  static const uint64_t tsc_initial = __rdtsc();
-+  static const uint64_t tsc_initial = ReadCycleCounter();
-   static const uint64_t perf_counter_initial = QPCNowRaw();
- 
-   // Make a another reading of the TSC and the performance counter every time
-   // that this function is called.
--  uint64_t tsc_now = __rdtsc();
-+  uint64_t tsc_now = ReadCycleCounter();
-   uint64_t perf_counter_now = QPCNowRaw();
- 
-   // Reset the thread priority.
-   ::SetThreadPriority(::GetCurrentThread(), previous_priority);
- 
-   // Make sure that at least 50 ms elapsed between the 2 readings. The first
-   // time that this function is called, we don't expect this to be the case.
-   // Note: The longer the elapsed time between the 2 readings is, the more
-@@ -702,16 +708,18 @@ double ThreadTicks::TSCTicksPerSecond() 
-   // Compute the frequency of the TSC.
-   DCHECK_GE(tsc_now, tsc_initial);
-   uint64_t tsc_ticks = tsc_now - tsc_initial;
-   tsc_ticks_per_second = tsc_ticks / elapsed_time_seconds;
- 
-   return tsc_ticks_per_second;
- }
- 
-+#undef ReadCycleCounter
-+
- // static
- TimeTicks TimeTicks::FromQPCValue(LONGLONG qpc_value) {
-   return TimeTicks() + QPCValueToTimeDelta(qpc_value);
- }
- 
- // TimeDelta ------------------------------------------------------------------
- 
- // static
-diff --git a/security/sandbox/chromium/build/build_config.h b/security/sandbox/chromium/build/build_config.h
---- a/security/sandbox/chromium/build/build_config.h
-+++ b/security/sandbox/chromium/build/build_config.h
-@@ -137,17 +137,17 @@
- #define ARCH_CPU_PPC64 1
- #define ARCH_CPU_64_BITS 1
- #define ARCH_CPU_LITTLE_ENDIAN 1
- #elif defined(__ARMEL__)
- #define ARCH_CPU_ARM_FAMILY 1
- #define ARCH_CPU_ARMEL 1
- #define ARCH_CPU_32_BITS 1
- #define ARCH_CPU_LITTLE_ENDIAN 1
--#elif defined(__aarch64__)
-+#elif defined(__aarch64__) || defined(_M_ARM64)
- #define ARCH_CPU_ARM_FAMILY 1
- #define ARCH_CPU_ARM64 1
- #define ARCH_CPU_64_BITS 1
- #define ARCH_CPU_LITTLE_ENDIAN 1
- #elif defined(__pnacl__)
- #define ARCH_CPU_32_BITS 1
- #define ARCH_CPU_LITTLE_ENDIAN 1
- #elif defined(__MIPSEL__)
-diff --git a/security/sandbox/chromium/sandbox/win/src/resolver_64.cc b/security/sandbox/chromium/sandbox/win/src/resolver_64.cc
---- a/security/sandbox/chromium/sandbox/win/src/resolver_64.cc
-+++ b/security/sandbox/chromium/sandbox/win/src/resolver_64.cc
-@@ -9,16 +9,18 @@
- // For placement new. This file must not depend on the CRT at runtime, but
- // placement operator new is inline.
- #include <new>
- 
- #include "sandbox/win/src/sandbox_nt_util.h"
- 
- namespace {
- 
-+#if defined(_M_X64)
-+
- const USHORT kMovRax = 0xB848;
- const USHORT kJmpRax = 0xe0ff;
- 
- #pragma pack(push, 1)
- struct InternalThunk {
-   // This struct contains roughly the following code:
-   // 01 48b8f0debc9a78563412  mov   rax,123456789ABCDEF0h
-   // ff e0                    jmp   rax
-@@ -31,16 +33,42 @@ struct InternalThunk {
-     interceptor_function = 0;
-   };
-   USHORT mov_rax;       // = 48 B8
-   ULONG_PTR interceptor_function;
-   USHORT jmp_rax;  // = ff e0
- };
- #pragma pack(pop)
- 
-+#elif defined(_M_ARM64)
-+
-+const ULONG kLdrX16Pc4 = 0x58000050;
-+const ULONG kBrX16 = 0xD61F0200;
-+
-+#pragma pack(push, 4)
-+struct InternalThunk {
-+  // This struct contains roughly the following code:
-+  // 00 58000050 ldr x16, pc+4
-+  // 04 D61F0200 br x16
-+  // 08 123456789ABCDEF0H
-+
-+  InternalThunk() {
-+    ldr_x16_pc4 = kLdrX16Pc4;
-+    br_x16 = kBrX16;
-+    interceptor_function = 0;
-+  };
-+  ULONG ldr_x16_pc4;
-+  ULONG br_x16;
-+  ULONG_PTR interceptor_function;
-+};
-+#pragma pack(pop)
-+#else
-+#error "Unsupported Windows 64-bit Arch"
-+#endif
-+
- } // namespace.
- 
- namespace sandbox {
- 
- size_t ResolverThunk::GetInternalThunkSize() const {
-   return sizeof(InternalThunk);
- }
- 
-diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.h b/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.h
---- a/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.h
-+++ b/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.h
-@@ -50,17 +50,17 @@ void __cdecl operator delete(void* memor
- #endif
- 
- #define CHECK_NT(condition) { (condition) ? (void)0 : __debugbreak(); }
- 
- #define NOTREACHED_NT() DCHECK_NT(false)
- 
- namespace sandbox {
- 
--#if defined(_M_X64)
-+#if defined(_M_X64) || defined(_M_ARM64)
- #pragma intrinsic(_InterlockedCompareExchange)
- #pragma intrinsic(_InterlockedCompareExchangePointer)
- 
- #elif defined(_M_IX86)
- extern "C" long _InterlockedCompareExchange(long volatile* destination,
-                                             long exchange, long comperand);
- 
- #pragma intrinsic(_InterlockedCompareExchange)
-diff --git a/security/sandbox/chromium/sandbox/win/src/service_resolver_64.cc b/security/sandbox/chromium/sandbox/win/src/service_resolver_64.cc
---- a/security/sandbox/chromium/sandbox/win/src/service_resolver_64.cc
-+++ b/security/sandbox/chromium/sandbox/win/src/service_resolver_64.cc
-@@ -7,16 +7,17 @@
- #include <stddef.h>
- 
- #include <memory>
- 
- #include "sandbox/win/src/sandbox_nt_util.h"
- #include "sandbox/win/src/win_utils.h"
- 
- namespace {
-+#if defined(_M_X64)
- #pragma pack(push, 1)
- 
- const ULONG kMmovR10EcxMovEax = 0xB8D18B4C;
- const USHORT kSyscall = 0x050F;
- const BYTE kRetNp = 0xC3;
- const ULONG64 kMov1 = 0x54894808244C8948;
- const ULONG64 kMov2 = 0x4C182444894C1024;
- const ULONG kMov3 = 0x20244C89;
-@@ -125,16 +126,54 @@ bool IsServiceWithInt2E(const void* sour
-       reinterpret_cast<const ServiceEntryWithInt2E*>(source);
- 
-   return (kMmovR10EcxMovEax == service->mov_r10_rcx_mov_eax &&
-           kTestByte == service->test_byte && kPtr == service->ptr &&
-           kJne == service->jne_over_syscall && kSyscall == service->syscall &&
-           kRet == service->ret && kRet == service->ret2);
- }
- 
-+bool IsAnyService(const void* source) {
-+  return IsService(source) || IsServiceW8(source) || IsServiceWithInt2E(source);
-+}
-+
-+#elif defined(_M_ARM64)
-+#pragma pack(push, 4)
-+
-+const ULONG kSvc = 0xD4000001;
-+const ULONG kRetNp = 0xD65F03C0;
-+const ULONG kServiceIdMask = 0x001FFFE0;
-+
-+struct ServiceEntry {
-+  ULONG svc;
-+  ULONG ret;
-+  ULONG64 unused;
-+};
-+
-+struct ServiceFullThunk {
-+  ServiceEntry original;
-+};
-+
-+#pragma pack(pop)
-+
-+bool IsService(const void* source) {
-+  const ServiceEntry* service = reinterpret_cast<const ServiceEntry*>(source);
-+
-+  return (kSvc == (service->svc & ~kServiceIdMask) && kRetNp == service->ret &&
-+          0 == service->unused);
-+}
-+
-+bool IsAnyService(const void* source) {
-+  return IsService(source);
-+}
-+
-+#else
-+#error "Unsupported Windows 64-bit Arch"
-+#endif
-+
- };  // namespace
- 
- namespace sandbox {
- 
- NTSTATUS ServiceResolverThunk::Setup(const void* target_module,
-                                      const void* interceptor_module,
-                                      const char* target_name,
-                                      const char* interceptor_name,
-@@ -197,18 +236,17 @@ bool ServiceResolverThunk::IsFunctionASe
-   SIZE_T read;
-   if (!::ReadProcessMemory(process_, target_, &function_code,
-                            sizeof(function_code), &read))
-     return false;
- 
-   if (sizeof(function_code) != read)
-     return false;
- 
--  if (!IsService(&function_code) && !IsServiceW8(&function_code) &&
--      !IsServiceWithInt2E(&function_code))
-+  if (!IsAnyService(&function_code))
-     return false;
- 
-   // Save the verified code.
-   memcpy(local_thunk, &function_code, sizeof(function_code));
- 
-   return true;
- }
- 
--- a/security/sandbox/chromium-shim/patches/with_update/add_option_to_not_use_restricting_sids.patch
+++ b/security/sandbox/chromium-shim/patches/with_update/add_option_to_not_use_restricting_sids.patch
@@ -7,35 +7,35 @@
 Bug 1366701 - Add option to Windows chromium sandbox policy to not use restricting SIDs. r=jimm
 
 This originally landed in changeset:
 https://hg.mozilla.org/mozilla-central/rev/14374cd9497a
 
 diff --git a/security/sandbox/chromium/sandbox/win/src/restricted_token_utils.cc b/security/sandbox/chromium/sandbox/win/src/restricted_token_utils.cc
 --- a/security/sandbox/chromium/sandbox/win/src/restricted_token_utils.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/restricted_token_utils.cc
-@@ -17,16 +17,17 @@
- #include "sandbox/win/src/sid.h"
+@@ -51,16 +51,17 @@
  
- namespace sandbox {
+ }  // namespace
  
- DWORD CreateRestrictedToken(TokenLevel security_level,
+ DWORD CreateRestrictedToken(HANDLE effective_token,
+                             TokenLevel security_level,
                              IntegrityLevel integrity_level,
                              TokenType token_type,
                              bool lockdown_default_dacl,
 +                            bool use_restricting_sids,
                              base::win::ScopedHandle* token) {
    RestrictedToken restricted_token;
-   restricted_token.Init(NULL);  // Initialized with the current process token
+   restricted_token.Init(effective_token);
    if (lockdown_default_dacl)
      restricted_token.SetLockdownDefaultDacl();
  
    std::vector<base::string16> privilege_exceptions;
    std::vector<Sid> sid_exceptions;
-@@ -39,19 +40,22 @@ DWORD CreateRestrictedToken(TokenLevel s
+@@ -68,19 +69,22 @@ DWORD CreateRestrictedToken(TokenLevel s
        deny_sids = false;
        remove_privileges = false;
        break;
      }
      case USER_RESTRICTED_SAME_ACCESS: {
        deny_sids = false;
        remove_privileges = false;
  
@@ -51,17 +51,17 @@ diff --git a/security/sandbox/chromium/s
  
        break;
      }
      case USER_NON_ADMIN: {
        sid_exceptions.push_back(WinBuiltinUsersSid);
        sid_exceptions.push_back(WinWorldSid);
        sid_exceptions.push_back(WinInteractiveSid);
        sid_exceptions.push_back(WinAuthenticatedUserSid);
-@@ -59,49 +63,57 @@ DWORD CreateRestrictedToken(TokenLevel s
+@@ -93,49 +97,57 @@ DWORD CreateRestrictedToken(TokenLevel s
        break;
      }
      case USER_INTERACTIVE: {
        sid_exceptions.push_back(WinBuiltinUsersSid);
        sid_exceptions.push_back(WinWorldSid);
        sid_exceptions.push_back(WinInteractiveSid);
        sid_exceptions.push_back(WinAuthenticatedUserSid);
        privilege_exceptions.push_back(SE_CHANGE_NOTIFY_NAME);
@@ -119,43 +119,43 @@ diff --git a/security/sandbox/chromium/s
      case USER_LOCKDOWN: {
        restricted_token.AddUserSidForDenyOnly();
 -      restricted_token.AddRestrictingSid(WinNullSid);
 +      if (use_restricting_sids) {
 +        restricted_token.AddRestrictingSid(WinNullSid);
 +      }
        break;
      }
-     default: {
-       return ERROR_BAD_ARGUMENTS;
-     }
+     default: { return ERROR_BAD_ARGUMENTS; }
    }
  
    DWORD err_code = ERROR_SUCCESS;
+   if (deny_sids) {
+     err_code = restricted_token.AddAllSidsForDenyOnly(&sid_exceptions);
 diff --git a/security/sandbox/chromium/sandbox/win/src/restricted_token_utils.h b/security/sandbox/chromium/sandbox/win/src/restricted_token_utils.h
 --- a/security/sandbox/chromium/sandbox/win/src/restricted_token_utils.h
 +++ b/security/sandbox/chromium/sandbox/win/src/restricted_token_utils.h
-@@ -35,16 +35,17 @@ enum TokenType {
- // running under the token.
+@@ -33,16 +33,17 @@ enum TokenType {
  // If the function succeeds, the return value is ERROR_SUCCESS. If the
  // function fails, the return value is the win32 error code corresponding to
  // the error.
- DWORD CreateRestrictedToken(TokenLevel security_level,
+ DWORD CreateRestrictedToken(HANDLE effective_token,
+                             TokenLevel security_level,
                              IntegrityLevel integrity_level,
                              TokenType token_type,
                              bool lockdown_default_dacl,
 +                            bool use_restricting_sids,
                              base::win::ScopedHandle* token);
  
  // Sets the integrity label on a object handle.
- DWORD SetObjectIntegrityLabel(HANDLE handle, SE_OBJECT_TYPE type,
+ DWORD SetObjectIntegrityLabel(HANDLE handle,
+                               SE_OBJECT_TYPE type,
                                const wchar_t* ace_access,
                                const wchar_t* integrity_level_sid);
  
- // Sets the integrity level on a token. This is only valid on Vista. It returns
 diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_policy.h b/security/sandbox/chromium/sandbox/win/src/sandbox_policy.h
 --- a/security/sandbox/chromium/sandbox/win/src/sandbox_policy.h
 +++ b/security/sandbox/chromium/sandbox/win/src/sandbox_policy.h
 @@ -95,16 +95,21 @@ class TargetPolicy {
    virtual ResultCode SetTokenLevel(TokenLevel initial, TokenLevel lockdown) = 0;
  
    // Returns the initial token level.
    virtual TokenLevel GetInitialTokenLevel() const = 0;
@@ -174,17 +174,17 @@ diff --git a/security/sandbox/chromium/s
    // can not be specified in the token security profile.
    // job_level: the security level for the job. See the explanation of each
    //   level in the JobLevel definition.
    // ui_exceptions: specify what specific rights that are disabled in the
    //   chosen job_level that need to be granted. Use this parameter to avoid
 diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.cc b/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.cc
 --- a/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.cc
-@@ -184,16 +184,20 @@ ResultCode PolicyBase::SetTokenLevel(Tok
+@@ -149,16 +149,20 @@ ResultCode PolicyBase::SetTokenLevel(Tok
  TokenLevel PolicyBase::GetInitialTokenLevel() const {
    return initial_level_;
  }
  
  TokenLevel PolicyBase::GetLockdownTokenLevel() const {
    return lockdown_level_;
  }
  
@@ -195,48 +195,48 @@ diff --git a/security/sandbox/chromium/s
  ResultCode PolicyBase::SetJobLevel(JobLevel job_level, uint32_t ui_exceptions) {
    if (memory_limit_ && job_level == JOB_NONE) {
      return SBOX_ERROR_BAD_PARAMS;
    }
    job_level_ = job_level;
    ui_exceptions_ = ui_exceptions;
    return SBOX_ALL_OK;
  }
-@@ -438,17 +442,18 @@ ResultCode PolicyBase::MakeJobObject(bas
+@@ -402,17 +406,18 @@ ResultCode PolicyBase::MakeJobObject(bas
  
  ResultCode PolicyBase::MakeTokens(base::win::ScopedHandle* initial,
                                    base::win::ScopedHandle* lockdown,
                                    base::win::ScopedHandle* lowbox) {
    // Create the 'naked' token. This will be the permanent token associated
    // with the process and therefore with any thread that is not impersonating.
    DWORD result =
-       CreateRestrictedToken(lockdown_level_, integrity_level_, PRIMARY,
--                            lockdown_default_dacl_, lockdown);
-+                            lockdown_default_dacl_, use_restricting_sids_,
-+                            lockdown);
+       CreateRestrictedToken(effective_token_, lockdown_level_, integrity_level_,
+-                            PRIMARY, lockdown_default_dacl_, lockdown);
++                            PRIMARY, lockdown_default_dacl_,
++                            use_restricting_sids_, lockdown);
    if (ERROR_SUCCESS != result)
      return SBOX_ERROR_GENERIC;
  
    // If we're launching on the alternate desktop we need to make sure the
    // integrity label on the object is no higher than the sandboxed process's
    // integrity level. So, we lower the label on the desktop process if it's
    // not already low enough for our process.
    if (use_alternate_desktop_ && integrity_level_ != INTEGRITY_LEVEL_LAST) {
-@@ -509,17 +514,18 @@ ResultCode PolicyBase::MakeTokens(base::
-     lowbox->Set(token_lowbox);
+@@ -466,17 +471,18 @@ ResultCode PolicyBase::MakeTokens(base::
+     }
    }
  
    // Create the 'better' token. We use this token as the one that the main
    // thread uses when booting up the process. It should contain most of
    // what we need (before reaching main( ))
    result =
-       CreateRestrictedToken(initial_level_, integrity_level_, IMPERSONATION,
--                            lockdown_default_dacl_, initial);
-+                            lockdown_default_dacl_, use_restricting_sids_,
-+                            initial);
+       CreateRestrictedToken(effective_token_, initial_level_, integrity_level_,
+-                            IMPERSONATION, lockdown_default_dacl_, initial);
++                            IMPERSONATION, lockdown_default_dacl_,
++                            use_restricting_sids_, initial);
    if (ERROR_SUCCESS != result)
      return SBOX_ERROR_GENERIC;
  
    return SBOX_ALL_OK;
  }
  
  PSID PolicyBase::GetLowBoxSid() const {
    return lowbox_sid_;
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/patches/with_update/add_return_in_QueryCancellationTraitsForNonCancellables_to_satisfy_build.patch
@@ -0,0 +1,29 @@
+# HG changeset patch
+# User Bob Owen <bobowencode@gmail.com>
+# Date 1560260462 -3600
+#      Tue Jun 11 14:41:02 2019 +0100
+# Node ID cb6cbf2c60077e833f472c82c1f437a794ac5266
+# Parent  71ac3df6aadbce233034b169646b66160c5944dc
+Bug 1552160: Add return after NOTREACHED() in QueryCancellationTraitsForNonCancellables to prevent build error. r=jld
+
+diff --git a/security/sandbox/chromium/base/callback_internal.cc b/security/sandbox/chromium/base/callback_internal.cc
+--- a/security/sandbox/chromium/base/callback_internal.cc
++++ b/security/sandbox/chromium/base/callback_internal.cc
+@@ -16,16 +16,17 @@ bool QueryCancellationTraitsForNonCancel
+     BindStateBase::CancellationQueryMode mode) {
+   switch (mode) {
+     case BindStateBase::IS_CANCELLED:
+       return false;
+     case BindStateBase::MAYBE_VALID:
+       return true;
+   }
+   NOTREACHED();
++  return false;
+ }
+ 
+ }  // namespace
+ 
+ void BindStateBaseRefCountTraits::Destruct(const BindStateBase* bind_state) {
+   bind_state->destructor_(bind_state);
+ }
+ 
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/patches/with_update/allow_env_changes.patch
@@ -0,0 +1,199 @@
+# HG changeset patch
+# User Gian-Carlo Pascutto <gcp@mozilla.com>
+# Date 1515402436 -3600
+#      Mon Jan 08 10:07:16 2018 +0100
+# Node ID 205e7ae2a6bc5ed1cdd1a982a12d99f52ce33258
+# Parent  a89071894b4904a0130139a03147d4a6cb5c3bfc
+Bug 1297740.
+
+diff --git a/security/sandbox/chromium/sandbox/win/src/broker_services.cc b/security/sandbox/chromium/sandbox/win/src/broker_services.cc
+--- a/security/sandbox/chromium/sandbox/win/src/broker_services.cc
++++ b/security/sandbox/chromium/sandbox/win/src/broker_services.cc
+@@ -301,16 +301,17 @@ DWORD WINAPI BrokerServicesBase::TargetE
+   NOTREACHED();
+   return 0;
+ }
+ 
+ // SpawnTarget does all the interesting sandbox setup and creates the target
+ // process inside the sandbox.
+ ResultCode BrokerServicesBase::SpawnTarget(const wchar_t* exe_path,
+                                            const wchar_t* command_line,
++                                           base::EnvironmentMap& env_map,
+                                            scoped_refptr<TargetPolicy> policy,
+                                            ResultCode* last_warning,
+                                            DWORD* last_error,
+                                            PROCESS_INFORMATION* target_info) {
+   if (!exe_path)
+     return SBOX_ERROR_BAD_PARAMS;
+ 
+   if (!policy)
+@@ -486,17 +487,17 @@ ResultCode BrokerServicesBase::SpawnTarg
+   // Brokerservices does not own the target object. It is owned by the Policy.
+   base::win::ScopedProcessInformation process_info;
+   TargetProcess* target = new TargetProcess(
+       std::move(initial_token), std::move(lockdown_token), job.Get(),
+       thread_pool_.get(),
+       profile ? profile->GetImpersonationCapabilities() : std::vector<Sid>());
+ 
+   result = target->Create(exe_path, command_line, inherit_handles, startup_info,
+-                          &process_info, last_error);
++                          &process_info, env_map, last_error);
+ 
+   if (result != SBOX_ALL_OK) {
+     SpawnCleanup(target);
+     return result;
+   }
+ 
+   if (lowbox_token.IsValid()) {
+     *last_warning = target->AssignLowBoxToken(lowbox_token);
+diff --git a/security/sandbox/chromium/sandbox/win/src/broker_services.h b/security/sandbox/chromium/sandbox/win/src/broker_services.h
+--- a/security/sandbox/chromium/sandbox/win/src/broker_services.h
++++ b/security/sandbox/chromium/sandbox/win/src/broker_services.h
+@@ -7,16 +7,17 @@
+ 
+ #include <list>
+ #include <map>
+ #include <memory>
+ #include <set>
+ #include <utility>
+ 
+ #include "base/compiler_specific.h"
++#include "base/environment.h"
+ #include "base/macros.h"
+ #include "base/memory/scoped_refptr.h"
+ #include "base/win/scoped_handle.h"
+ #include "sandbox/win/src/crosscall_server.h"
+ #include "sandbox/win/src/job.h"
+ #include "sandbox/win/src/sandbox.h"
+ #include "sandbox/win/src/sharedmem_ipc_server.h"
+ #include "sandbox/win/src/win2k_threadpool.h"
+@@ -45,16 +46,17 @@ class BrokerServicesBase final : public 
+ 
+   ~BrokerServicesBase();
+ 
+   // BrokerServices interface.
+   ResultCode Init() override;
+   scoped_refptr<TargetPolicy> CreatePolicy() override;
+   ResultCode SpawnTarget(const wchar_t* exe_path,
+                          const wchar_t* command_line,
++                         base::EnvironmentMap& env_map,
+                          scoped_refptr<TargetPolicy> policy,
+                          ResultCode* last_warning,
+                          DWORD* last_error,
+                          PROCESS_INFORMATION* target) override;
+   ResultCode WaitForAllTargets() override;
+   ResultCode AddTargetPeer(HANDLE peer_process) override;
+ 
+   // Checks if the supplied process ID matches one of the broker's active
+diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox.h b/security/sandbox/chromium/sandbox/win/src/sandbox.h
+--- a/security/sandbox/chromium/sandbox/win/src/sandbox.h
++++ b/security/sandbox/chromium/sandbox/win/src/sandbox.h
+@@ -79,16 +79,17 @@ class BrokerServices {
+   //   parameter will hold the last Win32 error value.
+   //   target: returns the resulting target process information such as process
+   //   handle and PID just as if CreateProcess() had been called. The caller is
+   //   responsible for closing the handles returned in this structure.
+   // Returns:
+   //   ALL_OK if successful. All other return values imply failure.
+   virtual ResultCode SpawnTarget(const wchar_t* exe_path,
+                                  const wchar_t* command_line,
++                                 base::EnvironmentMap& env_map,
+                                  scoped_refptr<TargetPolicy> policy,
+                                  ResultCode* last_warning,
+                                  DWORD* last_error,
+                                  PROCESS_INFORMATION* target) = 0;
+ 
+   // This call blocks (waits) for all the targets to terminate.
+   // Returns:
+   //   ALL_OK if successful. All other return values imply failure.
+diff --git a/security/sandbox/chromium/sandbox/win/src/target_process.cc b/security/sandbox/chromium/sandbox/win/src/target_process.cc
+--- a/security/sandbox/chromium/sandbox/win/src/target_process.cc
++++ b/security/sandbox/chromium/sandbox/win/src/target_process.cc
+@@ -137,16 +137,17 @@ TargetProcess::~TargetProcess() {
+ // Creates the target (child) process suspended and assigns it to the job
+ // object.
+ ResultCode TargetProcess::Create(
+     const wchar_t* exe_path,
+     const wchar_t* command_line,
+     bool inherit_handles,
+     const base::win::StartupInformation& startup_info,
+     base::win::ScopedProcessInformation* target_info,
++    base::EnvironmentMap& env_changes,
+     DWORD* win_error) {
+   exe_name_.reset(_wcsdup(exe_path));
+ 
+   // the command line needs to be writable by CreateProcess().
+   std::unique_ptr<wchar_t, base::FreeDeleter> cmd_line(_wcsdup(command_line));
+ 
+   // Start the target process suspended.
+   DWORD flags =
+@@ -156,22 +157,29 @@ ResultCode TargetProcess::Create(
+     flags |= EXTENDED_STARTUPINFO_PRESENT;
+ 
+   if (job_ && base::win::GetVersion() < base::win::VERSION_WIN8) {
+     // Windows 8 implements nested jobs, but for older systems we need to
+     // break out of any job we're in to enforce our restrictions.
+     flags |= CREATE_BREAKAWAY_FROM_JOB;
+   }
+ 
++  LPTCH original_environment = GetEnvironmentStrings();
++  base::NativeEnvironmentString new_environment =
++    base::AlterEnvironment(original_environment, env_changes);
++  // Ignore return value? What can we do?
++  FreeEnvironmentStrings(original_environment);
++  LPVOID new_env_ptr = (void*)new_environment.data();
++
+   PROCESS_INFORMATION temp_process_info = {};
+   if (!::CreateProcessAsUserW(lockdown_token_.Get(), exe_path, cmd_line.get(),
+                               nullptr,  // No security attribute.
+                               nullptr,  // No thread attribute.
+                               inherit_handles, flags,
+-                              nullptr,  // Use the environment of the caller.
++                              new_env_ptr,
+                               nullptr,  // Use current directory of the caller.
+                               startup_info.startup_info(),
+                               &temp_process_info)) {
+     *win_error = ::GetLastError();
+     return SBOX_ERROR_CREATE_PROCESS;
+   }
+   base::win::ScopedProcessInformation process_info(temp_process_info);
+ 
+diff --git a/security/sandbox/chromium/sandbox/win/src/target_process.h b/security/sandbox/chromium/sandbox/win/src/target_process.h
+--- a/security/sandbox/chromium/sandbox/win/src/target_process.h
++++ b/security/sandbox/chromium/sandbox/win/src/target_process.h
+@@ -9,16 +9,17 @@
+ 
+ #include <stddef.h>
+ #include <stdint.h>
+ 
+ #include <memory>
+ #include <vector>
+ 
+ #include "base/macros.h"
++#include "base/environment.h"
+ #include "base/memory/free_deleter.h"
+ #include "base/win/scoped_handle.h"
+ #include "base/win/scoped_process_information.h"
+ #include "sandbox/win/src/crosscall_server.h"
+ #include "sandbox/win/src/sandbox_types.h"
+ 
+ namespace base {
+ namespace win {
+@@ -54,16 +55,17 @@ class TargetProcess {
+   void Release() {}
+ 
+   // Creates the new target process. The process is created suspended.
+   ResultCode Create(const wchar_t* exe_path,
+                     const wchar_t* command_line,
+                     bool inherit_handles,
+                     const base::win::StartupInformation& startup_info,
+                     base::win::ScopedProcessInformation* target_info,
++                    base::EnvironmentMap& env_map,
+                     DWORD* win_error);
+ 
+   // Assign a new lowbox token to the process post creation. The process
+   // must still be in its initial suspended state, however this still
+   // might fail in the presence of third-party software.
+   ResultCode AssignLowBoxToken(const base::win::ScopedHandle& token);
+ 
+   // Destroys the target process.
--- a/security/sandbox/chromium-shim/patches/with_update/allow_read_only_all_paths_rule.patch
+++ b/security/sandbox/chromium-shim/patches/with_update/allow_read_only_all_paths_rule.patch
@@ -6,115 +6,117 @@
 # Parent  96707276b26997ea2a8e9fd8fdacc0c863717e7b
 Allow a special all paths rule in the Windows process sandbox when using semantics FILES_ALLOW_READONLY. r=jimm
 
 This also changes the read only related status checks in filesystem_interception.cc to include STATUS_NETWORK_OPEN_RESTRICTION (0xC0000201), which gets returned in some cases and fails because we never ask the broker.
 
 diff --git a/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc b/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc
 --- a/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/filesystem_interception.cc
-@@ -10,32 +10,37 @@
+@@ -11,16 +11,20 @@
  #include "sandbox/win/src/ipc_tags.h"
  #include "sandbox/win/src/policy_params.h"
  #include "sandbox/win/src/policy_target.h"
  #include "sandbox/win/src/sandbox_factory.h"
  #include "sandbox/win/src/sandbox_nt_util.h"
  #include "sandbox/win/src/sharedmem_ipc_client.h"
  #include "sandbox/win/src/target_services.h"
  
 +// This status occurs when trying to access a network share on the machine from
 +// which it is shared.
 +#define STATUS_NETWORK_OPEN_RESTRICTION ((NTSTATUS)0xC0000201L)
 +
  namespace sandbox {
  
  NTSTATUS WINAPI TargetNtCreateFile(NtCreateFileFunction orig_CreateFile,
-                                    PHANDLE file, ACCESS_MASK desired_access,
+                                    PHANDLE file,
+                                    ACCESS_MASK desired_access,
                                     POBJECT_ATTRIBUTES object_attributes,
                                     PIO_STATUS_BLOCK io_status,
                                     PLARGE_INTEGER allocation_size,
-                                    ULONG file_attributes, ULONG sharing,
-                                    ULONG disposition, ULONG options,
-                                    PVOID ea_buffer, ULONG ea_length) {
+@@ -29,17 +33,18 @@ NTSTATUS WINAPI TargetNtCreateFile(NtCre
+                                    ULONG disposition,
+                                    ULONG options,
+                                    PVOID ea_buffer,
+                                    ULONG ea_length) {
    // Check if the process can open it first.
-   NTSTATUS status = orig_CreateFile(file, desired_access, object_attributes,
-                                     io_status, allocation_size,
-                                     file_attributes, sharing, disposition,
-                                     options, ea_buffer, ea_length);
+   NTSTATUS status = orig_CreateFile(
+       file, desired_access, object_attributes, io_status, allocation_size,
+       file_attributes, sharing, disposition, options, ea_buffer, ea_length);
 -  if (STATUS_ACCESS_DENIED != status)
 +  if (STATUS_ACCESS_DENIED != status &&
 +      STATUS_NETWORK_OPEN_RESTRICTION != status)
      return status;
  
    // We don't trust that the IPC can work this early.
    if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
      return status;
  
-   wchar_t* name = NULL;
    do {
-@@ -101,17 +106,18 @@ NTSTATUS WINAPI TargetNtCreateFile(NtCre
- NTSTATUS WINAPI TargetNtOpenFile(NtOpenFileFunction orig_OpenFile, PHANDLE file,
+     if (!ValidParameter(file, sizeof(HANDLE), WRITE))
+@@ -106,17 +111,18 @@ NTSTATUS WINAPI TargetNtCreateFile(NtCre
                                   ACCESS_MASK desired_access,
                                   POBJECT_ATTRIBUTES object_attributes,
-                                  PIO_STATUS_BLOCK io_status, ULONG sharing,
+                                  PIO_STATUS_BLOCK io_status,
+                                  ULONG sharing,
                                   ULONG options) {
    // Check if the process can open it first.
    NTSTATUS status = orig_OpenFile(file, desired_access, object_attributes,
                                    io_status, sharing, options);
 -  if (STATUS_ACCESS_DENIED != status)
 +  if (STATUS_ACCESS_DENIED != status &&
 +      STATUS_NETWORK_OPEN_RESTRICTION != status)
      return status;
  
    // We don't trust that the IPC can work this early.
    if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
      return status;
  
-   wchar_t* name = NULL;
    do {
-@@ -173,17 +179,18 @@ NTSTATUS WINAPI TargetNtOpenFile(NtOpenF
+     if (!ValidParameter(file, sizeof(HANDLE), WRITE))
+@@ -176,17 +182,18 @@ NTSTATUS WINAPI TargetNtOpenFile(NtOpenF
  }
  
- NTSTATUS WINAPI TargetNtQueryAttributesFile(
-     NtQueryAttributesFileFunction orig_QueryAttributes,
-     POBJECT_ATTRIBUTES object_attributes,
-     PFILE_BASIC_INFORMATION file_attributes) {
+ NTSTATUS WINAPI
+ TargetNtQueryAttributesFile(NtQueryAttributesFileFunction orig_QueryAttributes,
+                             POBJECT_ATTRIBUTES object_attributes,
+                             PFILE_BASIC_INFORMATION file_attributes) {
    // Check if the process can query it first.
    NTSTATUS status = orig_QueryAttributes(object_attributes, file_attributes);
 -  if (STATUS_ACCESS_DENIED != status)
 +  if (STATUS_ACCESS_DENIED != status &&
 +      STATUS_NETWORK_OPEN_RESTRICTION != status)
      return status;
  
    // We don't trust that the IPC can work this early.
    if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
      return status;
  
-   wchar_t* name = NULL;
    do {
-@@ -231,17 +238,18 @@ NTSTATUS WINAPI TargetNtQueryAttributesF
+     if (!ValidParameter(file_attributes, sizeof(FILE_BASIC_INFORMATION), WRITE))
+@@ -232,17 +239,18 @@ NTSTATUS WINAPI TargetNtQueryAttributesF
  
  NTSTATUS WINAPI TargetNtQueryFullAttributesFile(
      NtQueryFullAttributesFileFunction orig_QueryFullAttributes,
      POBJECT_ATTRIBUTES object_attributes,
      PFILE_NETWORK_OPEN_INFORMATION file_attributes) {
    // Check if the process can query it first.
-   NTSTATUS status = orig_QueryFullAttributes(object_attributes,
-                                              file_attributes);
+   NTSTATUS status =
+       orig_QueryFullAttributes(object_attributes, file_attributes);
 -  if (STATUS_ACCESS_DENIED != status)
 +  if (STATUS_ACCESS_DENIED != status &&
 +      STATUS_NETWORK_OPEN_RESTRICTION != status)
      return status;
  
    // We don't trust that the IPC can work this early.
    if (!SandboxFactory::GetTargetServices()->GetState()->InitCalled())
      return status;
  
-   wchar_t* name = NULL;
    do {
+     if (!ValidParameter(file_attributes, sizeof(FILE_NETWORK_OPEN_INFORMATION),
 diff --git a/security/sandbox/chromium/sandbox/win/src/filesystem_policy.cc b/security/sandbox/chromium/sandbox/win/src/filesystem_policy.cc
 --- a/security/sandbox/chromium/sandbox/win/src/filesystem_policy.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/filesystem_policy.cc
 @@ -77,17 +77,21 @@ namespace sandbox {
  bool FileSystemPolicy::GenerateRules(const wchar_t* name,
                                       TargetPolicy::Semantics semantics,
                                       LowLevelPolicy* policy) {
    base::string16 mod_name(name);
deleted file mode 100644
--- a/security/sandbox/chromium-shim/patches/with_update/apply_upstream_alternate_desktop_fix.patch
+++ /dev/null
@@ -1,189 +0,0 @@
-# HG changeset patch
-# User Alex Gaynor <agaynor@mozilla.com>
-# Date 1504297684 0
-#      Fri Sep 01 20:28:04 2017 +0000
-# Node ID b96cc614adbd07273d66e1a5725dded8a3583c47
-# Parent  0f11c5ecbaefbe66f9236a93090e8fb4a61cd37b
-[PATCH] Correct two bugs in Windows sandboxing alternate desktops:
-From db4c64b63d6098294ed255e962700fd2d465575e Mon Sep 17 00:00:00 2001
-When a parent has two alternate desktops, one on a local winstation, the
-other on an alternate winstation:
-
-1) Ensure the desktops have different names.
-2) Ensure both desktops have their integrity level set correctly.
-
-Bug: https://bugzilla.mozilla.org/show_bug.cgi?id=1229829#c11
-Cq-Include-Trybots: master.tryserver.chromium.win:win10_chromium_x64_rel_ng
-Change-Id: I2d17779e389c9f74146a83d97d62babffa903184
-Reviewed-on: https://chromium-review.googlesource.com/638872
-Reviewed-by: Will Harris <wfh@chromium.org>
-Commit-Queue: Will Harris <wfh@chromium.org>
-Cr-Commit-Position: refs/heads/master@{#499280}
----
-
-diff --git a/security/sandbox/chromium/sandbox/win/src/policy_target_test.cc b/security/sandbox/chromium/sandbox/win/src/policy_target_test.cc
---- a/security/sandbox/chromium/sandbox/win/src/policy_target_test.cc
-+++ b/security/sandbox/chromium/sandbox/win/src/policy_target_test.cc
-@@ -373,16 +373,26 @@ TEST(PolicyTargetTest, BothLocalAndAlter
-   ResultCode result;
-   result = policy1->SetAlternateDesktop(false);
-   EXPECT_EQ(SBOX_ALL_OK, result);
-   result = policy2->SetAlternateDesktop(true);
-   EXPECT_EQ(SBOX_ALL_OK, result);
-   result = policy3->SetAlternateDesktop(false);
-   EXPECT_EQ(SBOX_ALL_OK, result);
- 
-+  base::string16 policy1_desktop_name = policy1->GetAlternateDesktop();
-+  base::string16 policy2_desktop_name = policy2->GetAlternateDesktop();
-+
-+  // Extract only the "desktop name" portion of
-+  // "{winstation name}\\{desktop name}"
-+  EXPECT_NE(policy1_desktop_name.substr(
-+                policy1_desktop_name.find_first_of(L'\\') + 1),
-+            policy2_desktop_name.substr(
-+                policy2_desktop_name.find_first_of(L'\\') + 1));
-+
-   policy1->DestroyAlternateDesktop();
-   policy2->DestroyAlternateDesktop();
-   policy3->DestroyAlternateDesktop();
- }
- 
- // Launches the app in the sandbox and share a handle with it. The app should
- // be able to use the handle.
- TEST(PolicyTargetTest, ShareHandleTest) {
-diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.cc b/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.cc
---- a/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.cc
-+++ b/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.cc
-@@ -111,16 +111,19 @@ SANDBOX_INTERCEPT MitigationFlags g_shar
- // Initializes static members. alternate_desktop_handle_ is a desktop on
- // alternate_winstation_handle_, alternate_desktop_local_winstation_handle_ is a
- // desktop on the same winstation as the parent process.
- HWINSTA PolicyBase::alternate_winstation_handle_ = nullptr;
- HDESK PolicyBase::alternate_desktop_handle_ = nullptr;
- HDESK PolicyBase::alternate_desktop_local_winstation_handle_ = nullptr;
- IntegrityLevel PolicyBase::alternate_desktop_integrity_level_label_ =
-     INTEGRITY_LEVEL_SYSTEM;
-+IntegrityLevel
-+    PolicyBase::alternate_desktop_local_winstation_integrity_level_label_ =
-+        INTEGRITY_LEVEL_SYSTEM;
- 
- PolicyBase::PolicyBase()
-     : ref_count(1),
-       lockdown_level_(USER_LOCKDOWN),
-       initial_level_(USER_LOCKDOWN),
-       job_level_(JOB_LOCKDOWN),
-       ui_exceptions_(0),
-       memory_limit_(0),
-@@ -442,36 +445,44 @@ ResultCode PolicyBase::MakeTokens(base::
-                             lockdown_default_dacl_, lockdown);
-   if (ERROR_SUCCESS != result)
-     return SBOX_ERROR_GENERIC;
- 
-   // If we're launching on the alternate desktop we need to make sure the
-   // integrity label on the object is no higher than the sandboxed process's
-   // integrity level. So, we lower the label on the desktop process if it's
-   // not already low enough for our process.
--  if (use_alternate_desktop_ && integrity_level_ != INTEGRITY_LEVEL_LAST &&
--      alternate_desktop_integrity_level_label_ < integrity_level_) {
-+  if (use_alternate_desktop_ && integrity_level_ != INTEGRITY_LEVEL_LAST) {
-     // Integrity label enum is reversed (higher level is a lower value).
-     static_assert(INTEGRITY_LEVEL_SYSTEM < INTEGRITY_LEVEL_UNTRUSTED,
-                   "Integrity level ordering reversed.");
-     HDESK desktop_handle = nullptr;
-+    IntegrityLevel desktop_integrity_level_label;
-     if (use_alternate_winstation_) {
-       desktop_handle = alternate_desktop_handle_;
-+      desktop_integrity_level_label = alternate_desktop_integrity_level_label_;
-     } else {
-       desktop_handle = alternate_desktop_local_winstation_handle_;
-+      desktop_integrity_level_label =
-+          alternate_desktop_local_winstation_integrity_level_label_;
-     }
-     // If the desktop_handle hasn't been created for any reason, skip this.
--    if (desktop_handle) {
-+    if (desktop_handle && desktop_integrity_level_label < integrity_level_) {
-       result =
-           SetObjectIntegrityLabel(desktop_handle, SE_WINDOW_OBJECT, L"",
-                                   GetIntegrityLevelString(integrity_level_));
-       if (ERROR_SUCCESS != result)
-         return SBOX_ERROR_GENERIC;
- 
--      alternate_desktop_integrity_level_label_ = integrity_level_;
-+      if (use_alternate_winstation_) {
-+        alternate_desktop_integrity_level_label_ = integrity_level_;
-+      } else {
-+        alternate_desktop_local_winstation_integrity_level_label_ =
-+            integrity_level_;
-+      }
-     }
-   }
- 
-   if (lowbox_sid_) {
-     NtCreateLowBoxToken CreateLowBoxToken = NULL;
-     ResolveNTFunctionPtr("NtCreateLowBoxToken", &CreateLowBoxToken);
-     OBJECT_ATTRIBUTES obj_attr;
-     InitializeObjectAttributes(&obj_attr, NULL, 0, NULL, NULL);
-diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.h b/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.h
---- a/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.h
-+++ b/security/sandbox/chromium/sandbox/win/src/sandbox_policy_base.h
-@@ -157,16 +157,18 @@ class PolicyBase final : public TargetPo
-   base::win::ScopedHandle lowbox_directory_;
-   std::unique_ptr<Dispatcher> dispatcher_;
-   bool lockdown_default_dacl_;
- 
-   static HDESK alternate_desktop_handle_;
-   static HWINSTA alternate_winstation_handle_;
-   static HDESK alternate_desktop_local_winstation_handle_;
-   static IntegrityLevel alternate_desktop_integrity_level_label_;
-+  static IntegrityLevel
-+      alternate_desktop_local_winstation_integrity_level_label_;
- 
-   // Contains the list of handles being shared with the target process.
-   // This list contains handles other than the stderr/stdout handles which are
-   // shared with the target at times.
-   base::HandlesToInheritVector handles_to_share_;
-   bool enable_opm_redirection_;
- 
-   DISALLOW_COPY_AND_ASSIGN(PolicyBase);
-diff --git a/security/sandbox/chromium/sandbox/win/src/window.cc b/security/sandbox/chromium/sandbox/win/src/window.cc
---- a/security/sandbox/chromium/sandbox/win/src/window.cc
-+++ b/security/sandbox/chromium/sandbox/win/src/window.cc
-@@ -26,17 +26,17 @@ bool GetSecurityAttributes(HANDLE handle
-                                    DACL_SECURITY_INFORMATION, NULL, NULL, &dacl,
-                                    NULL, &attributes->lpSecurityDescriptor);
-   if (ERROR_SUCCESS == result)
-     return true;
- 
-   return false;
- }
- 
--}
-+}  // namespace
- 
- namespace sandbox {
- 
- ResultCode CreateAltWindowStation(HWINSTA* winsta) {
-   // Get the security attributes from the current window station; we will
-   // use this as the base security attributes for the new window station.
-   HWINSTA current_winsta = ::GetProcessWindowStation();
-   if (!current_winsta)
-@@ -60,16 +60,20 @@ ResultCode CreateAltWindowStation(HWINST
-     return SBOX_ALL_OK;
- 
-   return SBOX_ERROR_CANNOT_CREATE_WINSTATION;
- }
- 
- ResultCode CreateAltDesktop(HWINSTA winsta, HDESK* desktop) {
-   base::string16 desktop_name = L"sbox_alternate_desktop_";
- 
-+  if (!winsta) {
-+    desktop_name += L"local_winstation_";
-+  }
-+
-   // Append the current PID to the desktop name.
-   wchar_t buffer[16];
-   _snwprintf_s(buffer, sizeof(buffer) / sizeof(wchar_t), L"0x%X",
-                ::GetCurrentProcessId());
-   desktop_name += buffer;
- 
-   HDESK current_desktop = GetThreadDesktop(GetCurrentThreadId());
deleted file mode 100644
--- a/security/sandbox/chromium-shim/patches/with_update/fix_Wcomma_warning_in_time_cc.patch
+++ /dev/null
@@ -1,41 +0,0 @@
-# HG changeset patch
-# User Daniel Holbert <dholbert@cs.stanford.edu>
-# Date 1496432701 25200
-#      Fri Jun 02 12:45:01 2017 -0700
-# Node ID 9877f0ae77cd45046182caa62cbf9518a2b73451
-# Parent  25facf3ac669983297260e34b010edb0c10c1ac3
-Add a void cast to silence clang Wcomma build warning, in sandbox's snapshot of chromium header. r=bobowen
-
-The build warning is for "possible misuse of comma operator".
-
-The comma operator is a bit of a footgun becasue its first operand's result
-just gets dropped on the floor (in this case, the result of the DCHECK
-expression).  It appears that Chromium's use of the comma operator here is
-intentional, though -- so we might as well accept clang's suggestion and "cast
-expression to void to silence warning".
-
-This is also filed upstream as:
- https://bugs.chromium.org/p/chromium/issues/detail?id=729123
-
-diff --git a/security/sandbox/chromium/base/time/time.h b/security/sandbox/chromium/base/time/time.h
---- a/security/sandbox/chromium/base/time/time.h
-+++ b/security/sandbox/chromium/base/time/time.h
-@@ -724,17 +724,17 @@ constexpr TimeDelta TimeDelta::FromDoubl
- // static
- constexpr TimeDelta TimeDelta::FromProduct(int64_t value,
-                                            int64_t positive_value) {
-   return (
- #if !defined(_PREFAST_) || !defined(OS_WIN)
-       // Avoid internal compiler errors in /analyze builds with VS 2015
-       // update 3.
-       // https://connect.microsoft.com/VisualStudio/feedback/details/2870865
--      DCHECK(positive_value > 0),
-+      static_cast<void>(DCHECK(positive_value > 0)),
- #endif
-       value > std::numeric_limits<int64_t>::max() / positive_value
-           ? Max()
-           : value < std::numeric_limits<int64_t>::min() / positive_value
-                 ? Min()
-                 : TimeDelta(value * positive_value));
- }
- 
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/patches/with_update/fix_incorrect_int_use_in_Kernel32BaseVersion.patch
@@ -0,0 +1,40 @@
+# HG changeset patch
+# User Bob Owen <bobowencode@gmail.com>
+# Date 1549903491 0
+#      Mon Feb 11 16:44:51 2019 +0000
+# Node ID 3bb3e5a6275db53530d50549b7b329cc1248d450
+# Parent  fc9d5e40028058abeb06f8bdc2f75fc868fbe14b
+
+Fix incorrect int use in Kernel32BaseVersion in windows_version.cc. r=aklotz
+
+diff --git a/security/sandbox/chromium/base/win/windows_version.cc b/security/sandbox/chromium/base/win/windows_version.cc
+--- a/security/sandbox/chromium/base/win/windows_version.cc
++++ b/security/sandbox/chromium/base/win/windows_version.cc
+@@ -236,23 +236,23 @@ Version OSInfo::Kernel32Version() const 
+ // kernel32 will still be the "real" version.
+ base::Version OSInfo::Kernel32BaseVersion() const {
+   static const base::NoDestructor<base::Version> version([] {
+     std::unique_ptr<FileVersionInfoWin> file_version_info(
+         static_cast<FileVersionInfoWin*>(
+             FileVersionInfoWin::CreateFileVersionInfo(
+                 base::FilePath(FILE_PATH_LITERAL("kernel32.dll")))));
+     DCHECK(file_version_info);
+-    const int major =
++    const uint32_t major =
+         HIWORD(file_version_info->fixed_file_info()->dwFileVersionMS);
+-    const int minor =
++    const uint32_t minor =
+         LOWORD(file_version_info->fixed_file_info()->dwFileVersionMS);
+-    const int build =
++    const uint32_t build =
+         HIWORD(file_version_info->fixed_file_info()->dwFileVersionLS);
+-    const int patch =
++    const uint32_t patch =
+         LOWORD(file_version_info->fixed_file_info()->dwFileVersionLS);
+     return base::Version(std::vector<uint32_t>{major, minor, build, patch});
+   }());
+   return *version;
+ }
+ 
+ std::string OSInfo::processor_model_name() {
+   if (processor_model_name_.empty()) {
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/patches/with_update/ifdef_out_AppContainerProfileBase_testing_functions.patch
@@ -0,0 +1,79 @@
+# HG changeset patch
+# User Bob Owen <bobowencode@gmail.com>
+# Date 1560259052 -3600
+#      Tue Jun 11 14:17:32 2019 +0100
+# Node ID ca1bafe49015cb6625648274f32959e4160a6ce9
+# Parent  3ec022faaf83642e3c1894d83ff99926bada990c
+Hash if out testing functions that cause dependency creep. r=aklotz
+
+diff --git a/security/sandbox/chromium/sandbox/win/src/app_container_profile_base.cc b/security/sandbox/chromium/sandbox/win/src/app_container_profile_base.cc
+--- a/security/sandbox/chromium/sandbox/win/src/app_container_profile_base.cc
++++ b/security/sandbox/chromium/sandbox/win/src/app_container_profile_base.cc
+@@ -3,17 +3,19 @@
+ // found in the LICENSE file.
+ 
+ #include <memory>
+ 
+ #include <aclapi.h>
+ #include <userenv.h>
+ 
+ #include "base/strings/stringprintf.h"
++#if !defined(MOZ_SANDBOX)
+ #include "base/win/scoped_co_mem.h"
++#endif
+ #include "base/win/scoped_handle.h"
+ #include "sandbox/win/src/app_container_profile_base.h"
+ #include "sandbox/win/src/restricted_token_utils.h"
+ #include "sandbox/win/src/win_utils.h"
+ 
+ namespace sandbox {
+ 
+ namespace {
+@@ -167,39 +169,47 @@ bool AppContainerProfileBase::GetRegistr
+   HKEY key_handle;
+   if (FAILED(get_app_container_registry_location(desired_access, &key_handle)))
+     return false;
+   key->Set(key_handle);
+   return true;
+ }
+ 
+ bool AppContainerProfileBase::GetFolderPath(base::FilePath* file_path) {
++#if defined(MOZ_SANDBOX)
++  IMMEDIATE_CRASH();
++#else
+   static GetAppContainerFolderPathFunc* get_app_container_folder_path =
+       reinterpret_cast<GetAppContainerFolderPathFunc*>(GetProcAddress(
+           GetModuleHandle(L"userenv"), "GetAppContainerFolderPath"));
+   if (!get_app_container_folder_path)
+     return false;
+   base::string16 sddl_str;
+   if (!package_sid_.ToSddlString(&sddl_str))
+     return false;
+   base::win::ScopedCoMem<wchar_t> path_str;
+   if (FAILED(get_app_container_folder_path(sddl_str.c_str(), &path_str)))
+     return false;
+   *file_path = base::FilePath(path_str.get());
+   return true;
++#endif
+ }
+ 
+ bool AppContainerProfileBase::GetPipePath(const wchar_t* pipe_name,
+                                           base::FilePath* pipe_path) {
++#if defined(MOZ_SANDBOX)
++  IMMEDIATE_CRASH();
++#else
+   base::string16 sddl_str;
+   if (!package_sid_.ToSddlString(&sddl_str))
+     return false;
+   *pipe_path = base::FilePath(base::StringPrintf(L"\\\\.\\pipe\\%ls\\%ls",
+                                                  sddl_str.c_str(), pipe_name));
+   return true;
++#endif
+ }
+ 
+ bool AppContainerProfileBase::AccessCheck(const wchar_t* object_name,
+                                           SE_OBJECT_TYPE object_type,
+                                           DWORD desired_access,
+                                           DWORD* granted_access,
+                                           BOOL* access_status) {
+   GENERIC_MAPPING generic_mapping;
--- a/security/sandbox/chromium-shim/patches/with_update/ifdef_out_FromStringInternal.patch
+++ b/security/sandbox/chromium-shim/patches/with_update/ifdef_out_FromStringInternal.patch
@@ -23,17 +23,17 @@ diff --git a/security/sandbox/chromium/b
    return Time();
  }
  
 +#if !defined(MOZ_SANDBOX)
  // static
  bool Time::FromStringInternal(const char* time_string,
                                bool is_local,
                                Time* parsed_time) {
-   DCHECK((time_string != NULL) && (parsed_time != NULL));
+   DCHECK((time_string != nullptr) && (parsed_time != nullptr));
  
    if (time_string[0] == '\0')
      return false;
 @@ -261,16 +262,17 @@ bool Time::FromStringInternal(const char
                                         &result_time);
    if (PR_SUCCESS != result)
      return false;
  
--- a/security/sandbox/chromium-shim/patches/with_update/ifdef_out_SequenceChecker_code.patch
+++ b/security/sandbox/chromium-shim/patches/with_update/ifdef_out_SequenceChecker_code.patch
@@ -6,20 +6,20 @@
 # Parent  bbbba04e693f3819bcb6dd70ea27d3cab194e4cb
 This removes sequence checking on RefCountedBase in DEBUG builds. r=aklotz
 
 We don't currently make use of it and it brings in many dependencies.
 
 diff --git a/security/sandbox/chromium/base/memory/ref_counted.cc b/security/sandbox/chromium/base/memory/ref_counted.cc
 --- a/security/sandbox/chromium/base/memory/ref_counted.cc
 +++ b/security/sandbox/chromium/base/memory/ref_counted.cc
-@@ -34,18 +34,22 @@ bool RefCountedThreadSafeBase::Release()
+@@ -53,18 +53,22 @@ bool RefCountedThreadSafeBase::Release()
  }
- void RefCountedThreadSafeBase::AddRef() const {
-   AddRefImpl();
+ void RefCountedThreadSafeBase::AddRefWithCheck() const {
+   AddRefWithCheckImpl();
  }
  #endif
  
  #if DCHECK_IS_ON()
  bool RefCountedBase::CalledOnValidSequence() const {
 +#if defined(MOZ_SANDBOX)
 +  return true;
 +#else
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/patches/with_update/include_atomic_header_in_platform_thread.patch
@@ -0,0 +1,27 @@
+# HG changeset patch
+# User Bob Owen <bobowencode@gmail.com>
+# Date 1560260570 -3600
+#      Tue Jun 11 14:42:50 2019 +0100
+# Node ID 7baa38185938e45ab128ec3975ae139753c8ad67
+# Parent  cb568f9b29f8c2c84c72c49b7a565d8081929f04
+Bug 1552160: Fix missing atomic include in chromium platform_thread.cc. r=jld
+
+diff --git a/security/sandbox/chromium/base/threading/platform_thread.cc b/security/sandbox/chromium/base/threading/platform_thread.cc
+--- a/security/sandbox/chromium/base/threading/platform_thread.cc
++++ b/security/sandbox/chromium/base/threading/platform_thread.cc
+@@ -1,14 +1,15 @@
+ // Copyright 2018 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/threading/platform_thread.h"
+ 
++#include <atomic>
+ #include <memory>
+ 
+ #include "base/feature_list.h"
+ 
+ namespace base {
+ 
+ namespace {
+ 
--- a/security/sandbox/chromium-shim/patches/with_update/mingw_capitalization.patch
+++ b/security/sandbox/chromium-shim/patches/with_update/mingw_capitalization.patch
@@ -1,15 +1,15 @@
 # HG changeset patch
 # User Tom Ritter <tom@mozilla.com>
 # Date 1516825559 21600
 #      Wed Jan 24 14:25:59 2018 -0600
-# Node ID 3fc024ee4ac9f68acf3ad27cfbfdf1527f20438b
-# Parent  bba456aaff2bebb7dc4b695cfb8cb5d492a7c402
-Bug 1431797 Correct the capitalization of headers inside the chromium code so MinGW can compile r?bobowen
+# Node ID 9ce534c9f572dfb5abd3e409d9cfec069ccee0cd
+# Parent  6413cb580dccd986c61e6dbdc72fc370765b8f10
+Bug 1431797 Correct the capitalization of headers inside the chromium code so MinGW can compile
 
 diff --git a/security/sandbox/chromium/base/rand_util_win.cc b/security/sandbox/chromium/base/rand_util_win.cc
 --- a/security/sandbox/chromium/base/rand_util_win.cc
 +++ b/security/sandbox/chromium/base/rand_util_win.cc
 @@ -7,17 +7,17 @@
  #include <windows.h>
  #include <stddef.h>
  #include <stdint.h>
@@ -26,18 +26,18 @@ diff --git a/security/sandbox/chromium/b
  #include <limits>
  
  #include "base/logging.h"
  
  namespace base {
 diff --git a/security/sandbox/chromium/base/win/pe_image.h b/security/sandbox/chromium/base/win/pe_image.h
 --- a/security/sandbox/chromium/base/win/pe_image.h
 +++ b/security/sandbox/chromium/base/win/pe_image.h
-@@ -12,17 +12,17 @@
- #define BASE_WIN_PE_IMAGE_H_
+@@ -14,17 +14,17 @@
+ #include <stdint.h>
  
  #include <windows.h>
  
  #if defined(_WIN32_WINNT_WIN8)
  // The Windows 8 SDK defines FACILITY_VISUALCPP in winerror.h.
  #undef FACILITY_VISUALCPP
  #endif
 -#include <DelayIMP.h>
@@ -45,57 +45,16 @@ diff --git a/security/sandbox/chromium/b
  
  namespace base {
  namespace win {
  
  // This class is a wrapper for the Portable Executable File Format (PE).
  // Its main purpose is to provide an easy way to work with imports and exports
  // from a file, mapped in memory as image.
  class PEImage {
-diff --git a/security/sandbox/chromium/sandbox/win/src/acl.h b/security/sandbox/chromium/sandbox/win/src/acl.h
---- a/security/sandbox/chromium/sandbox/win/src/acl.h
-+++ b/security/sandbox/chromium/sandbox/win/src/acl.h
-@@ -1,16 +1,16 @@
- // 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 SANDBOX_SRC_ACL_H_
- #define SANDBOX_SRC_ACL_H_
- 
--#include <AccCtrl.h>
-+#include <accctrl.h>
- #include <windows.h>
- 
- #include <memory>
- 
- #include "base/memory/free_deleter.h"
- #include "sandbox/win/src/sid.h"
- 
- namespace sandbox {
-diff --git a/security/sandbox/chromium/sandbox/win/src/broker_services.cc b/security/sandbox/chromium/sandbox/win/src/broker_services.cc
---- a/security/sandbox/chromium/sandbox/win/src/broker_services.cc
-+++ b/security/sandbox/chromium/sandbox/win/src/broker_services.cc
-@@ -1,15 +1,15 @@
- // Copyright (c) 2012 The Chromium Authors. All rights reserved.
- // Use of this source code is governed by a BSD-style license that can be
- // found in the LICENSE file.
- 
- #include "sandbox/win/src/broker_services.h"
- 
--#include <AclAPI.h>
-+#include <aclapi.h>
- #include <stddef.h>
- 
- #include <utility>
- 
- #include "base/logging.h"
- #include "base/macros.h"
- #include "base/memory/ptr_util.h"
- #include "base/threading/platform_thread.h"
 diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_rand.cc b/security/sandbox/chromium/sandbox/win/src/sandbox_rand.cc
 --- a/security/sandbox/chromium/sandbox/win/src/sandbox_rand.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/sandbox_rand.cc
 @@ -5,17 +5,17 @@
  #include "sandbox/win/src/sandbox_rand.h"
  
  #include <windows.h>
  
@@ -105,11 +64,11 @@ diff --git a/security/sandbox/chromium/s
  #define SystemFunction036 NTAPI SystemFunction036
 -#include <NTSecAPI.h>
 +#include <ntsecapi.h>
  #undef SystemFunction036
  
  namespace sandbox {
  
  bool GetRandom(unsigned int* random_value) {
-   return RtlGenRandom(random_value, sizeof(unsigned int)) != FALSE;
+   return RtlGenRandom(random_value, sizeof(unsigned int)) != false;
  }
  
--- a/security/sandbox/chromium-shim/patches/with_update/mingw_cast_getprocaddress.patch
+++ b/security/sandbox/chromium-shim/patches/with_update/mingw_cast_getprocaddress.patch
@@ -5,74 +5,30 @@
 # Node ID 2b4556cb7407c196522e52cfd286ee88c3bb6e72
 # Parent  60aa47b111918d4e30f7e363359d1dcc3a3f277d
 Bug 1432295 Cast GetProcAddress to (void*) r?bobowen
 
 error: invalid conversion from 'FARPROC {aka int (__attribute__((__stdcall__)) *)()}' to 'void*' [-fpermissive]
 
 According to http://stackoverflow.com/questions/13958081/, msvc does the fixup
 
-diff --git a/security/sandbox/chromium/sandbox/win/src/resolver.cc b/security/sandbox/chromium/sandbox/win/src/resolver.cc
---- a/security/sandbox/chromium/sandbox/win/src/resolver.cc
-+++ b/security/sandbox/chromium/sandbox/win/src/resolver.cc
-@@ -48,17 +48,17 @@ NTSTATUS ResolverThunk::ResolveIntercept
-   DCHECK_NT(address);
-   if (!interceptor_module)
-     return STATUS_INVALID_PARAMETER;
- 
-   base::win::PEImage pe(interceptor_module);
-   if (!pe.VerifyMagic())
-     return STATUS_INVALID_IMAGE_FORMAT;
- 
--  *address = pe.GetProcAddress(interceptor_name);
-+  *address = reinterpret_cast<void*>(pe.GetProcAddress(interceptor_name));
- 
-   if (!(*address))
-     return STATUS_PROCEDURE_NOT_FOUND;
- 
-   return STATUS_SUCCESS;
- }
- 
- }  // namespace sandbox
-diff --git a/security/sandbox/chromium/sandbox/win/src/service_resolver.cc b/security/sandbox/chromium/sandbox/win/src/service_resolver.cc
---- a/security/sandbox/chromium/sandbox/win/src/service_resolver.cc
-+++ b/security/sandbox/chromium/sandbox/win/src/service_resolver.cc
-@@ -24,17 +24,17 @@ NTSTATUS ServiceResolverThunk::ResolveIn
- // just a simple GetProcAddress.
- NTSTATUS ServiceResolverThunk::ResolveTarget(const void* module,
-                                              const char* function_name,
-                                              void** address) {
-   if (NULL == module)
-     return STATUS_UNSUCCESSFUL;
- 
-   base::win::PEImage module_image(module);
--  *address = module_image.GetProcAddress(function_name);
-+  *address = (void*)module_image.GetProcAddress(function_name);
- 
-   if (NULL == *address) {
-     NOTREACHED_NT();
-     return STATUS_UNSUCCESSFUL;
-   }
- 
-   return STATUS_SUCCESS;
- }
 diff --git a/security/sandbox/chromium/sandbox/win/src/target_process.cc b/security/sandbox/chromium/sandbox/win/src/target_process.cc
 --- a/security/sandbox/chromium/sandbox/win/src/target_process.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/target_process.cc
-@@ -179,17 +179,17 @@ ResultCode TargetProcess::TransferVariab
+@@ -231,17 +231,17 @@ ResultCode TargetProcess::TransferVariab
  
    void* child_var = address;
  
  #if SANDBOX_EXPORTS
    HMODULE module = ::LoadLibrary(exe_name_.get());
-   if (NULL == module)
+   if (!module)
      return SBOX_ERROR_GENERIC;
  
 -  child_var = ::GetProcAddress(module, name);
-+  child_var = (void*)::GetProcAddress(module, name);
++  child_var = reinterpret_cast<void*>(::GetProcAddress(module, name));
    ::FreeLibrary(module);
  
-   if (NULL == child_var)
+   if (!child_var)
      return SBOX_ERROR_GENERIC;
  
-   size_t offset = reinterpret_cast<char*>(child_var) -
-                   reinterpret_cast<char*>(module);
+   size_t offset =
+       reinterpret_cast<char*>(child_var) - reinterpret_cast<char*>(module);
    child_var = reinterpret_cast<char*>(MainModule()) + offset;
deleted file mode 100644
--- a/security/sandbox/chromium-shim/patches/with_update/mingw_duplicate_instatinations.patch
+++ /dev/null
@@ -1,52 +0,0 @@
-# HG changeset patch
-# User Tom Ritter <tom@mozilla.com>
-# Date 1488911037 0
-#      Tue Mar 07 18:23:57 2017 +0000
-# Node ID b198c0d01cada4ad84f09897d7fc15f0dc03ceea
-# Parent  489e4a8d1628a79d07e1880c3b1818809515ba5f
-Bug 1431801 Don't declare duplicate instantiations. r?bobowen
-
-On MinGW, these typedefs are the same, and mingw complains about duplicate instantiations.
-Rather than use -fpermissive, just comment out the second instantiation.
-
-MozReview-Commit-ID: 5prsrStgwKY
-
-diff --git a/security/sandbox/chromium/base/strings/utf_string_conversion_utils.cc b/security/sandbox/chromium/base/strings/utf_string_conversion_utils.cc
---- a/security/sandbox/chromium/base/strings/utf_string_conversion_utils.cc
-+++ b/security/sandbox/chromium/base/strings/utf_string_conversion_utils.cc
-@@ -117,17 +117,20 @@ void PrepareForUTF8Output(const CHAR* sr
-   } else {
-     // Assume that the entire input is non-ASCII and will have 3 bytes per char.
-     output->reserve(src_len * 3);
-   }
- }
- 
- // Instantiate versions we know callers will need.
- template void PrepareForUTF8Output(const wchar_t*, size_t, std::string*);
-+#ifndef __MINGW32__
-+// On MinGW, these instantiations are the same, and MinGW complains if there are two
- template void PrepareForUTF8Output(const char16*, size_t, std::string*);
-+#endif
- 
- template<typename STRING>
- void PrepareForUTF16Or32Output(const char* src,
-                                size_t src_len,
-                                STRING* output) {
-   output->clear();
-   if (src_len == 0)
-     return;
-@@ -138,11 +141,14 @@ void PrepareForUTF16Or32Output(const cha
-     // Otherwise assume that the UTF-8 sequences will have 2 bytes for each
-     // character.
-     output->reserve(src_len / 2);
-   }
- }
- 
- // Instantiate versions we know callers will need.
- template void PrepareForUTF16Or32Output(const char*, size_t, std::wstring*);
-+#ifndef __MINGW32__
-+// On MinGW, these instantiations are the same, and MinGW complains if there are two
- template void PrepareForUTF16Or32Output(const char*, size_t, string16*);
-+#endif
- 
- }  // namespace base
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/patches/with_update/mingw_missing_windows_types_defines.patch
@@ -0,0 +1,37 @@
+# HG changeset patch
+# User Bob Owen <bobowencode@gmail.com>
+# Date 1558294860 -3600
+#      Sun May 19 20:41:00 2019 +0100
+# Node ID 331daa6926b2d495959a0aebbf034958a9bc1e2a
+# Parent  e71e4e7a914c2d2515bf84be6ad045febabb6dfc
+Bug 1552160: Add missing defines from concurrencysal.h and specstrings.h in windows_type.h on MinGW.
+
+diff --git a/security/sandbox/chromium/base/win/windows_types.h b/security/sandbox/chromium/base/win/windows_types.h
+--- a/security/sandbox/chromium/base/win/windows_types.h
++++ b/security/sandbox/chromium/base/win/windows_types.h
+@@ -4,17 +4,25 @@
+ 
+ // This file contains defines and typedefs that allow popular Windows types to
+ // be used without the overhead of including windows.h.
+ 
+ #ifndef BASE_WIN_WINDOWS_TYPES_H
+ #define BASE_WIN_WINDOWS_TYPES_H
+ 
+ // Needed for function prototypes.
++#if defined(__MINGW32__)
++// MinGW doesn't have this file yet, but we only need this define.
++// Bug 1552706 tracks removing this and the one below.
++#define _Releases_exclusive_lock_(lock)
++// MinGW doesn't appear to have this in specstrings.h either.
++#define _Post_equals_last_error_
++#else
+ #include <concurrencysal.h>
++#endif
+ #include <sal.h>
+ #include <specstrings.h>
+ 
+ #ifdef __cplusplus
+ extern "C" {
+ #endif
+ 
+ // typedef and define the most commonly used Windows integer types.
deleted file mode 100644
--- a/security/sandbox/chromium-shim/patches/with_update/mingw_noexports_casts.patch
+++ /dev/null
@@ -1,41 +0,0 @@
-# HG changeset patch
-# User Tom Ritter <tom@mozilla.com>
-# Date 1526498300 18000
-#      Wed May 16 14:18:20 2018 -0500
-# Node ID dd3f4940aeb0c4e00e8bcf1c238f2355ad793489
-# Parent  cf646c80b9545db7ab548f88a482378734ee2f78
-Bug 1462100 Cast to void* to avoid conversion errors on MinGW, which does not do the automatic conversion like msvc r?bobowen
-
-MozReview-Commit-ID: 8fO9Nu9gaxh
-
-diff --git a/security/sandbox/chromium/sandbox/win/src/interception.h b/security/sandbox/chromium/sandbox/win/src/interception.h
---- a/security/sandbox/chromium/sandbox/win/src/interception.h
-+++ b/security/sandbox/chromium/sandbox/win/src/interception.h
-@@ -264,25 +264,25 @@ class InterceptionManager {
- #define MAKE_SERVICE_NAME(service) &Target##service##64
- #else
- #define MAKE_SERVICE_NAME(service) &Target##service
- #endif
- 
- #define ADD_NT_INTERCEPTION(service, id, num_params) \
-   AddToPatchedFunctions(kNtdllName, #service, \
-                         sandbox::INTERCEPTION_SERVICE_CALL, \
--                        MAKE_SERVICE_NAME(service), id)
-+                        (void*)MAKE_SERVICE_NAME(service), id)
- 
- #define INTERCEPT_NT(manager, service, id, num_params) \
-   manager->ADD_NT_INTERCEPTION(service, id, num_params)
- 
- // When intercepting the EAT it is important that the patched version of the
- // function not call any functions imported from system libraries unless
- // |TargetServices::InitCalled()| returns true, because it is only then that
- // we are guaranteed that our IAT has been initialized.
- #define INTERCEPT_EAT(manager, dll, function, id, num_params) \
-   manager->AddToPatchedFunctions(dll, #function, sandbox::INTERCEPTION_EAT, \
--                                 MAKE_SERVICE_NAME(function), id)
-+                                 (void*)MAKE_SERVICE_NAME(function), id)
- #endif  // SANDBOX_EXPORTS
- 
- }  // namespace sandbox
- 
- #endif  // SANDBOX_SRC_INTERCEPTION_H_
--- a/security/sandbox/chromium-shim/patches/with_update/mingw_offsetof.patch
+++ b/security/sandbox/chromium-shim/patches/with_update/mingw_offsetof.patch
@@ -6,17 +6,17 @@
 # Parent  1987e062f1e5bf2998bb8e9d96353c5ccb0cc281
 Bug 1461421 Use OffsetOf to calculate the location of parameters_ rather than making assumptions about the parent class r?bobowen
 
 MozReview-Commit-ID: D7REZiAIMpN
 
 diff --git a/security/sandbox/chromium/sandbox/win/src/crosscall_params.h b/security/sandbox/chromium/sandbox/win/src/crosscall_params.h
 --- a/security/sandbox/chromium/sandbox/win/src/crosscall_params.h
 +++ b/security/sandbox/chromium/sandbox/win/src/crosscall_params.h
-@@ -55,16 +55,17 @@ union MultiType {
+@@ -61,16 +61,17 @@ union MultiType {
    ULONG_PTR ulong_ptr;
  };
  
  // Maximum number of IPC parameters currently supported.
  // To increase this value, we have to:
  //  - Add another Callback typedef to Dispatcher.
  //  - Add another case to the switch on SharedMemIPCServer::InvokeCallback.
  //  - Add another case to the switch in GetActualAndMaxBufferSize
@@ -30,38 +30,38 @@ diff --git a/security/sandbox/chromium/s
    uint32_t size_;
  };
 @@ -271,16 +272,18 @@ class ActualCallParams : public CrossCal
   protected:
    ActualCallParams() : CrossCallParams(0, NUMBER_PARAMS) { }
  
   private:
    ParamInfo param_info_[NUMBER_PARAMS + 1];
-   char parameters_[BLOCK_SIZE - sizeof(CrossCallParams)
-                    - sizeof(ParamInfo) * (NUMBER_PARAMS + 1)];
+   char parameters_[BLOCK_SIZE - sizeof(CrossCallParams) -
+                    sizeof(ParamInfo) * (NUMBER_PARAMS + 1)];
    DISALLOW_COPY_AND_ASSIGN(ActualCallParams);
 +
 +  friend uint32_t GetMinDeclaredActualCallParamsSize(uint32_t param_count);
  };
  
  static_assert(sizeof(ActualCallParams<1, 1024>) == 1024, "bad size buffer");
  static_assert(sizeof(ActualCallParams<2, 1024>) == 1024, "bad size buffer");
  static_assert(sizeof(ActualCallParams<3, 1024>) == 1024, "bad size buffer");
  
  }  // namespace sandbox
  
 diff --git a/security/sandbox/chromium/sandbox/win/src/crosscall_server.cc b/security/sandbox/chromium/sandbox/win/src/crosscall_server.cc
 --- a/security/sandbox/chromium/sandbox/win/src/crosscall_server.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/crosscall_server.cc
-@@ -22,30 +22,31 @@ namespace {
+@@ -28,30 +28,31 @@ namespace {
  
  // The buffer for a message must match the max channel size.
  const size_t kMaxBufferSize = sandbox::kIPCChannelSize;
  
- }
+ }  // namespace
  
  namespace sandbox {
  
 +// The template types are used to calculate the maximum expected size.
 +typedef ActualCallParams<0, kMaxBufferSize> ActualCP0;
 +typedef ActualCallParams<1, kMaxBufferSize> ActualCP1;
 +typedef ActualCallParams<2, kMaxBufferSize> ActualCP2;
 +typedef ActualCallParams<3, kMaxBufferSize> ActualCP3;
@@ -89,17 +89,17 @@ diff --git a/security/sandbox/chromium/s
    // Retrieve the actual size and the maximum size of the params buffer.
    switch (param_count) {
      case 0:
        return 0;
      case 1:
        return reinterpret_cast<ActualCP1*>(buffer_base)->GetSize();
      case 2:
        return reinterpret_cast<ActualCP2*>(buffer_base)->GetSize();
-@@ -63,16 +64,45 @@ uint32_t GetActualBufferSize(uint32_t pa
+@@ -69,16 +70,45 @@ uint32_t GetActualBufferSize(uint32_t pa
        return reinterpret_cast<ActualCP8*>(buffer_base)->GetSize();
      case 9:
        return reinterpret_cast<ActualCP9*>(buffer_base)->GetSize();
      default:
        return 0;
    }
  }
  
@@ -135,48 +135,48 @@ diff --git a/security/sandbox/chromium/s
  // Verifies that the declared sizes of an IPC buffer are within range.
  bool IsSizeWithinRange(uint32_t buffer_size,
                         uint32_t min_declared_size,
                         uint32_t declared_size) {
    if ((buffer_size < min_declared_size) ||
        (sizeof(CrossCallParamsEx) > min_declared_size)) {
      // Minimal computed size bigger than existing buffer or param_count
      // integer overflow.
-@@ -132,18 +162,17 @@ CrossCallParamsEx* CrossCallParamsEx::Cr
+@@ -133,18 +163,17 @@ CrossCallParamsEx* CrossCallParamsEx::Cr
    // will catch memory access violations so we don't crash.
    __try {
      CrossCallParams* call_params =
          reinterpret_cast<CrossCallParams*>(buffer_base);
  
      // Check against the minimum size given the number of stated params
      // if too small we bail out.
      param_count = call_params->GetParamsCount();
--    min_declared_size = sizeof(CrossCallParams) +
--                        ((param_count + 1) * sizeof(ParamInfo));
+-    min_declared_size =
+-        sizeof(CrossCallParams) + ((param_count + 1) * sizeof(ParamInfo));
 +    min_declared_size = GetMinDeclaredActualCallParamsSize(param_count);
  
+     // Initial check for the buffer being big enough to determine the actual
+     // buffer size.
+     if (buffer_size < min_declared_size)
+       return nullptr;
+ 
      // Retrieve the declared size which if it fails returns 0.
      declared_size = GetActualBufferSize(param_count, buffer_base);
- 
-     if (!IsSizeWithinRange(buffer_size, min_declared_size, declared_size))
-       return NULL;
- 
-     // Now we copy the actual amount of the message.
-@@ -152,18 +181,17 @@ CrossCallParamsEx* CrossCallParamsEx::Cr
+@@ -158,18 +187,17 @@ CrossCallParamsEx* CrossCallParamsEx::Cr
      copied_params = reinterpret_cast<CrossCallParamsEx*>(backing_mem);
      memcpy(backing_mem, call_params, declared_size);
  
      // Avoid compiler optimizations across this point. Any value stored in
      // memory should be stored for real, and values previously read from memory
      // should be actually read.
-     _ReadWriteBarrier();
+     base::subtle::MemoryBarrier();
  
--    min_declared_size = sizeof(CrossCallParams) +
--                        ((param_count + 1) * sizeof(ParamInfo));
+-    min_declared_size =
+-        sizeof(CrossCallParams) + ((param_count + 1) * sizeof(ParamInfo));
 +    min_declared_size = GetMinDeclaredActualCallParamsSize(param_count);
  
      // Check that the copied buffer is still valid.
      if (copied_params->GetParamsCount() != param_count ||
          GetActualBufferSize(param_count, backing_mem) != declared_size ||
          !IsSizeWithinRange(buffer_size, min_declared_size, declared_size)) {
-       delete [] backing_mem;
-       return NULL;
+       delete[] backing_mem;
+       return nullptr;
      }
--- a/security/sandbox/chromium-shim/patches/with_update/mingw_operator_new.patch
+++ b/security/sandbox/chromium-shim/patches/with_update/mingw_operator_new.patch
@@ -6,21 +6,21 @@
 # Parent  a99512c712f6580537e3133e5fd1adc091583e95
 Bug 1230910 Declare operator new [](size_t, sandbox::AllocationType, void*)
 
 MozReview-Commit-ID: GCKj5Ao2Y2n
 
 diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.cc b/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.cc
 --- a/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.cc
-@@ -649,16 +649,21 @@ void* operator new(size_t size, sandbox:
+@@ -663,16 +663,21 @@ void* operator new(size_t size, sandbox:
  
-   // TODO: Returning NULL from operator new has undefined behavior, but
-   // the Allocate() functions called above can return NULL. Consider checking
-   // for NULL here and crashing or throwing.
+   // TODO: Returning nullptr from operator new has undefined behavior, but
+   // the Allocate() functions called above can return nullptr. Consider checking
+   // for nullptr here and crashing or throwing.
  
    return result;
  }
  
 +void* operator new [](size_t size, sandbox::AllocationType type,
 +		      void* near_to) {
 +  return operator new(size, type, near_to);
 +}
@@ -31,27 +31,28 @@ diff --git a/security/sandbox/chromium/s
      VERIFY(sandbox::g_nt.RtlFreeHeap(sandbox::g_heap, 0, memory));
    } else if (type == sandbox::NT_PAGE) {
      void* base = memory;
      SIZE_T size = 0;
      VERIFY_SUCCESS(sandbox::g_nt.FreeVirtualMemory(NtCurrentProcess, &base,
 diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.h b/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.h
 --- a/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.h
 +++ b/security/sandbox/chromium/sandbox/win/src/sandbox_nt_util.h
-@@ -11,16 +11,18 @@
- 
+@@ -13,16 +13,19 @@
  #include "base/macros.h"
  #include "sandbox/win/src/nt_internals.h"
  #include "sandbox/win/src/sandbox_nt_types.h"
  
  // Placement new and delete to be used from ntdll interception code.
- void* __cdecl operator new(size_t size, sandbox::AllocationType type,
-                            void* near_to = NULL);
-+void* __cdecl operator new[](size_t size, sandbox::AllocationType type,
-+			     void* near_to = NULL);
+ void* __cdecl operator new(size_t size,
+                            sandbox::AllocationType type,
+                            void* near_to = nullptr);
++void* __cdecl operator new[](size_t size,
++                             sandbox::AllocationType type,
++                             void* near_to = nullptr);
  void __cdecl operator delete(void* memory, sandbox::AllocationType type);
  // Add operator delete that matches the placement form of the operator new
  // above. This is required by compiler to generate code to call operator delete
  // in case the object's constructor throws an exception.
  // See http://msdn.microsoft.com/en-us/library/cxdxz3x6.aspx
- void __cdecl operator delete(void* memory, sandbox::AllocationType type,
+ void __cdecl operator delete(void* memory,
+                              sandbox::AllocationType type,
                               void* near_to);
- 
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/patches/with_update/mingw_undefine_MemoryBarrier.patch
@@ -0,0 +1,52 @@
+# HG changeset patch
+# User Bob Owen <bobowencode@gmail.com>
+# Date 1558340081 -3600
+#      Mon May 20 09:14:41 2019 +0100
+# Node ID ba49022852e0cd13ddb6afa501b61c1f603d60b7
+# Parent  672e222dce87dd64c3e2a1381d16aec71b21aef6
+Bug 1552160: always undefine MemoryBarrier in Windows sandbox on MinGW.
+
+diff --git a/security/sandbox/chromium/base/atomicops.h b/security/sandbox/chromium/base/atomicops.h
+--- a/security/sandbox/chromium/base/atomicops.h
++++ b/security/sandbox/chromium/base/atomicops.h
+@@ -34,17 +34,17 @@
+ // identify the STL implementation.
+ // - libc++: captures __config for _LIBCPP_VERSION
+ // - libstdc++: captures bits/c++config.h for __GLIBCXX__
+ #include <cstddef>
+ 
+ #include "base/base_export.h"
+ #include "build/build_config.h"
+ 
+-#if defined(OS_WIN) && defined(ARCH_CPU_64_BITS)
++#if defined(OS_WIN) && (defined(ARCH_CPU_64_BITS) || defined(__MINGW32__))
+ // windows.h #defines this (only on x64). This causes problems because the
+ // public API also uses MemoryBarrier at the public name for this fence. So, on
+ // X64, undef it, and call its documented
+ // (http://msdn.microsoft.com/en-us/library/windows/desktop/ms684208.aspx)
+ // implementation directly.
+ #undef MemoryBarrier
+ #endif
+ 
+diff --git a/security/sandbox/chromium/base/atomicops_internals_x86_msvc.h b/security/sandbox/chromium/base/atomicops_internals_x86_msvc.h
+--- a/security/sandbox/chromium/base/atomicops_internals_x86_msvc.h
++++ b/security/sandbox/chromium/base/atomicops_internals_x86_msvc.h
+@@ -9,17 +9,17 @@
+ 
+ #include "base/win/windows_types.h"
+ 
+ #include <intrin.h>
+ 
+ #include "base/macros.h"
+ #include "build/build_config.h"
+ 
+-#if defined(ARCH_CPU_64_BITS)
++#if defined(ARCH_CPU_64_BITS) || defined(__MINGW32__)
+ // windows.h #defines this (only on x64). This causes problems because the
+ // public API also uses MemoryBarrier at the public name for this fence. So, on
+ // X64, undef it, and call its documented
+ // (http://msdn.microsoft.com/en-us/library/windows/desktop/ms684208.aspx)
+ // implementation directly.
+ #undef MemoryBarrier
+ #endif
+ 
--- a/security/sandbox/chromium-shim/patches/with_update/patch_order.txt
+++ b/security/sandbox/chromium-shim/patches/with_update/patch_order.txt
@@ -1,24 +1,25 @@
-apply_upstream_alternate_desktop_fix.patch
 update_chromium_linux_x86_syscalls.patch
 revert_remove_AddTargetPeer.patch
 revert_remove_BrokerDuplicateHandle.patch
 ifdef_out_ApplyMitigationsToCurrentThread.patch
 ifdef_out_FromStringInternal.patch
 add_option_to_not_use_restricting_sids.patch
 ifdef_out_SequenceChecker_code.patch
-revert_c++14_typename_alias_usage.patch
-revert_c++14_index_sequence_usage.patch
-fix_Wcomma_warning_in_time_cc.patch
 allow_read_only_all_paths_rule.patch
 revert_TargetNtSetInformationThread_change.patch
 mingw_base_win_get_caller.patch
-mingw_duplicate_instatinations.patch
 mingw_copy_s.patch
 mingw_operator_new.patch
 mingw_cast_getprocaddress.patch
 mingw_capitalization.patch
 mingw_disable_one_try.patch
-mingw_noexports_casts.patch
 mingw_offsetof.patch
-add_aarch64_windows_support.patch
+fix_incorrect_int_use_in_Kernel32BaseVersion.patch
+revert_removal_of_AlterEnvironment_on_Windows.patch
+allow_env_changes.patch
+ifdef_out_AppContainerProfileBase_testing_functions.patch
+mingw_missing_windows_types_defines.patch
+mingw_undefine_MemoryBarrier.patch
+add_return_in_QueryCancellationTraitsForNonCancellables_to_satisfy_build.patch
+include_atomic_header_in_platform_thread.patch
 aarch64_control_flow_guard.patch
--- a/security/sandbox/chromium-shim/patches/with_update/revert_TargetNtSetInformationThread_change.patch
+++ b/security/sandbox/chromium-shim/patches/with_update/revert_TargetNtSetInformationThread_change.patch
@@ -4,19 +4,19 @@
 #      Tue Nov 07 12:44:22 2017 +0000
 # Node ID 5b2b8b6c509a1025ef6d6ba208b093d4c4359186
 # Parent  2c3a28eab0bfcaa5a14771454f83703ae938da6c
 Revert commit f7540af7428f4b146136ec19b781886693f8c03f changes to policy_target.cc for causing issues with CoInitializeSecurity. r=aklotz
 
 diff --git a/security/sandbox/chromium/sandbox/win/src/policy_target.cc b/security/sandbox/chromium/sandbox/win/src/policy_target.cc
 --- a/security/sandbox/chromium/sandbox/win/src/policy_target.cc
 +++ b/security/sandbox/chromium/sandbox/win/src/policy_target.cc
-@@ -76,16 +76,26 @@ NTSTATUS WINAPI TargetNtSetInformationTh
-     NtSetInformationThreadFunction orig_SetInformationThread, HANDLE thread,
-     NT_THREAD_INFORMATION_CLASS thread_info_class, PVOID thread_information,
+@@ -78,16 +78,26 @@ NTSTATUS WINAPI TargetNtSetInformationTh
+     NT_THREAD_INFORMATION_CLASS thread_info_class,
+     PVOID thread_information,
      ULONG thread_information_bytes) {
    do {
      if (SandboxFactory::GetTargetServices()->GetState()->RevertedToSelf())
        break;
      if (ThreadImpersonationToken != thread_info_class)
        break;
 +    if (!thread_information)
 +      break;
@@ -27,12 +27,13 @@ diff --git a/security/sandbox/chromium/s
 +    NTSTATUS ret = CopyData(&token, thread_information, sizeof(token));
 +    if (!NT_SUCCESS(ret) || NULL != token)
 +      break;
 +
      // This is a revert to self.
      return STATUS_SUCCESS;
    } while (false);
  
-   return orig_SetInformationThread(thread, thread_info_class,
-                                    thread_information,
-                                    thread_information_bytes);
+   return orig_SetInformationThread(
+       thread, thread_info_class, thread_information, thread_information_bytes);
  }
+ 
+ // Hooks NtOpenThreadToken to force the open_as_self parameter to be set to
deleted file mode 100644
--- a/security/sandbox/chromium-shim/patches/with_update/revert_c++14_index_sequence_usage.patch
+++ /dev/null
@@ -1,302 +0,0 @@
-# HG changeset patch
-# User Bob Owen <bobowencode@gmail.com>
-# Date 1509027043 -3600
-#      Thu Oct 26 15:10:43 2017 +0100
-# Node ID 5d15fb26a11152cdd914d6c5b774a3887bcfd5c3
-# Parent  67700f068215bedeadef23539fb72b951b4b0c28
-Revert usage of c++14 std::index_sequence. r=jld
-
-This basically reverts chromium commit 84956fa86786f73fa41ebf99e2f6b8d549688c91.
-
-diff --git a/security/sandbox/chromium/base/bind.h b/security/sandbox/chromium/base/bind.h
---- a/security/sandbox/chromium/base/bind.h
-+++ b/security/sandbox/chromium/base/bind.h
-@@ -1,17 +1,15 @@
- // 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 <utility>
--
- #include "base/bind_internal.h"
- 
- // -----------------------------------------------------------------------------
- // Usage documentation
- // -----------------------------------------------------------------------------
- //
- // See //docs/callback.md for documentation.
- //
-@@ -79,17 +77,17 @@ template <typename Index,
-           typename UnwrappedTypeList,
-           typename ParamsList>
- struct AssertBindArgsValidity;
- 
- template <size_t... Ns,
-           typename... Args,
-           typename... Unwrapped,
-           typename... Params>
--struct AssertBindArgsValidity<std::index_sequence<Ns...>,
-+struct AssertBindArgsValidity<IndexSequence<Ns...>,
-                               TypeList<Args...>,
-                               TypeList<Unwrapped...>,
-                               TypeList<Params...>>
-     : AssertConstructible<Ns, Args, typename std::decay<Args>::type, Unwrapped, Params>... {
-   static constexpr bool ok = true;
- };
- 
- // The implementation of TransformToUnwrappedType below.
-@@ -166,17 +164,17 @@ BindOnce(Functor&& functor, Args&&... ar
-   using Helper = internal::BindTypeHelper<Functor, Args...>;
-   using FunctorTraits = typename Helper::FunctorTraits;
-   using BoundArgsList = typename Helper::BoundArgsList;
-   using UnwrappedArgsList =
-       internal::MakeUnwrappedTypeList<true, FunctorTraits::is_method,
-                                       Args&&...>;
-   using BoundParamsList = typename Helper::BoundParamsList;
-   static_assert(internal::AssertBindArgsValidity<
--                    std::make_index_sequence<Helper::num_bounds>, BoundArgsList,
-+                    MakeIndexSequence<Helper::num_bounds>, BoundArgsList,
-                     UnwrappedArgsList, BoundParamsList>::ok,
-                 "The bound args need to be convertible to the target params.");
- 
-   using BindState = internal::MakeBindStateType<Functor, Args...>;
-   using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
-   using Invoker = internal::Invoker<BindState, UnboundRunType>;
-   using CallbackType = OnceCallback<UnboundRunType>;
- 
-@@ -207,17 +205,17 @@ BindRepeating(Functor&& functor, Args&&.
-   using Helper = internal::BindTypeHelper<Functor, Args...>;
-   using FunctorTraits = typename Helper::FunctorTraits;
-   using BoundArgsList = typename Helper::BoundArgsList;
-   using UnwrappedArgsList =
-       internal::MakeUnwrappedTypeList<false, FunctorTraits::is_method,
-                                       Args&&...>;
-   using BoundParamsList = typename Helper::BoundParamsList;
-   static_assert(internal::AssertBindArgsValidity<
--                    std::make_index_sequence<Helper::num_bounds>, BoundArgsList,
-+                    MakeIndexSequence<Helper::num_bounds>, BoundArgsList,
-                     UnwrappedArgsList, BoundParamsList>::ok,
-                 "The bound args need to be convertible to the target params.");
- 
-   using BindState = internal::MakeBindStateType<Functor, Args...>;
-   using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
-   using Invoker = internal::Invoker<BindState, UnboundRunType>;
-   using CallbackType = RepeatingCallback<UnboundRunType>;
- 
-diff --git a/security/sandbox/chromium/base/bind_internal.h b/security/sandbox/chromium/base/bind_internal.h
---- a/security/sandbox/chromium/base/bind_internal.h
-+++ b/security/sandbox/chromium/base/bind_internal.h
-@@ -2,24 +2,25 @@
- // 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 <utility>
- 
- #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"
- 
- namespace base {
- namespace internal {
- 
- // See base/callback.h for user documentation.
- //
- //
-@@ -313,37 +314,37 @@ struct Invoker<StorageType, R(UnboundArg
-     // 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_),
--                   std::make_index_sequence<num_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.
-     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_,
--                   std::make_index_sequence<num_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,
--                          std::index_sequence<indices...>,
-+                          IndexSequence<indices...>,
-                           UnboundArgs&&... unbound_args) {
-     static constexpr bool is_method = MakeFunctorTraits<Functor>::is_method;
- 
-     using DecayedArgsTuple = typename std::decay<BoundArgsTuple>::type;
-     static constexpr bool is_weak_call =
-         IsWeakMethod<is_method,
-                      typename std::tuple_element<
-                          indices,
-@@ -396,31 +397,31 @@ typename std::enable_if<!FunctorTraits<F
- IsNull(const Functor&) {
-   return false;
- }
- 
- // Used by ApplyCancellationTraits below.
- template <typename Functor, typename BoundArgsTuple, size_t... indices>
- bool ApplyCancellationTraitsImpl(const Functor& functor,
-                                  const BoundArgsTuple& bound_args,
--                                 std::index_sequence<indices...>) {
-+                                 IndexSequence<indices...>) {
-   return CallbackCancellationTraits<Functor, BoundArgsTuple>::IsCancelled(
-       functor, std::get<indices>(bound_args)...);
- }
- 
- // Relays |base| to corresponding CallbackCancellationTraits<>::Run(). Returns
- // true if the callback |base| represents is canceled.
- template <typename BindStateType>
- bool ApplyCancellationTraits(const BindStateBase* base) {
-   const BindStateType* storage = static_cast<const BindStateType*>(base);
-   static constexpr size_t num_bound_args =
-       std::tuple_size<decltype(storage->bound_args_)>::value;
-   return ApplyCancellationTraitsImpl(
-       storage->functor_, storage->bound_args_,
--      std::make_index_sequence<num_bound_args>());
-+      MakeIndexSequence<num_bound_args>());
- };
- 
- // BindState<>
- //
- // This stores all the state passed into Bind().
- template <typename Functor, typename... BoundArgs>
- struct BindState final : BindStateBase {
-   using IsCancellable = std::integral_constant<
-diff --git a/security/sandbox/chromium/base/tuple.h b/security/sandbox/chromium/base/tuple.h
---- a/security/sandbox/chromium/base/tuple.h
-+++ b/security/sandbox/chromium/base/tuple.h
-@@ -22,24 +22,45 @@
- //   DispatchToMethod(&foo, &Foo::SomeMeth, std::make_tuple(1, 2, 3));
- //   // foo->SomeMeth(1, 2, 3);
- 
- #ifndef BASE_TUPLE_H_
- #define BASE_TUPLE_H_
- 
- #include <stddef.h>
- #include <tuple>
--#include <utility>
- 
- #include "build/build_config.h"
- 
- namespace base {
- 
-+// Index sequences
-+//
-+// Minimal clone of the similarly-named C++14 functionality.
-+
-+template <size_t...>
-+struct IndexSequence {};
-+
-+template <size_t... Ns>
-+struct MakeIndexSequenceImpl;
-+
-+template <size_t... Ns>
-+struct MakeIndexSequenceImpl<0, Ns...> {
-+  using Type = IndexSequence<Ns...>;
-+};
-+
-+template <size_t N, size_t... Ns>
-+struct MakeIndexSequenceImpl<N, Ns...>
-+    : MakeIndexSequenceImpl<N - 1, N - 1, Ns...> {};
-+
-+template <size_t N>
-+using MakeIndexSequence = typename MakeIndexSequenceImpl<N>::Type;
-+
- template <typename T>
--using MakeIndexSequenceForTuple = std::make_index_sequence<
-+using MakeIndexSequenceForTuple = MakeIndexSequence<
-     std::tuple_size<typename std::decay<T>::type>::value>;
- 
- // Dispatchers ----------------------------------------------------------------
- //
- // Helper functions that call the given method on an object, with the unpacked
- // tuple arguments.  Notice that they all have the same number of arguments,
- // so you need only write:
- //   DispatchToMethod(object, &Object::method, args);
-@@ -47,34 +68,34 @@ using MakeIndexSequenceForTuple = std::m
- // what type |args| is.
- 
- // Non-Static Dispatchers with no out params.
- 
- template <typename ObjT, typename Method, typename Tuple, size_t... Ns>
- inline void DispatchToMethodImpl(const ObjT& obj,
-                                  Method method,
-                                  Tuple&& args,
--                                 std::index_sequence<Ns...>) {
-+                                 IndexSequence<Ns...>) {
-   (obj->*method)(std::get<Ns>(std::forward<Tuple>(args))...);
- }
- 
- template <typename ObjT, typename Method, typename Tuple>
- inline void DispatchToMethod(const ObjT& obj,
-                              Method method,
-                              Tuple&& args) {
-   DispatchToMethodImpl(obj, method, std::forward<Tuple>(args),
-                        MakeIndexSequenceForTuple<Tuple>());
- }
- 
- // Static Dispatchers with no out params.
- 
- template <typename Function, typename Tuple, size_t... Ns>
- inline void DispatchToFunctionImpl(Function function,
-                                    Tuple&& args,
--                                   std::index_sequence<Ns...>) {
-+                                   IndexSequence<Ns...>) {
-   (*function)(std::get<Ns>(std::forward<Tuple>(args))...);
- }
- 
- template <typename Function, typename Tuple>
- inline void DispatchToFunction(Function function, Tuple&& args) {
-   DispatchToFunctionImpl(function, std::forward<Tuple>(args),
-                          MakeIndexSequenceForTuple<Tuple>());
- }
-@@ -86,18 +107,18 @@ template <typename ObjT,
-           typename InTuple,
-           typename OutTuple,
-           size_t... InNs,
-           size_t... OutNs>
- inline void DispatchToMethodImpl(const ObjT& obj,
-                                  Method method,
-                                  InTuple&& in,
-                                  OutTuple* out,
--                                 std::index_sequence<InNs...>,
--                                 std::index_sequence<OutNs...>) {
-+                                 IndexSequence<InNs...>,
-+                                 IndexSequence<OutNs...>) {
-   (obj->*method)(std::get<InNs>(std::forward<InTuple>(in))...,
-                  &std::get<OutNs>(*out)...);
- }
- 
- template <typename ObjT, typename Method, typename InTuple, typename OutTuple>
- inline void DispatchToMethod(const ObjT& obj,
-                              Method method,
-                              InTuple&& in,
deleted file mode 100644
--- a/security/sandbox/chromium-shim/patches/with_update/revert_c++14_typename_alias_usage.patch
+++ /dev/null
@@ -1,374 +0,0 @@
-# HG changeset patch
-# User Bob Owen <bobowencode@gmail.com>
-# Date 1509027043 -3600
-#      Thu Oct 26 15:10:43 2017 +0100
-# Node ID 0f50026844c4d27ccffb76033d0b6bdca3b99902
-# Parent  2c68d0d04b6d97a4509db8a66770f0430b4e2c15
-Revert usage of c++14 alias versions of standard type traits. r=jld
-
-This basically reverts chromium commit 35a31743fdc9006d5424fd2e1e15f6aba0a3c30c.
-
-diff --git a/security/sandbox/chromium/base/bind.h b/security/sandbox/chromium/base/bind.h
---- a/security/sandbox/chromium/base/bind.h
-+++ b/security/sandbox/chromium/base/bind.h
-@@ -48,28 +48,28 @@ struct AssertConstructible {
-   static constexpr bool param_is_forwardable =
-       std::is_constructible<Param, Unwrapped>::value;
-   // Unlike the check for binding into storage below, the check for
-   // forwardability drops the const qualifier for repeating callbacks. This is
-   // to try to catch instances where std::move()--which forwards as a const
-   // reference with repeating callbacks--is used instead of base::Passed().
-   static_assert(
-       param_is_forwardable ||
--          !std::is_constructible<Param, std::decay_t<Unwrapped>&&>::value,
-+          !std::is_constructible<Param, typename std::decay<Unwrapped>::type&&>::value,
-       "Bound argument |i| is move-only but will be forwarded by copy. "
-       "Ensure |Arg| is bound using base::Passed(), not std::move().");
-   static_assert(
-       param_is_forwardable,
-       "Bound argument |i| of type |Arg| cannot be forwarded as "
-       "|Unwrapped| to the bound functor, which declares it as |Param|.");
- 
-   static constexpr bool arg_is_storable =
-       std::is_constructible<Storage, Arg>::value;
-   static_assert(arg_is_storable ||
--                    !std::is_constructible<Storage, std::decay_t<Arg>&&>::value,
-+                    !std::is_constructible<Storage, typename std::decay<Arg>::type&&>::value,
-                 "Bound argument |i| is move-only but will be bound by copy. "
-                 "Ensure |Arg| is mutable and bound using std::move().");
-   static_assert(arg_is_storable,
-                 "Bound argument |i| of type |Arg| cannot be converted and "
-                 "bound as |Storage|.");
- };
- 
- // Takes three same-length TypeLists, and applies AssertConstructible for each
-@@ -83,34 +83,34 @@ struct AssertBindArgsValidity;
- template <size_t... Ns,
-           typename... Args,
-           typename... Unwrapped,
-           typename... Params>
- struct AssertBindArgsValidity<std::index_sequence<Ns...>,
-                               TypeList<Args...>,
-                               TypeList<Unwrapped...>,
-                               TypeList<Params...>>
--    : AssertConstructible<Ns, Args, std::decay_t<Args>, Unwrapped, Params>... {
-+    : AssertConstructible<Ns, Args, typename std::decay<Args>::type, Unwrapped, Params>... {
-   static constexpr bool ok = true;
- };
- 
- // The implementation of TransformToUnwrappedType below.
- template <bool is_once, typename T>
- struct TransformToUnwrappedTypeImpl;
- 
- template <typename T>
- struct TransformToUnwrappedTypeImpl<true, T> {
--  using StoredType = std::decay_t<T>;
-+  using StoredType = typename std::decay<T>::type;
-   using ForwardType = StoredType&&;
-   using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
- };
- 
- template <typename T>
- struct TransformToUnwrappedTypeImpl<false, T> {
--  using StoredType = std::decay_t<T>;
-+  using StoredType = typename std::decay<T>::type;
-   using ForwardType = const StoredType&;
-   using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
- };
- 
- // Transform |T| into `Unwrapped` type, which is passed to the target function.
- // Example:
- //   In is_once == true case,
- //     `int&&` -> `int&&`,
-@@ -148,21 +148,22 @@ using MakeUnwrappedTypeList =
-     typename MakeUnwrappedTypeListImpl<is_once, is_method, Args...>::Type;
- 
- }  // namespace internal
- 
- // Bind as OnceCallback.
- template <typename Functor, typename... Args>
- inline OnceCallback<MakeUnboundRunType<Functor, Args...>>
- BindOnce(Functor&& functor, Args&&... args) {
--  static_assert(!internal::IsOnceCallback<std::decay_t<Functor>>() ||
--                    (std::is_rvalue_reference<Functor&&>() &&
--                     !std::is_const<std::remove_reference_t<Functor>>()),
--                "BindOnce requires non-const rvalue for OnceCallback binding."
--                " I.e.: base::BindOnce(std::move(callback)).");
-+  static_assert(
-+      !internal::IsOnceCallback<typename std::decay<Functor>::type>() ||
-+          (std::is_rvalue_reference<Functor&&>() &&
-+           !std::is_const<typename std::remove_reference<Functor>::type>()),
-+      "BindOnce requires non-const rvalue for OnceCallback binding."
-+      " I.e.: base::BindOnce(std::move(callback)).");
- 
-   // This block checks if each |args| matches to the corresponding params of the
-   // target function. This check does not affect the behavior of Bind, but its
-   // error message should be more readable.
-   using Helper = internal::BindTypeHelper<Functor, Args...>;
-   using FunctorTraits = typename Helper::FunctorTraits;
-   using BoundArgsList = typename Helper::BoundArgsList;
-   using UnwrappedArgsList =
-@@ -192,17 +193,17 @@ BindOnce(Functor&& functor, Args&&... ar
-       std::forward<Args>(args)...));
- }
- 
- // Bind as RepeatingCallback.
- template <typename Functor, typename... Args>
- inline RepeatingCallback<MakeUnboundRunType<Functor, Args...>>
- BindRepeating(Functor&& functor, Args&&... args) {
-   static_assert(
--      !internal::IsOnceCallback<std::decay_t<Functor>>(),
-+      !internal::IsOnceCallback<typename std::decay<Functor>::type>(),
-       "BindRepeating cannot bind OnceCallback. Use BindOnce with std::move().");
- 
-   // This block checks if each |args| matches to the corresponding params of the
-   // target function. This check does not affect the behavior of Bind, but its
-   // error message should be more readable.
-   using Helper = internal::BindTypeHelper<Functor, Args...>;
-   using FunctorTraits = typename Helper::FunctorTraits;
-   using BoundArgsList = typename Helper::BoundArgsList;
-diff --git a/security/sandbox/chromium/base/bind_helpers.h b/security/sandbox/chromium/base/bind_helpers.h
---- a/security/sandbox/chromium/base/bind_helpers.h
-+++ b/security/sandbox/chromium/base/bind_helpers.h
-@@ -277,17 +277,17 @@ class PassedWrapper {
-   }
- 
-  private:
-   mutable bool is_valid_;
-   mutable T scoper_;
- };
- 
- template <typename T>
--using Unwrapper = BindUnwrapTraits<std::decay_t<T>>;
-+using Unwrapper = BindUnwrapTraits<typename std::decay<T>::type>;
- 
- template <typename T>
- 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
-@@ -433,17 +433,17 @@ 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,
--          std::enable_if_t<!std::is_lvalue_reference<T>::value>* = nullptr>
-+          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>
- static inline internal::PassedWrapper<T> Passed(T* scoper) {
-   return internal::PassedWrapper<T>(std::move(*scoper));
- }
- 
-@@ -532,19 +532,19 @@ struct CallbackCancellationTraits {
-   static constexpr bool is_cancellable = false;
- };
- 
- // Specialization for method bound to weak pointer receiver.
- template <typename Functor, typename... BoundArgs>
- struct CallbackCancellationTraits<
-     Functor,
-     std::tuple<BoundArgs...>,
--    std::enable_if_t<
-+    typename std::enable_if<
-         internal::IsWeakMethod<internal::FunctorTraits<Functor>::is_method,
--                               BoundArgs...>::value>> {
-+                               BoundArgs...>::value>::type> {
-   static constexpr bool is_cancellable = true;
- 
-   template <typename Receiver, typename... Args>
-   static bool IsCancelled(const Functor&,
-                           const Receiver& receiver,
-                           const Args&...) {
-     return !receiver;
-   }
-diff --git a/security/sandbox/chromium/base/bind_internal.h b/security/sandbox/chromium/base/bind_internal.h
---- a/security/sandbox/chromium/base/bind_internal.h
-+++ b/security/sandbox/chromium/base/bind_internal.h
-@@ -93,19 +93,19 @@ struct IsConvertibleToRunType<Callable, 
- template <typename... Args>
- 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_t<NeedsScopedRefptrButGetsRawPtr<T>::value,
--                         std::true_type,
--                         HasRefCountedTypeAsRawPtr<Args...>> {};
-+    : std::conditional<NeedsScopedRefptrButGetsRawPtr<T>::value,
-+                       std::true_type,
-+                       HasRefCountedTypeAsRawPtr<Args...>>::type {};
- 
- // ForceVoidReturn<>
- //
- // Set of templates that support forcing the function return type to void.
- template <typename Sig>
- struct ForceVoidReturn;
- 
- template <typename R, typename... Args>
-@@ -119,18 +119,19 @@ struct ForceVoidReturn<R(Args...)> {
- template <typename Functor, typename SFINAE>
- 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,
--                     std::enable_if_t<IsConvertibleToRunType<Functor>::value>> {
-+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)...);
-@@ -251,17 +252,17 @@ struct FunctorTraits<RepeatingCallback<R
-   static R Invoke(CallbackType&& callback, RunArgs&&... args) {
-     DCHECK(!callback.is_null());
-     return std::forward<CallbackType>(callback).Run(
-         std::forward<RunArgs>(args)...);
-   }
- };
- 
- template <typename Functor>
--using MakeFunctorTraits = FunctorTraits<std::decay_t<Functor>>;
-+using MakeFunctorTraits = FunctorTraits<typename std::decay<Functor>::type>;
- 
- // InvokeHelper<>
- //
- // There are 2 logical InvokeHelper<> specializations: normal, WeakCalls.
- //
- // The normal type just calls the underlying runnable.
- //
- // WeakCalls need special syntax that is applied to the first argument to check
-@@ -336,20 +337,22 @@ struct Invoker<StorageType, R(UnboundArg
-  private:
-   template <typename Functor, typename BoundArgsTuple, size_t... indices>
-   static inline R RunImpl(Functor&& functor,
-                           BoundArgsTuple&& bound,
-                           std::index_sequence<indices...>,
-                           UnboundArgs&&... unbound_args) {
-     static constexpr bool is_method = MakeFunctorTraits<Functor>::is_method;
- 
--    using DecayedArgsTuple = std::decay_t<BoundArgsTuple>;
-+    using DecayedArgsTuple = typename std::decay<BoundArgsTuple>::type;
-     static constexpr bool is_weak_call =
-         IsWeakMethod<is_method,
--                     std::tuple_element_t<indices, DecayedArgsTuple>...>();
-+                     typename std::tuple_element<
-+                         indices,
-+                         DecayedArgsTuple>::type...>::value;
- 
-     return InvokeHelper<is_weak_call, R>::MakeItSo(
-         std::forward<Functor>(functor),
-         Unwrap(std::get<indices>(std::forward<BoundArgsTuple>(bound)))...,
-         std::forward<UnboundArgs>(unbound_args)...);
-   }
- };
- 
-@@ -378,24 +381,24 @@ struct BindTypeHelper {
-   using UnboundParamsList = DropTypeListItem<num_bounds, RunParamsList>;
- 
-   using BoundArgsList = TypeList<BoundArgs...>;
- 
-   using UnboundRunType = MakeFunctionType<ReturnType, UnboundParamsList>;
- };
- 
- template <typename Functor>
--std::enable_if_t<FunctorTraits<Functor>::is_nullable, bool> IsNull(
--    const Functor& functor) {
-+typename std::enable_if<FunctorTraits<Functor>::is_nullable, bool>::type
-+IsNull(const Functor& functor) {
-   return !functor;
- }
- 
- template <typename Functor>
--std::enable_if_t<!FunctorTraits<Functor>::is_nullable, bool> IsNull(
--    const Functor&) {
-+typename std::enable_if<!FunctorTraits<Functor>::is_nullable, bool>::type
-+IsNull(const Functor&) {
-   return false;
- }
- 
- // Used by ApplyCancellationTraits below.
- template <typename Functor, typename BoundArgsTuple, size_t... indices>
- bool ApplyCancellationTraitsImpl(const Functor& functor,
-                                  const BoundArgsTuple& bound_args,
-                                  std::index_sequence<indices...>) {
-@@ -474,43 +477,48 @@ struct BindState final : BindStateBase {
- };
- 
- // 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<std::decay_t<BoundArgs>...>::value,
-+  static_assert(!HasRefCountedTypeAsRawPtr<
-+                    typename std::decay<BoundArgs>::type...>::value,
-                 "A parameter is a refcounted type and needs scoped_refptr.");
--  using Type = BindState<std::decay_t<Functor>, std::decay_t<BoundArgs>...>;
-+  using Type = BindState<typename std::decay<Functor>::type,
-+                         typename std::decay<BoundArgs>::type...>;
- };
- 
- template <typename Functor>
- struct MakeBindStateTypeImpl<true, Functor> {
--  using Type = BindState<std::decay_t<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<std::remove_reference_t<Receiver>>::value,
--                "First bound argument to a method cannot be an array.");
--  static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<BoundArgs>...>::value,
-+  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<
-+                    typename std::decay<BoundArgs>::type...>::value,
-                 "A parameter is a refcounted type and needs scoped_refptr.");
- 
-  private:
--  using DecayedReceiver = std::decay_t<Receiver>;
-+  using DecayedReceiver = typename std::decay<Receiver>::type;
- 
-  public:
-   using Type = BindState<
--      std::decay_t<Functor>,
--      std::conditional_t<std::is_pointer<DecayedReceiver>::value,
--                         scoped_refptr<std::remove_pointer_t<DecayedReceiver>>,
--                         DecayedReceiver>,
--      std::decay_t<BoundArgs>...>;
-+      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<MakeFunctorTraits<Functor>::is_method,
-                                    Functor,
-                                    BoundArgs...>::Type;
- 
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium-shim/patches/with_update/revert_removal_of_AlterEnvironment_on_Windows.patch
@@ -0,0 +1,150 @@
+# HG changeset patch
+# User Bob Owen <bobowencode@gmail.com>
+# Date 1560256605 -3600
+#      Tue Jun 11 13:36:45 2019 +0100
+# Node ID 686d4b711b65b7cd8692e92e9a7ae152a942b69e
+# Parent  213d707af158b3d276c8cce56aba2e3c27abda82
+Bug 1552160: Revert removal of AlterEnvironment from chromium code on Windows. r=jld
+
+diff --git a/security/sandbox/chromium/base/environment.cc b/security/sandbox/chromium/base/environment.cc
+--- a/security/sandbox/chromium/base/environment.cc
++++ b/security/sandbox/chromium/base/environment.cc
+@@ -96,34 +96,32 @@ class EnvironmentImpl : public Environme
+     return !!SetEnvironmentVariable(UTF8ToWide(variable_name).c_str(), nullptr);
+ #elif defined(OS_POSIX) || defined(OS_FUCHSIA)
+     // On success, zero is returned.
+     return !unsetenv(variable_name.data());
+ #endif
+   }
+ };
+ 
+-#if defined(OS_POSIX) || defined(OS_FUCHSIA)
+ // Parses a null-terminated input string of an environment block. The key is
+ // placed into the given string, and the total length of the line, including
+ // the terminating null, is returned.
+ size_t ParseEnvLine(const NativeEnvironmentString::value_type* input,
+                     NativeEnvironmentString* key) {
+   // Skip to the equals or end of the string, this is the key.
+   size_t cur = 0;
+   while (input[cur] && input[cur] != '=')
+     cur++;
+   *key = NativeEnvironmentString(&input[0], cur);
+ 
+   // Now just skip to the end of the string.
+   while (input[cur])
+     cur++;
+   return cur + 1;
+ }
+-#endif
+ 
+ }  // namespace
+ 
+ namespace env_vars {
+ 
+ #if defined(OS_POSIX) || defined(OS_FUCHSIA)
+ // On Posix systems, this variable contains the location of the user's home
+ // directory. (e.g, /home/username/).
+@@ -138,17 +136,57 @@ Environment::~Environment() = default;
+ std::unique_ptr<Environment> Environment::Create() {
+   return std::make_unique<EnvironmentImpl>();
+ }
+ 
+ bool Environment::HasVar(StringPiece variable_name) {
+   return GetVar(variable_name, nullptr);
+ }
+ 
+-#if defined(OS_POSIX) || defined(OS_FUCHSIA)
++#if defined(OS_WIN)
++
++string16 AlterEnvironment(const wchar_t* env,
++                          const EnvironmentMap& changes) {
++  string16 result;
++
++  // First copy all unmodified values to the output.
++  size_t cur_env = 0;
++  string16 key;
++  while (env[cur_env]) {
++    const wchar_t* line = &env[cur_env];
++    size_t line_length = ParseEnvLine(line, &key);
++
++    // Keep only values not specified in the change vector.
++    EnvironmentMap::const_iterator found_change = changes.find(key);
++    if (found_change == changes.end())
++      result.append(line, line_length);
++
++    cur_env += line_length;
++  }
++
++  // Now append all modified and new values.
++  for (EnvironmentMap::const_iterator i = changes.begin();
++       i != changes.end(); ++i) {
++    if (!i->second.empty()) {
++      result.append(i->first);
++      result.push_back('=');
++      result.append(i->second);
++      result.push_back(0);
++    }
++  }
++
++  // An additional null marks the end of the list. We always need a double-null
++  // in case nothing was added above.
++  if (result.empty())
++    result.push_back(0);
++  result.push_back(0);
++  return result;
++}
++
++#elif defined(OS_POSIX) || defined(OS_FUCHSIA)
+ 
+ std::unique_ptr<char* []> AlterEnvironment(const char* const* const env,
+                                            const EnvironmentMap& changes) {
+   std::string value_storage;  // Holds concatenated null-terminated strings.
+   std::vector<size_t> result_indices;  // Line indices into value_storage.
+ 
+   // First build up all of the unchanged environment strings. These are
+   // null-terminated of the form "key=value".
+diff --git a/security/sandbox/chromium/base/environment.h b/security/sandbox/chromium/base/environment.h
+--- a/security/sandbox/chromium/base/environment.h
++++ b/security/sandbox/chromium/base/environment.h
+@@ -48,27 +48,36 @@ class BASE_EXPORT Environment {
+ 
+ 
+ #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) || defined(OS_FUCHSIA)
+ 
+ typedef std::string 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.
++// 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,
--- a/security/sandbox/chromium-shim/patches/with_update/revert_remove_AddTargetPeer.patch
+++ b/security/sandbox/chromium-shim/patches/with_update/revert_remove_AddTargetPeer.patch
@@ -109,17 +109,17 @@ diff --git a/security/sandbox/chromium/s
      } else if (THREAD_CTRL_QUIT == key) {
        // The broker object is being destroyed so the thread needs to exit.
        return 0;
      } else {
        // We have not implemented more commands.
        NOTREACHED();
      }
    }
-@@ -460,26 +495,71 @@ ResultCode BrokerServicesBase::SpawnTarg
+@@ -460,25 +495,70 @@ ResultCode BrokerServicesBase::SpawnTarg
      // TODO(wfh): Find a way to make this have the correct lifetime.
      policy_base->AddRef();
  
      // We have to signal the event once here because the completion port will
      // never get a message that this target is being terminated thus we should
      // not block WaitForAllTargets until we have at least one target with job.
      if (child_process_ids_.empty())
        ::SetEvent(no_targets_.Get());
@@ -130,17 +130,16 @@ diff --git a/security/sandbox/chromium/s
 +    // targets for e.g. BrokerDuplicateHandle so track them as peer processes.
 +    AddTargetPeer(process_info.process_handle());
    }
  
    *target_info = process_info.Take();
    return result;
  }
  
- 
  ResultCode BrokerServicesBase::WaitForAllTargets() {
    ::WaitForSingleObject(no_targets_.Get(), INFINITE);
    return SBOX_ALL_OK;
  }
  
  bool BrokerServicesBase::IsActiveTarget(DWORD process_id) {
    AutoLock lock(&lock_);
 -  return child_process_ids_.find(process_id) != child_process_ids_.end();
@@ -280,16 +279,16 @@ diff --git a/security/sandbox/chromium/s
 +
 +  // Adds an unsandboxed process as a peer for policy decisions (e.g.
 +  // HANDLES_DUP_ANY policy).
 +  // Returns:
 +  //   ALL_OK if successful. All other return values imply failure.
 +  //   If the return is ERROR_GENERIC, you can call ::GetLastError() to get
 +  //   more information.
 +  virtual ResultCode AddTargetPeer(HANDLE peer_process) = 0;
+ 
+  protected:
+   ~BrokerServices() {}
  };
  
  // TargetServices models the current process from the perspective
  // of a target process. To obtain a pointer to it use
  // Sandbox::GetTargetServices(). Note that this call returns a non-null
- // pointer only if this process is in fact a target. A process is a target
- // only if the process was spawned by a call to BrokerServices::SpawnTarget().
- //
--- a/security/sandbox/chromium-shim/patches/with_update/revert_remove_BrokerDuplicateHandle.patch
+++ b/security/sandbox/chromium-shim/patches/with_update/revert_remove_BrokerDuplicateHandle.patch
@@ -509,17 +509,17 @@ diff --git a/security/sandbox/chromium/s
    IPC_CREATETHREAD_TAG,
    IPC_USER_ENUMDISPLAYMONITORS_TAG,
    IPC_USER_ENUMDISPLAYDEVICES_TAG,
    IPC_USER_GETMONITORINFO_TAG,
    IPC_GDI_CREATEOPMPROTECTEDOUTPUTS_TAG,
 diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox.h b/security/sandbox/chromium/sandbox/win/src/sandbox.h
 --- a/security/sandbox/chromium/sandbox/win/src/sandbox.h
 +++ b/security/sandbox/chromium/sandbox/win/src/sandbox.h
-@@ -136,14 +136,28 @@ class TargetServices {
+@@ -136,16 +136,30 @@ class TargetServices {
    // processing any untrusted data or running third-party code. If this call
    // fails the current process could be terminated immediately.
    virtual void LowerToken() = 0;
  
    // Returns the ProcessState object. Through that object it's possible to have
    // information about the current state of the process, such as whether
    // LowerToken has been called or not.
    virtual ProcessState* GetState() = 0;
@@ -532,36 +532,38 @@ diff --git a/security/sandbox/chromium/s
 +  //   ALL_OK if successful. All other return values imply failure.
 +  //   If the return is ERROR_GENERIC, you can call ::GetLastError() to get
 +  //   more information.
 +  virtual ResultCode DuplicateHandle(HANDLE source_handle,
 +                                     DWORD target_process_id,
 +                                     HANDLE* target_handle,
 +                                     DWORD desired_access,
 +                                     DWORD options) = 0;
+ 
+  protected:
+   ~TargetServices() {}
  };
  
  }  // namespace sandbox
  
  
- #endif  // SANDBOX_WIN_SRC_SANDBOX_H_
 diff --git a/security/sandbox/chromium/sandbox/win/src/sandbox_policy.h b/security/sandbox/chromium/sandbox/win/src/sandbox_policy.h
 --- a/security/sandbox/chromium/sandbox/win/src/sandbox_policy.h
 +++ b/security/sandbox/chromium/sandbox/win/src/sandbox_policy.h
-@@ -21,27 +21,31 @@ class TargetPolicy {
+@@ -24,27 +24,31 @@ class TargetPolicy {
    // exactly like the CreateProcess API does. See the comment at the top of
    // process_thread_dispatcher.cc for more details.
    enum SubSystem {
-     SUBSYS_FILES,             // Creation and opening of files and pipes.
-     SUBSYS_NAMED_PIPES,       // Creation of named pipes.
-     SUBSYS_PROCESS,           // Creation of child processes.
-     SUBSYS_REGISTRY,          // Creation and opening of registry keys.
-     SUBSYS_SYNC,              // Creation of named sync objects.
-+    SUBSYS_HANDLES,           // Duplication of handles to other processes.
-     SUBSYS_WIN32K_LOCKDOWN    // Win32K Lockdown related policy.
+     SUBSYS_FILES,           // Creation and opening of files and pipes.
+     SUBSYS_NAMED_PIPES,     // Creation of named pipes.
+     SUBSYS_PROCESS,         // Creation of child processes.
+     SUBSYS_REGISTRY,        // Creation and opening of registry keys.
+     SUBSYS_SYNC,            // Creation of named sync objects.
++    SUBSYS_HANDLES,         // Duplication of handles to other processes.
+     SUBSYS_WIN32K_LOCKDOWN  // Win32K Lockdown related policy.
    };
  
    // Allowable semantics when a rule is matched.
    enum Semantics {
      FILES_ALLOW_ANY,       // Allows open or create for any kind of access that
                             // the file system supports.
      FILES_ALLOW_READONLY,  // Allows open or create with read access only.
      FILES_ALLOW_QUERY,     // Allows access to query the attributes of a file.
--- a/security/sandbox/chromium/base/at_exit.cc
+++ b/security/sandbox/chromium/base/at_exit.cc
@@ -15,22 +15,21 @@
 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;
+static AtExitManager* g_top_manager = nullptr;
 
 static bool g_disable_managers = false;
 
-AtExitManager::AtExitManager()
-    : processing_callbacks_(false), next_manager_(g_top_manager) {
+AtExitManager::AtExitManager() : 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;
 }
 
@@ -55,55 +54,62 @@ 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_);
+#if DCHECK_IS_ON()
   DCHECK(!g_top_manager->processing_callbacks_);
+#endif
   g_top_manager->stack_.push(std::move(task));
 }
 
 // static
 void AtExitManager::ProcessCallbacksNow() {
   if (!g_top_manager) {
     NOTREACHED() << "Tried to ProcessCallbacksNow without an AtExitManager";
     return;
   }
 
   // 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;
+  base::stack<base::Closure> tasks;
   {
     AutoLock lock(g_top_manager->lock_);
     tasks.swap(g_top_manager->stack_);
+#if DCHECK_IS_ON()
     g_top_manager->processing_callbacks_ = true;
+#endif
   }
 
   // Relax the cross-thread access restriction to non-thread-safe RefCount.
   // It's safe since all other threads should be terminated at this point.
   ScopedAllowCrossThreadRefCountAccess allow_cross_thread_ref_count_access;
 
   while (!tasks.empty()) {
     base::Closure task = tasks.top();
     task.Run();
     tasks.pop();
   }
 
+#if DCHECK_IS_ON()
+  AutoLock lock(g_top_manager->lock_);
   // Expect that all callbacks have been run.
   DCHECK(g_top_manager->stack_.empty());
+  g_top_manager->processing_callbacks_ = false;
+#endif
 }
 
 void AtExitManager::DisableAllAtExitManagers() {
   AutoLock lock(g_top_manager->lock_);
   g_disable_managers = true;
 }
 
-AtExitManager::AtExitManager(bool shadow)
-    : processing_callbacks_(false), next_manager_(g_top_manager) {
+AtExitManager::AtExitManager(bool shadow) : 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
@@ -1,21 +1,21 @@
 // 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_AT_EXIT_H_
 #define BASE_AT_EXIT_H_
 
-#include <stack>
-
 #include "base/base_export.h"
 #include "base/callback.h"
+#include "base/containers/stack.h"
 #include "base/macros.h"
 #include "base/synchronization/lock.h"
+#include "base/thread_annotations.h"
 
 namespace base {
 
 // This class provides a facility similar to the CRT atexit(), except that
 // we control when the callbacks are executed. Under Windows for a DLL they
 // happen at a really bad time and under the loader lock. This facility is
 // mostly used by base::Singleton.
 //
@@ -57,19 +57,25 @@ class BASE_EXPORT AtExitManager {
   // This constructor will allow this instance of AtExitManager to be created
   // 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.
+
+  base::stack<base::Closure> stack_ GUARDED_BY(lock_);
+
+#if DCHECK_IS_ON()
+  bool processing_callbacks_ GUARDED_BY(lock_) = false;
+#endif
+
+  // Stack of managers to allow shadowing.
+  AtExitManager* const next_manager_;
 
   DISALLOW_COPY_AND_ASSIGN(AtExitManager);
 };
 
 #if defined(UNIT_TEST)
 class ShadowingAtExitManager : public AtExitManager {
  public:
   ShadowingAtExitManager() : AtExitManager(true) {}
--- a/security/sandbox/chromium/base/atomic_ref_count.h
+++ b/security/sandbox/chromium/base/atomic_ref_count.h
@@ -14,21 +14,23 @@ namespace base {
 
 class AtomicRefCount {
  public:
   constexpr AtomicRefCount() : ref_count_(0) {}
   explicit constexpr AtomicRefCount(int initial_value)
       : ref_count_(initial_value) {}
 
   // Increment a reference count.
-  void Increment() { Increment(1); }
+  // Returns the previous value of the count.
+  int Increment() { return Increment(1); }
 
   // Increment a reference count by "increment", which must exceed 0.
-  void Increment(int increment) {
-    ref_count_.fetch_add(increment, std::memory_order_relaxed);
+  // Returns the previous value of the count.
+  int Increment(int increment) {
+    return ref_count_.fetch_add(increment, std::memory_order_relaxed);
   }
 
   // Decrement a reference count, and return whether the result is non-zero.
   // Insert barriers to ensure that state written before the reference count
   // became zero will be visible to a thread that has just made the count zero.
   bool Decrement() {
     // TODO(jbroman): Technically this doesn't need to be an acquire operation
     // unless the result is 1 (i.e., the ref count did indeed reach zero).
--- a/security/sandbox/chromium/base/atomic_sequence_num.h
+++ b/security/sandbox/chromium/base/atomic_sequence_num.h
@@ -11,17 +11,17 @@
 
 namespace base {
 
 // AtomicSequenceNumber is a thread safe increasing sequence number generator.
 // Its constructor doesn't emit a static initializer, so it's safe to use as a
 // global variable or static member.
 class AtomicSequenceNumber {
  public:
-  constexpr AtomicSequenceNumber() {}
+  constexpr AtomicSequenceNumber() = default;
 
   // Returns an increasing sequence number starts from 0 for each call.
   // This function can be called from any thread without data race.
   inline int GetNext() { return seq_.fetch_add(1, std::memory_order_relaxed); }
 
  private:
   std::atomic_int seq_{0};
 
--- a/security/sandbox/chromium/base/atomicops.h
+++ b/security/sandbox/chromium/base/atomicops.h
@@ -34,17 +34,17 @@
 // identify the STL implementation.
 // - libc++: captures __config for _LIBCPP_VERSION
 // - libstdc++: captures bits/c++config.h for __GLIBCXX__
 #include <cstddef>
 
 #include "base/base_export.h"
 #include "build/build_config.h"
 
-#if defined(OS_WIN) && defined(ARCH_CPU_64_BITS)
+#if defined(OS_WIN) && (defined(ARCH_CPU_64_BITS) || defined(__MINGW32__))
 // windows.h #defines this (only on x64). This causes problems because the
 // public API also uses MemoryBarrier at the public name for this fence. So, on
 // X64, undef it, and call its documented
 // (http://msdn.microsoft.com/en-us/library/windows/desktop/ms684208.aspx)
 // implementation directly.
 #undef MemoryBarrier
 #endif
 
@@ -140,18 +140,18 @@ Atomic64 NoBarrier_Load(volatile const A
 Atomic64 Acquire_Load(volatile const Atomic64* ptr);
 Atomic64 Release_Load(volatile const Atomic64* ptr);
 #endif  // ARCH_CPU_64_BITS
 
 }  // namespace subtle
 }  // namespace base
 
 #if defined(OS_WIN) && defined(ARCH_CPU_X86_FAMILY)
-// TODO(jfb): The MSVC header includes windows.h, which other files end up
-//            relying on. Fix this as part of crbug.com/559247.
+// TODO(jfb): Try to use base/atomicops_internals_portable.h everywhere.
+// https://crbug.com/559247.
 #  include "base/atomicops_internals_x86_msvc.h"
 #else
 #  include "base/atomicops_internals_portable.h"
 #endif
 
 // On some platforms we need additional declarations to make
 // AtomicWord compatible with our other Atomic* types.
 #if defined(OS_MACOSX) || defined(OS_OPENBSD)
--- a/security/sandbox/chromium/base/atomicops_internals_x86_msvc.h
+++ b/security/sandbox/chromium/base/atomicops_internals_x86_msvc.h
@@ -2,24 +2,24 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
 // This file is an internal atomic implementation, use base/atomicops.h instead.
 
 #ifndef BASE_ATOMICOPS_INTERNALS_X86_MSVC_H_
 #define BASE_ATOMICOPS_INTERNALS_X86_MSVC_H_
 
-#include <windows.h>
+#include "base/win/windows_types.h"
 
 #include <intrin.h>
 
 #include "base/macros.h"
 #include "build/build_config.h"
 
-#if defined(ARCH_CPU_64_BITS)
+#if defined(ARCH_CPU_64_BITS) || defined(__MINGW32__)
 // windows.h #defines this (only on x64). This causes problems because the
 // public API also uses MemoryBarrier at the public name for this fence. So, on
 // X64, undef it, and call its documented
 // (http://msdn.microsoft.com/en-us/library/windows/desktop/ms684208.aspx)
 // implementation directly.
 #undef MemoryBarrier
 #endif
 
@@ -56,18 +56,20 @@ inline Atomic32 NoBarrier_AtomicIncremen
   return Barrier_AtomicIncrement(ptr, increment);
 }
 
 inline void MemoryBarrier() {
 #if defined(ARCH_CPU_64_BITS)
   // See #undef and note at the top of this file.
   __faststorefence();
 #else
-  // We use MemoryBarrier from WinNT.h
-  ::MemoryBarrier();
+  // We use the implementation of MemoryBarrier from WinNT.h
+  LONG barrier;
+
+  _InterlockedOr(&barrier, 0);
 #endif
 }
 
 inline Atomic32 Acquire_CompareAndSwap(volatile Atomic32* ptr,
                                        Atomic32 old_value,
                                        Atomic32 new_value) {
   return NoBarrier_CompareAndSwap(ptr, old_value, new_value);
 }
@@ -110,35 +112,35 @@ inline Atomic32 Release_Load(volatile co
 
 // 64-bit low-level operations on 64-bit platform.
 
 static_assert(sizeof(Atomic64) == sizeof(PVOID), "atomic word is atomic");
 
 inline Atomic64 NoBarrier_CompareAndSwap(volatile Atomic64* ptr,
                                          Atomic64 old_value,
                                          Atomic64 new_value) {
-  PVOID result = InterlockedCompareExchangePointer(
-    reinterpret_cast<volatile PVOID*>(ptr),
-    reinterpret_cast<PVOID>(new_value), reinterpret_cast<PVOID>(old_value));
+  PVOID result = _InterlockedCompareExchangePointer(
+      reinterpret_cast<volatile PVOID*>(ptr),
+      reinterpret_cast<PVOID>(new_value), reinterpret_cast<PVOID>(old_value));
   return reinterpret_cast<Atomic64>(result);
 }
 
 inline Atomic64 NoBarrier_AtomicExchange(volatile Atomic64* ptr,
                                          Atomic64 new_value) {
-  PVOID result = InterlockedExchangePointer(
-    reinterpret_cast<volatile PVOID*>(ptr),
-    reinterpret_cast<PVOID>(new_value));
+  PVOID result =
+      _InterlockedExchangePointer(reinterpret_cast<volatile PVOID*>(ptr),
+                                  reinterpret_cast<PVOID>(new_value));
   return reinterpret_cast<Atomic64>(result);
 }
 
 inline Atomic64 Barrier_AtomicIncrement(volatile Atomic64* ptr,
                                         Atomic64 increment) {
-  return InterlockedExchangeAdd64(
-      reinterpret_cast<volatile LONGLONG*>(ptr),
-      static_cast<LONGLONG>(increment)) + increment;
+  return _InterlockedExchangeAdd64(reinterpret_cast<volatile LONGLONG*>(ptr),
+                                   static_cast<LONGLONG>(increment)) +
+         increment;
 }
 
 inline Atomic64 NoBarrier_AtomicIncrement(volatile Atomic64* ptr,
                                           Atomic64 increment) {
   return Barrier_AtomicIncrement(ptr, increment);
 }
 
 inline void NoBarrier_Store(volatile Atomic64* ptr, Atomic64 value) {
--- a/security/sandbox/chromium/base/base_paths.h
+++ b/security/sandbox/chromium/base/base_paths.h
@@ -13,42 +13,43 @@
 #if defined(OS_WIN)
 #include "base/base_paths_win.h"
 #elif defined(OS_MACOSX)
 #include "base/base_paths_mac.h"
 #elif defined(OS_ANDROID)
 #include "base/base_paths_android.h"
 #endif
 
-#if defined(OS_POSIX)
+#if defined(OS_POSIX) || defined(OS_FUCHSIA)
 #include "base/base_paths_posix.h"
 #endif
 
 namespace base {
 
 enum BasePathKey {
   PATH_START = 0,
 
   DIR_CURRENT,       // Current directory.
   DIR_EXE,           // Directory containing FILE_EXE.
   DIR_MODULE,        // Directory containing FILE_MODULE.
+  DIR_ASSETS,        // Directory that contains application assets.
   DIR_TEMP,          // Temporary directory.
   DIR_HOME,          // User's root home directory. On Windows this will look
                      // 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.
   DIR_USER_DESKTOP,  // The current user's Desktop.
 
-  DIR_TEST_DATA,     // Used only for testing.
+  DIR_TEST_DATA,  // Used only for testing.
 
   PATH_END
 };
 
 }  // namespace base
 
 #endif  // BASE_BASE_PATHS_H_
--- a/security/sandbox/chromium/base/base_switches.cc
+++ b/security/sandbox/chromium/base/base_switches.cc
@@ -2,42 +2,32 @@
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
 #include "base/base_switches.h"
 #include "build/build_config.h"
 
 namespace switches {
 
+// Delays execution of base::TaskPriority::BEST_EFFORT tasks until shutdown.
+const char kDisableBestEffortTasks[] = "disable-best-effort-tasks";
+
 // Disables the crash reporting.
 const char kDisableBreakpad[]               = "disable-breakpad";
 
+// Comma-separated list of feature names to disable. See also kEnableFeatures.
+const char kDisableFeatures[] = "disable-features";
+
 // Indicates that crash reporting should be enabled. On platforms where helper
 // processes cannot access to files needed to make this decision, this flag is
 // generated internally.
 const char kEnableCrashReporter[]           = "enable-crash-reporter";
 
-// Makes memory allocators keep track of their allocations and context, so a
-// detailed breakdown of memory usage can be presented in chrome://tracing when
-// the memory-infra category is enabled.
-const char kEnableHeapProfiling[]           = "enable-heap-profiling";
-
-// Report pseudo allocation traces. Pseudo traces are derived from currently
-// active trace events.
-const char kEnableHeapProfilingModePseudo[] = "";
-
-// Report native (walk the stack) allocation traces. By default pseudo stacks
-// derived from trace events are reported.
-const char kEnableHeapProfilingModeNative[] = "native";
-
-// Report per-task heap usage and churn in the task profiler.
-// Does not keep track of individual allocations unlike the default and native
-// mode. Keeps only track of summarized churn stats in the task profiler
-// (chrome://profiler).
-const char kEnableHeapProfilingTaskProfiler[] = "task-profiler";
+// Comma-separated list of feature names to enable. See also kDisableFeatures.
+const char kEnableFeatures[] = "enable-features";
 
 // 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.
@@ -86,39 +76,67 @@ const char kWaitForDebugger[]           
 // Sends trace events from these categories to a file.
 // --trace-to-file on its own sends to default categories.
 const char kTraceToFile[]                   = "trace-to-file";
 
 // Specifies the file name for --trace-to-file. If unspecified, it will
 // go to a default file name.
 const char kTraceToFileName[]               = "trace-to-file-name";
 
-// Configure whether chrome://profiler will contain timing information. This
-// option is enabled by default. A value of "0" will disable profiler timing,
-// while all other values will enable it.
-const char kProfilerTiming[]                = "profiler-timing";
-// Value of the --profiler-timing flag that will disable timing information for
-// chrome://profiler.
-const char kProfilerTimingDisabledValue[]   = "0";
+// Starts the sampling based profiler for the browser process at startup. This
+// will only work if chrome has been built with the gn arg enable_profiling =
+// true. The output will go to the value of kProfilingFile.
+const char kProfilingAtStart[] = "profiling-at-start";
 
 // 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";
 
+// Controls whether profile data is periodically flushed to a file. Normally
+// the data gets written on exit but cases exist where chromium doesn't exit
+// cleanly (especially when using single-process). A time in seconds can be
+// specified.
+const char kProfilingFlush[] = "profiling-flush";
+
 #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_LINUX) && !defined(OS_CHROMEOS)
+// The /dev/shm partition is too small in certain VM environments, causing
+// Chrome to fail or crash (see http://crbug.com/715363). Use this flag to
+// work-around this issue (a temporary directory will always be used to create
+// anonymous shared memory files).
+const char kDisableDevShmUsage[] = "disable-dev-shm-usage";
+#endif
+
 #if defined(OS_POSIX)
 // Used for turning on Breakpad crash reporting in a debug environment where
 // crash reporting is typically compiled but disabled.
 const char kEnableCrashReporterForTesting[] =
     "enable-crash-reporter-for-testing";
 #endif
 
+#if defined(OS_ANDROID)
+// Enables the reached code profiler that samples all threads in all processes
+// to determine which functions are almost never executed.
+const char kEnableReachedCodeProfiler[] = "enable-reached-code-profiler";
+
+// Specifies optimization of memory layout of the native library using the
+// orderfile symbols given in base/android/library_loader/anchor_functions.h,
+// via madvise and changing the library prefetch behavior.
+//
+// If this switch is not specified, an optimization may be done depending on a
+// synthetic trial. If specified, its values may be 'on' or 'off'. These
+// override the synthetic trial.
+//
+// This flag is only used on architectures with SUPPORTS_CODE_ORDERING defined.
+const char kOrderfileMemoryOptimization[] = "orderfile-memory-optimization";
+#endif
+
 }  // namespace switches
--- a/security/sandbox/chromium/base/base_switches.h
+++ b/security/sandbox/chromium/base/base_switches.h
@@ -6,41 +6,49 @@
 
 #ifndef BASE_BASE_SWITCHES_H_
 #define BASE_BASE_SWITCHES_H_
 
 #include "build/build_config.h"
 
 namespace switches {
 
+extern const char kDisableBestEffortTasks[];
 extern const char kDisableBreakpad[];
+extern const char kDisableFeatures[];
 extern const char kDisableLowEndDeviceMode[];
 extern const char kEnableCrashReporter[];
-extern const char kEnableHeapProfiling[];
-extern const char kEnableHeapProfilingModePseudo[];
-extern const char kEnableHeapProfilingModeNative[];
-extern const char kEnableHeapProfilingTaskProfiler[];
+extern const char kEnableFeatures[];
 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 kProfilingAtStart[];
 extern const char kProfilingFile[];
+extern const char kProfilingFlush[];
 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[];
 #endif
 
+#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
+extern const char kDisableDevShmUsage[];
+#endif
+
 #if defined(OS_POSIX)
 extern const char kEnableCrashReporterForTesting[];
 #endif
 
+#if defined(OS_ANDROID)
+extern const char kEnableReachedCodeProfiler[];
+extern const char kOrderfileMemoryOptimization[];
+#endif
+
 }  // namespace switches
 
 #endif  // BASE_BASE_SWITCHES_H_
--- a/security/sandbox/chromium/base/bind.h
+++ b/security/sandbox/chromium/base/bind.h
@@ -1,23 +1,57 @@
 // 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 <functional>
+#include <memory>
+#include <utility>
+
 #include "base/bind_internal.h"
+#include "base/compiler_specific.h"
+#include "build/build_config.h"
+
+#if defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
+#include "base/mac/scoped_block.h"
+#endif
 
 // -----------------------------------------------------------------------------
 // Usage documentation
 // -----------------------------------------------------------------------------
 //
-// See //docs/callback.md for documentation.
+// Overview:
+// base::BindOnce() and base::BindRepeating() are helpers for creating
+// base::OnceCallback and base::RepeatingCallback objects respectively.
+//
+// For a runnable object of n-arity, the base::Bind*() family allows partial
+// application of the first m arguments. The remaining n - m arguments must be
+// passed when invoking the callback with Run().
+//
+//   // The first argument is bound at callback creation; the remaining
+//   // two must be passed when calling Run() on the callback object.
+//   base::OnceCallback<long(int, long)> cb = base::BindOnce(
+//       [](short x, int y, long z) { return x * y * z; }, 42);
 //
+// When binding to a method, the receiver object must also be specified at
+// callback creation time. When Run() is invoked, the method will be invoked on
+// the specified receiver object.
+//
+//   class C : public base::RefCounted<C> { void F(); };
+//   auto instance = base::MakeRefCounted<C>();
+//   auto cb = base::BindOnce(&C::F, instance);
+//   cb.Run();  // Identical to instance->F()
+//
+// base::Bind is currently a type alias for base::BindRepeating(). In the
+// future, we expect to flip this to default to base::BindOnce().
+//
+// See //docs/callback.md for the full 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.
@@ -46,28 +80,28 @@ struct AssertConstructible {
   static constexpr bool param_is_forwardable =
       std::is_constructible<Param, Unwrapped>::value;
   // Unlike the check for binding into storage below, the check for
   // forwardability drops the const qualifier for repeating callbacks. This is
   // to try to catch instances where std::move()--which forwards as a const
   // reference with repeating callbacks--is used instead of base::Passed().
   static_assert(
       param_is_forwardable ||
-          !std::is_constructible<Param, typename std::decay<Unwrapped>::type&&>::value,
+          !std::is_constructible<Param, std::decay_t<Unwrapped>&&>::value,
       "Bound argument |i| is move-only but will be forwarded by copy. "
       "Ensure |Arg| is bound using base::Passed(), not std::move().");
   static_assert(
       param_is_forwardable,
       "Bound argument |i| of type |Arg| cannot be forwarded as "
       "|Unwrapped| to the bound functor, which declares it as |Param|.");
 
   static constexpr bool arg_is_storable =
       std::is_constructible<Storage, Arg>::value;
   static_assert(arg_is_storable ||
-                    !std::is_constructible<Storage, typename std::decay<Arg>::type&&>::value,
+                    !std::is_constructible<Storage, std::decay_t<Arg>&&>::value,
                 "Bound argument |i| is move-only but will be bound by copy. "
                 "Ensure |Arg| is mutable and bound using std::move().");
   static_assert(arg_is_storable,
                 "Bound argument |i| of type |Arg| cannot be converted and "
                 "bound as |Storage|.");
 };
 
 // Takes three same-length TypeLists, and applies AssertConstructible for each
@@ -77,38 +111,38 @@ template <typename Index,
           typename UnwrappedTypeList,
           typename ParamsList>
 struct AssertBindArgsValidity;
 
 template <size_t... Ns,
           typename... Args,
           typename... Unwrapped,
           typename... Params>
-struct AssertBindArgsValidity<IndexSequence<Ns...>,
+struct AssertBindArgsValidity<std::index_sequence<Ns...>,
                               TypeList<Args...>,
                               TypeList<Unwrapped...>,
                               TypeList<Params...>>
-    : AssertConstructible<Ns, Args, typename std::decay<Args>::type, Unwrapped, Params>... {
+    : AssertConstructible<Ns, Args, std::decay_t<Args>, Unwrapped, Params>... {
   static constexpr bool ok = true;
 };
 
 // The implementation of TransformToUnwrappedType below.
 template <bool is_once, typename T>
 struct TransformToUnwrappedTypeImpl;
 
 template <typename T>
 struct TransformToUnwrappedTypeImpl<true, T> {
-  using StoredType = typename std::decay<T>::type;
+  using StoredType = std::decay_t<T>;
   using ForwardType = StoredType&&;
   using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
 };
 
 template <typename T>
 struct TransformToUnwrappedTypeImpl<false, T> {
-  using StoredType = typename std::decay<T>::type;
+  using StoredType = std::decay_t<T>;
   using ForwardType = const StoredType&;
   using Unwrapped = decltype(Unwrap(std::declval<ForwardType>()));
 };
 
 // Transform |T| into `Unwrapped` type, which is passed to the target function.
 // Example:
 //   In is_once == true case,
 //     `int&&` -> `int&&`,
@@ -146,105 +180,102 @@ using MakeUnwrappedTypeList =
     typename MakeUnwrappedTypeListImpl<is_once, is_method, Args...>::Type;
 
 }  // namespace internal
 
 // Bind as OnceCallback.
 template <typename Functor, typename... Args>
 inline OnceCallback<MakeUnboundRunType<Functor, Args...>>
 BindOnce(Functor&& functor, Args&&... args) {
-  static_assert(
-      !internal::IsOnceCallback<typename std::decay<Functor>::type>() ||
-          (std::is_rvalue_reference<Functor&&>() &&
-           !std::is_const<typename std::remove_reference<Functor>::type>()),
-      "BindOnce requires non-const rvalue for OnceCallback binding."
-      " I.e.: base::BindOnce(std::move(callback)).");
+  static_assert(!internal::IsOnceCallback<std::decay_t<Functor>>() ||
+                    (std::is_rvalue_reference<Functor&&>() &&
+                     !std::is_const<std::remove_reference_t<Functor>>()),
+                "BindOnce requires non-const rvalue for OnceCallback binding."
+                " I.e.: base::BindOnce(std::move(callback)).");
 
   // This block checks if each |args| matches to the corresponding params of the
   // target function. This check does not affect the behavior of Bind, but its
   // error message should be more readable.
   using Helper = internal::BindTypeHelper<Functor, Args...>;
   using FunctorTraits = typename Helper::FunctorTraits;
   using BoundArgsList = typename Helper::BoundArgsList;
   using UnwrappedArgsList =
       internal::MakeUnwrappedTypeList<true, FunctorTraits::is_method,
                                       Args&&...>;
   using BoundParamsList = typename Helper::BoundParamsList;
   static_assert(internal::AssertBindArgsValidity<
-                    MakeIndexSequence<Helper::num_bounds>, BoundArgsList,
+                    std::make_index_sequence<Helper::num_bounds>, BoundArgsList,
                     UnwrappedArgsList, BoundParamsList>::ok,
                 "The bound args need to be convertible to the target params.");
 
   using BindState = internal::MakeBindStateType<Functor, Args...>;
   using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
   using Invoker = internal::Invoker<BindState, UnboundRunType>;
   using CallbackType = OnceCallback<UnboundRunType>;
 
   // 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 InvokeFuncStorage = internal::BindStateBase::InvokeFuncStorage;
-  return CallbackType(new BindState(
+  return CallbackType(BindState::Create(
       reinterpret_cast<InvokeFuncStorage>(invoke_func),
-      std::forward<Functor>(functor),
-      std::forward<Args>(args)...));
+      std::forward<Functor>(functor), std::forward<Args>(args)...));
 }
 
 // Bind as RepeatingCallback.
 template <typename Functor, typename... Args>
 inline RepeatingCallback<MakeUnboundRunType<Functor, Args...>>
 BindRepeating(Functor&& functor, Args&&... args) {
   static_assert(
-      !internal::IsOnceCallback<typename std::decay<Functor>::type>(),
+      !internal::IsOnceCallback<std::decay_t<Functor>>(),
       "BindRepeating cannot bind OnceCallback. Use BindOnce with std::move().");
 
   // This block checks if each |args| matches to the corresponding params of the
   // target function. This check does not affect the behavior of Bind, but its
   // error message should be more readable.
   using Helper = internal::BindTypeHelper<Functor, Args...>;
   using FunctorTraits = typename Helper::FunctorTraits;
   using BoundArgsList = typename Helper::BoundArgsList;
   using UnwrappedArgsList =
       internal::MakeUnwrappedTypeList<false, FunctorTraits::is_method,
                                       Args&&...>;
   using BoundParamsList = typename Helper::BoundParamsList;
   static_assert(internal::AssertBindArgsValidity<
-                    MakeIndexSequence<Helper::num_bounds>, BoundArgsList,
+                    std::make_index_sequence<Helper::num_bounds>, BoundArgsList,
                     UnwrappedArgsList, BoundParamsList>::ok,
                 "The bound args need to be convertible to the target params.");
 
   using BindState = internal::MakeBindStateType<Functor, Args...>;
   using UnboundRunType = MakeUnboundRunType<Functor, Args...>;
   using Invoker = internal::Invoker<BindState, UnboundRunType>;
   using CallbackType = RepeatingCallback<UnboundRunType>;
 
   // 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;
 
   using InvokeFuncStorage = internal::BindStateBase::InvokeFuncStorage;
-  return CallbackType(new BindState(
+  return CallbackType(BindState::Create(
       reinterpret_cast<InvokeFuncStorage>(invoke_func),
-      std::forward<Functor>(functor),
-      std::forward<Args>(args)...));
+      std::forward<Functor>(functor), std::forward<Args>(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)...);
+  return base::BindRepeating(std::forward<Functor>(functor),
+                             std::forward<Args>(args)...);
 }
 
 // Special cases for binding to a base::Callback without extra bound arguments.
 template <typename Signature>
 OnceCallback<Signature> BindOnce(OnceCallback<Signature> closure) {
   return closure;
 }
 
@@ -254,11 +285,178 @@ RepeatingCallback<Signature> BindRepeati
   return closure;
 }
 
 template <typename Signature>
 Callback<Signature> Bind(Callback<Signature> closure) {
   return closure;
 }
 
+// Unretained() allows Bind() to bind a non-refcounted class, and to disable
+// refcounting on arguments that are refcounted objects.
+//
+// EXAMPLE OF Unretained():
+//
+//   class Foo {
+//    public:
+//     void func() { cout << "Foo:f" << endl; }
+//   };
+//
+//   // In some function somewhere.
+//   Foo foo;
+//   Closure foo_callback =
+//       Bind(&Foo::func, Unretained(&foo));
+//   foo_callback.Run();  // Prints "Foo:f".
+//
+// Without the Unretained() wrapper on |&foo|, the above call would fail
+// to compile because Foo does not support the AddRef() and Release() methods.
+template <typename T>
+static inline internal::UnretainedWrapper<T> Unretained(T* o) {
+  return internal::UnretainedWrapper<T>(o);
+}
+
+// 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.
+//
+// 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!
+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));
+}
+
+// Owned() transfers ownership of an object to the Callback resulting from
+// bind; the object will be deleted when the Callback is deleted.
+//
+// EXAMPLE OF Owned():
+//
+//   void foo(int* arg) { cout << *arg << endl }
+//
+//   int* pn = new int(1);
+//   Closure foo_callback = Bind(&foo, Owned(pn));
+//
+//   foo_callback.Run();  // Prints "1"
+//   foo_callback.Run();  // Prints "1"
+//   *n = 2;
+//   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.
+template <typename T>
+static inline internal::OwnedWrapper<T> Owned(T* o) {
+  return internal::OwnedWrapper<T>(o);
+}
+
+template <typename T>
+static inline internal::OwnedWrapper<T> Owned(std::unique_ptr<T>&& ptr) {
+  return internal::OwnedWrapper<T>(std::move(ptr));
+}
+
+// Passed() is for transferring movable-but-not-copyable types (eg. unique_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.
+//
+// Note that Passed() is not necessary with BindOnce(), as std::move() does the
+// same thing. Avoid Passed() in favor of std::move() with BindOnce().
+//
+// EXAMPLE OF Passed():
+//
+//   void TakesOwnership(std::unique_ptr<Foo> arg) { }
+//   std::unique_ptr<Foo> CreateFoo() { return std::make_unique<Foo>();
+//   }
+//
+//   auto f = std::make_unique<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();
+//
+//   // |cb| is given a new Foo created by CreateFoo().
+//   cb = Bind(&TakesOwnership, Passed(CreateFoo()));
+//
+//   // |arg| in TakesOwnership() is given ownership of Foo(). |cb|
+//   // no longer owns Foo() and, if reset, would not delete Foo().
+//   cb.Run();  // Foo() is now transferred to |arg| and deleted.
+//   cb.Run();  // This CHECK()s since Foo() already been used once.
+//
+// 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,
+          std::enable_if_t<!std::is_lvalue_reference<T>::value>* = nullptr>
+static inline internal::PassedWrapper<T> Passed(T&& scoper) {
+  return internal::PassedWrapper<T>(std::move(scoper));
+}
+template <typename T>
+static inline internal::PassedWrapper<T> Passed(T* scoper) {
+  return internal::PassedWrapper<T>(std::move(*scoper));
+}
+
+// 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.
+//
+// EXAMPLE OF IgnoreResult():
+//
+//   int DoSomething(int arg) { cout << arg << endl; }
+//
+//   // Assign to a Callback with a void return type.
+//   Callback<void(int)> cb = Bind(IgnoreResult(&DoSomething));
+//   cb->Run(1);  // Prints "1".
+//
+//   // Prints "1" on |ml|.
+//   ml->PostTask(FROM_HERE, BindOnce(IgnoreResult(&DoSomething), 1);
+template <typename T>
+static inline internal::IgnoreResultHelper<T> IgnoreResult(T data) {
+  return internal::IgnoreResultHelper<T>(std::move(data));
+}
+
+#if defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
+
+// RetainBlock() is used to adapt an Objective-C block when Automated Reference
+// Counting (ARC) is disabled. This is unnecessary when ARC is enabled, as the
+// BindOnce and BindRepeating already support blocks then.
+//
+// EXAMPLE OF RetainBlock():
+//
+//   // Wrap the block and bind it to a callback.
+//   Callback<void(int)> cb = Bind(RetainBlock(^(int n) { NSLog(@"%d", n); }));
+//   cb.Run(1);  // Logs "1".
+template <typename R, typename... Args>
+base::mac::ScopedBlock<R (^)(Args...)> RetainBlock(R (^block)(Args...)) {
+  return base::mac::ScopedBlock<R (^)(Args...)>(block,
+                                                base::scoped_policy::RETAIN);
+}
+
+#endif  // defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
+
 }  // namespace base
 
 #endif  // BASE_BIND_H_
--- a/security/sandbox/chromium/base/bind_helpers.h
+++ b/security/sandbox/chromium/base/bind_helpers.h
@@ -1,578 +1,69 @@
 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
 // Use of this source code is governed by a BSD-style license that can be
 // found in the LICENSE file.
 
-// This defines a set of argument wrappers and related factory methods that
-// can be used specify the refcounting and reference semantics of arguments
-// that are bound by the Bind() function in base/bind.h.
-//
-// It also defines a set of simple functions and utilities that people want
-// when using Callback<> and Bind().
-//
-//
-// ARGUMENT BINDING WRAPPERS
-//
-// The wrapper functions are base::Unretained(), base::Owned(), base::Passed(),
-// base::ConstRef(), and base::IgnoreResult().
-//
-// Unretained() allows Bind() to bind a non-refcounted class, and to disable
-// refcounting on arguments that are refcounted objects.
-//
-// Owned() transfers ownership of an object to the Callback resulting from
-// bind; the object will be deleted when the Callback is deleted.
-//
-// Passed() is for transferring movable-but-not-copyable types (eg. unique_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.
-//
-// EXAMPLE OF Unretained():
-//
-//   class Foo {
-//    public:
-//     void func() { cout << "Foo:f" << endl; }
-//   };
-//
-//   // In some function somewhere.
-//   Foo foo;
-//   Closure foo_callback =
-//       Bind(&Foo::func, Unretained(&foo));
-//   foo_callback.Run();  // Prints "Foo:f".
-//
-// Without the Unretained() wrapper on |&foo|, the above call would fail
-// to compile because Foo does not support the AddRef() and Release() methods.
-//
-//
-// EXAMPLE OF Owned():
-//
-//   void foo(int* arg) { cout << *arg << endl }
-//
-//   int* pn = new int(1);
-//   Closure foo_callback = Bind(&foo, Owned(pn));
-//
-//   foo_callback.Run();  // Prints "1"
-//   foo_callback.Run();  // Prints "1"
-//   *n = 2;
-//   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));
-//
-//   no_ref.Run();  // Prints "1"
-//   has_ref.Run();  // Prints "1"
-//
-//   n = 2;
-//   no_ref.Run();  // Prints "1"
-//   has_ref.Run();  // Prints "2"
-//
-// Note that because ConstRef() takes a reference on |n|, |n| must outlive all
-// its bound callbacks.
-//
-//
-// EXAMPLE OF IgnoreResult():
-//
-//   int DoSomething(int arg) { cout << arg << endl; }
-//
-//   // Assign to a Callback with a void return type.
-//   Callback<void(int)> cb = Bind(IgnoreResult(&DoSomething));
-//   cb->Run(1);  // Prints "1".
-//
-//   // Prints "1" on |ml|.
-//   ml->PostTask(FROM_HERE, Bind(IgnoreResult(&DoSomething), 1);
-//
-//
-// EXAMPLE OF Passed():
-//
-//   void TakesOwnership(std::unique_ptr<Foo> arg) { }
-//   std::unique_ptr<Foo> CreateFoo() { return std::unique_ptr<Foo>(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();
-//
-//   // |cb| is given a new Foo created by CreateFoo().
-//   cb = Bind(&TakesOwnership, Passed(CreateFoo()));
-//
-//   // |arg| in TakesOwnership() is given ownership of Foo(). |cb|
-//   // no longer owns Foo() and, if reset, would not delete Foo().
-//   cb.Run();  // Foo() is now transferred to |arg| and deleted.
-//   cb.Run();  // This CHECK()s since Foo() already been used once.
-//
-// Passed() is particularly useful with PostTask() when you are transferring
-// ownership of an argument into a task, but don't necessarily know if the
-// task will always be executed. This can happen if the task is cancellable
-// or if it is posted to a TaskRunner.
-//
-//
-// SIMPLE FUNCTIONS AND UTILITIES.
-//
-//   DoNothing() - Useful for creating a Closure that does nothing when called.
-//   DeletePointer<T>() - Useful for creating a Closure that will delete a
-//                        pointer when invoked. Only use this when necessary.
-//                        In most cases MessageLoop::DeleteSoon() is a better
-//                        fit.
-
 #ifndef BASE_BIND_HELPERS_H_
 #define BASE_BIND_HELPERS_H_
 
 #include <stddef.h>
 
 #include <type_traits>
 #include <utility>
 
+#include "base/bind.h"
 #include "base/callback.h"
 #include "base/memory/weak_ptr.h"
 #include "build/build_config.h"
 
+// This defines a set of simple functions and utilities that people want when
+// using Callback<> and Bind().
+
 namespace base {
 
-template <typename T>
-struct IsWeakReceiver;
-
-template <typename>
-struct BindUnwrapTraits;
-
-namespace internal {
-
-template <typename Functor, typename SFINAE = void>
-struct FunctorTraits;
-
-template <typename T>
-class UnretainedWrapper {
- public:
-  explicit UnretainedWrapper(T* o) : ptr_(o) {}
-  T* get() const { return ptr_; }
- private:
-  T* ptr_;
-};
-
-template <typename T>
-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 {
+// Creates a null callback.
+class BASE_EXPORT NullCallback {
  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_(std::move(functor)) {}
-  explicit operator bool() const { return !!functor_; }
-
-  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 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(OwnedWrapper&& other) {
-    ptr_ = other.ptr_;
-    other.ptr_ = NULL;
+  template <typename R, typename... Args>
+  operator RepeatingCallback<R(Args...)>() const {
+    return RepeatingCallback<R(Args...)>();
   }
-
- private:
-  mutable T* ptr_;
-};
-
-// PassedWrapper is a copyable adapter for a scoper that ignores const.
-//
-// It is needed to get around the fact that Bind() takes a const reference to
-// all its arguments.  Because Bind() takes a const reference to avoid
-// unnecessary copies, it is incompatible with movable-but-not-copyable
-// types; doing a destructive "move" of the type into Bind() would violate
-// the const correctness.
-//
-// This conundrum cannot be solved without either C++11 rvalue references or
-// a O(2^n) blowup of Bind() templates to handle each combination of regular
-// types and movable-but-not-copyable types.  Thus we introduce a wrapper type
-// that is copyable to transmit the correct type information down into
-// BindState<>. Ignoring const in this type makes sense because it is only
-// created when we are explicitly trying to do a destructive move.
-//
-// Two notes:
-//  1) PassedWrapper supports any type that has a move constructor, however
-//     the type will need to be specifically whitelisted in order for it to be
-//     bound to a Callback. We guard this explicitly at the call of Passed()
-//     to make for clear errors. Things not given to Passed() will be forwarded
-//     and stored by value which will not work for general move-only types.
-//  2) is_valid_ is distinct from NULL because it is valid to bind a "NULL"
-//     scoper to a Callback and allow the Callback to execute once.
-template <typename T>
-class PassedWrapper {
- public:
-  explicit PassedWrapper(T&& scoper)
-      : is_valid_(true), scoper_(std::move(scoper)) {}
-  PassedWrapper(PassedWrapper&& other)
-      : is_valid_(other.is_valid_), scoper_(std::move(other.scoper_)) {}
-  T Take() const {
-    CHECK(is_valid_);
-    is_valid_ = false;
-    return std::move(scoper_);
+  template <typename R, typename... Args>
+  operator OnceCallback<R(Args...)>() const {
+    return OnceCallback<R(Args...)>();
   }
-
- private:
-  mutable bool is_valid_;
-  mutable T scoper_;
 };
 
-template <typename T>
-using Unwrapper = BindUnwrapTraits<typename std::decay<T>::type>;
-
-template <typename T>
-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 is_method, typename... Args>
-struct IsWeakMethod : std::false_type {};
-
-template <typename T, typename... Args>
-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;
-
-// Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
-template <size_t n, typename T, typename... List>
-struct DropTypeListItemImpl<n, TypeList<T, List...>>
-    : DropTypeListItemImpl<n - 1, TypeList<List...>> {};
-
-template <typename T, typename... List>
-struct DropTypeListItemImpl<0, TypeList<T, List...>> {
-  using Type = TypeList<T, List...>;
-};
-
-template <>
-struct DropTypeListItemImpl<0, TypeList<>> {
-  using Type = TypeList<>;
-};
-
-// A type-level function that drops |n| list item from given TypeList.
-template <size_t n, typename List>
-using DropTypeListItem = typename DropTypeListItemImpl<n, List>::Type;
-
-// Used for TakeTypeListItem implementation.
-template <size_t n, typename List, typename... Accum>
-struct TakeTypeListItemImpl;
-
-// Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
-template <size_t n, typename T, typename... List, typename... Accum>
-struct TakeTypeListItemImpl<n, TypeList<T, List...>, Accum...>
-    : TakeTypeListItemImpl<n - 1, TypeList<List...>, Accum..., T> {};
-
-template <typename T, typename... List, typename... Accum>
-struct TakeTypeListItemImpl<0, TypeList<T, List...>, Accum...> {
-  using Type = TypeList<Accum...>;
-};
-
-template <typename... Accum>
-struct TakeTypeListItemImpl<0, TypeList<>, Accum...> {
-  using Type = TypeList<Accum...>;
-};
-
-// A type-level function that takes first |n| list item from given TypeList.
-// E.g. TakeTypeListItem<3, TypeList<A, B, C, D>> is evaluated to
-// TypeList<A, B, C>.
-template <size_t n, typename List>
-using TakeTypeListItem = typename TakeTypeListItemImpl<n, List>::Type;
-
-// Used for ConcatTypeLists implementation.
-template <typename List1, typename List2>
-struct ConcatTypeListsImpl;
-
-template <typename... Types1, typename... Types2>
-struct ConcatTypeListsImpl<TypeList<Types1...>, TypeList<Types2...>> {
-  using Type = TypeList<Types1..., Types2...>;
+// Creates a callback that does nothing when called.
+class BASE_EXPORT DoNothing {
+ public:
+  template <typename... Args>
+  operator RepeatingCallback<void(Args...)>() const {
+    return Repeatedly<Args...>();
+  }
+  template <typename... Args>
+  operator OnceCallback<void(Args...)>() const {
+    return Once<Args...>();
+  }
+  // Explicit way of specifying a specific callback type when the compiler can't
+  // deduce it.
+  template <typename... Args>
+  static RepeatingCallback<void(Args...)> Repeatedly() {
+    return BindRepeating([](Args... args) {});
+  }
+  template <typename... Args>
+  static OnceCallback<void(Args...)> Once() {
+    return BindOnce([](Args... args) {});
+  }
 };
 
-// A type-level function that concats two TypeLists.
-template <typename List1, typename List2>
-using ConcatTypeLists = typename ConcatTypeListsImpl<List1, List2>::Type;
-
-// Used for MakeFunctionType implementation.
-template <typename R, typename ArgList>
-struct MakeFunctionTypeImpl;
-
-template <typename R, typename... Args>
-struct MakeFunctionTypeImpl<R, TypeList<Args...>> {
-  // MSVC 2013 doesn't support Type Alias of function types.
-  // Revisit this after we update it to newer version.
-  typedef R Type(Args...);
-};
-
-// A type-level function that constructs a function type that has |R| as its
-// return type and has TypeLists items as its arguments.
-template <typename R, typename ArgList>
-using MakeFunctionType = typename MakeFunctionTypeImpl<R, ArgList>::Type;
-
-// Used for ExtractArgs and ExtractReturnType.
-template <typename Signature>
-struct ExtractArgsImpl;
-
-template <typename R, typename... Args>
-struct ExtractArgsImpl<R(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>::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
-
+// Useful for creating a Closure that will delete a pointer when invoked. Only
+// use this when necessary. In most cases MessageLoop::DeleteSoon() is a better
+// fit.
 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);
-}
-
-// 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<!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>
-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>(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();
-  }
-};
-
-// CallbackCancellationTraits allows customization of Callback's cancellation
-// semantics. By default, callbacks are not cancellable. A specialization should
-// set is_cancellable = true and implement an IsCancelled() that returns if the
-// callback should be cancelled.
-template <typename Functor, typename BoundArgsTuple, typename SFINAE = void>
-struct CallbackCancellationTraits {
-  static constexpr bool is_cancellable = false;
-};
-
-// Specialization for method bound to weak pointer receiver.
-template <typename Functor, typename... BoundArgs>
-struct CallbackCancellationTraits<
-    Functor,
-    std::tuple<BoundArgs...>,
-    typename std::enable_if<
-        internal::IsWeakMethod<internal::FunctorTraits<Functor>::is_method,
-                               BoundArgs...>::value>::type> {
-  static constexpr bool is_cancellable = true;
-
-  template <typename Receiver, typename... Args>
-  static bool IsCancelled(const Functor&,
-                          const Receiver& receiver,
-                          const Args&...) {
-    return !receiver;
-  }
-};
-
-// Specialization for a nested bind.
-template <typename Signature, typename... BoundArgs>
-struct CallbackCancellationTraits<OnceCallback<Signature>,
-                                  std::tuple<BoundArgs...>> {
-  static constexpr bool is_cancellable = true;
-
-  template <typename Functor>
-  static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
-    return functor.IsCancelled();
-  }
-};
-
-template <typename Signature, typename... BoundArgs>
-struct CallbackCancellationTraits<RepeatingCallback<Signature>,
-                                  std::tuple<BoundArgs...>> {
-  static constexpr bool is_cancellable = true;
-
-  template <typename Functor>
-  static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
-    return functor.IsCancelled();
-  }
-};
-
 }  // namespace base
 
 #endif  // BASE_BIND_HELPERS_H_
--- a/security/sandbox/chromium/base/bind_internal.h
+++ b/security/sandbox/chromium/base/bind_internal.h
@@ -2,29 +2,33 @@
 // 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 <functional>
+#include <memory>
 #include <tuple>
 #include <type_traits>
+#include <utility>
 
-#include "base/bind_helpers.h"
+#include "base/bind.h"
 #include "base/callback_internal.h"
+#include "base/compiler_specific.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"
 
-namespace base {
-namespace internal {
+#if defined(OS_MACOSX) && !HAS_FEATURE(objc_arc)
+#include "base/mac/scoped_block.h"
+#endif
 
 // See base/callback.h for user documentation.
 //
 //
 // CONCEPTS:
 //  Functor -- A movable type representing something that should be called.
 //             All function pointers and Callback<> are functors even if the
 //             invocation syntax differs.
@@ -41,72 +45,301 @@ namespace internal {
 //  InvokeHelper<> -- Take a Functor + arguments and actully invokes it.
 //                    Handle the differing syntaxes needed for WeakPtr<>
 //                    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.
 
+#if defined(OS_WIN)
+namespace Microsoft {
+namespace WRL {
+template <typename>
+class ComPtr;
+}  // namespace WRL
+}  // namespace Microsoft
+#endif
+
+namespace base {
+
+template <typename T>
+struct IsWeakReceiver;
+
+template <typename>
+struct BindUnwrapTraits;
+
+template <typename Functor, typename BoundArgsTuple, typename SFINAE = void>
+struct CallbackCancellationTraits;
+
+namespace internal {
+
+template <typename Functor, typename SFINAE = void>
+struct FunctorTraits;
+
+template <typename T>
+class UnretainedWrapper {
+ public:
+  explicit UnretainedWrapper(T* o) : ptr_(o) {}
+  T* get() const { return ptr_; }
+
+ private:
+  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_(std::move(functor)) {}
+  explicit operator bool() const { return !!functor_; }
+
+  T functor_;
+};
+
+template <typename T>
+class OwnedWrapper {
+ public:
+  explicit OwnedWrapper(T* o) : ptr_(o) {}
+  explicit OwnedWrapper(std::unique_ptr<T>&& ptr) : ptr_(std::move(ptr)) {}
+  T* get() const { return ptr_.get(); }
+
+ private:
+  std::unique_ptr<T> ptr_;
+};
+
+// PassedWrapper is a copyable adapter for a scoper that ignores const.
+//
+// It is needed to get around the fact that Bind() takes a const reference to
+// all its arguments.  Because Bind() takes a const reference to avoid
+// unnecessary copies, it is incompatible with movable-but-not-copyable
+// types; doing a destructive "move" of the type into Bind() would violate
+// the const correctness.
+//
+// This conundrum cannot be solved without either C++11 rvalue references or
+// a O(2^n) blowup of Bind() templates to handle each combination of regular
+// types and movable-but-not-copyable types.  Thus we introduce a wrapper type
+// that is copyable to transmit the correct type information down into
+// BindState<>. Ignoring const in this type makes sense because it is only
+// created when we are explicitly trying to do a destructive move.
+//
+// Two notes:
+//  1) PassedWrapper supports any type that has a move constructor, however
+//     the type will need to be specifically whitelisted in order for it to be
+//     bound to a Callback. We guard this explicitly at the call of Passed()
+//     to make for clear errors. Things not given to Passed() will be forwarded
+//     and stored by value which will not work for general move-only types.
+//  2) is_valid_ is distinct from NULL because it is valid to bind a "NULL"
+//     scoper to a Callback and allow the Callback to execute once.
+template <typename T>
+class PassedWrapper {
+ public:
+  explicit PassedWrapper(T&& scoper)
+      : is_valid_(true), scoper_(std::move(scoper)) {}
+  PassedWrapper(PassedWrapper&& other)
+      : is_valid_(other.is_valid_), scoper_(std::move(other.scoper_)) {}
+  T Take() const {
+    CHECK(is_valid_);
+    is_valid_ = false;
+    return std::move(scoper_);
+  }
+
+ private:
+  mutable bool is_valid_;
+  mutable T scoper_;
+};
+
+template <typename T>
+using Unwrapper = BindUnwrapTraits<std::decay_t<T>>;
+
+template <typename T>
+decltype(auto) Unwrap(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 is_method, typename... Args>
+struct IsWeakMethod : std::false_type {};
+
+template <typename T, typename... Args>
+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;
+
+// Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
+template <size_t n, typename T, typename... List>
+struct DropTypeListItemImpl<n, TypeList<T, List...>>
+    : DropTypeListItemImpl<n - 1, TypeList<List...>> {};
+
+template <typename T, typename... List>
+struct DropTypeListItemImpl<0, TypeList<T, List...>> {
+  using Type = TypeList<T, List...>;
+};
+
+template <>
+struct DropTypeListItemImpl<0, TypeList<>> {
+  using Type = TypeList<>;
+};
+
+// A type-level function that drops |n| list item from given TypeList.
+template <size_t n, typename List>
+using DropTypeListItem = typename DropTypeListItemImpl<n, List>::Type;
+
+// Used for TakeTypeListItem implementation.
+template <size_t n, typename List, typename... Accum>
+struct TakeTypeListItemImpl;
+
+// Do not use enable_if and SFINAE here to avoid MSVC2013 compile failure.
+template <size_t n, typename T, typename... List, typename... Accum>
+struct TakeTypeListItemImpl<n, TypeList<T, List...>, Accum...>
+    : TakeTypeListItemImpl<n - 1, TypeList<List...>, Accum..., T> {};
+
+template <typename T, typename... List, typename... Accum>
+struct TakeTypeListItemImpl<0, TypeList<T, List...>, Accum...> {
+  using Type = TypeList<Accum...>;
+};
+
+template <typename... Accum>
+struct TakeTypeListItemImpl<0, TypeList<>, Accum...> {
+  using Type = TypeList<Accum...>;
+};
+
+// A type-level function that takes first |n| list item from given TypeList.
+// E.g. TakeTypeListItem<3, TypeList<A, B, C, D>> is evaluated to
+// TypeList<A, B, C>.
+template <size_t n, typename List>
+using TakeTypeListItem = typename TakeTypeListItemImpl<n, List>::Type;
+
+// Used for ConcatTypeLists implementation.
+template <typename List1, typename List2>
+struct ConcatTypeListsImpl;
+
+template <typename... Types1, typename... Types2>
+struct ConcatTypeListsImpl<TypeList<Types1...>, TypeList<Types2...>> {
+  using Type = TypeList<Types1..., Types2...>;
+};
+
+// A type-level function that concats two TypeLists.
+template <typename List1, typename List2>
+using ConcatTypeLists = typename ConcatTypeListsImpl<List1, List2>::Type;
+
+// Used for MakeFunctionType implementation.
+template <typename R, typename ArgList>
+struct MakeFunctionTypeImpl;
+
+template <typename R, typename... Args>
+struct MakeFunctionTypeImpl<R, TypeList<Args...>> {
+  // MSVC 2013 doesn't support Type Alias of function types.
+  // Revisit this after we update it to newer version.
+  typedef R Type(Args...);
+};
+
+// A type-level function that constructs a function type that has |R| as its
+// return type and has TypeLists items as its arguments.
+template <typename R, typename ArgList>
+using MakeFunctionType = typename MakeFunctionTypeImpl<R, ArgList>::Type;
+
+// Used for ExtractArgs and ExtractReturnType.
+template <typename Signature>
+struct ExtractArgsImpl;
+
+template <typename R, typename... Args>
+struct ExtractArgsImpl<R(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>::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;
+
 template <typename Callable,
           typename Signature = decltype(&Callable::operator())>
 struct ExtractCallableRunTypeImpl;
 
 template <typename Callable, typename R, typename... Args>
-struct ExtractCallableRunTypeImpl<Callable, R(Callable::*)(Args...) const> {
+struct ExtractCallableRunTypeImpl<Callable, R (Callable::*)(Args...)> {
+  using Type = R(Args...);
+};
+
+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;
 
-// IsConvertibleToRunType<Functor> is std::true_type if |Functor| has operator()
-// and convertible to the corresponding function pointer. Otherwise, it's
-// std::false_type.
+// IsCallableObject<Functor> is std::true_type if |Functor| has operator().
+// Otherwise, it's std::false_type.
 // Example:
-//   IsConvertibleToRunType<void(*)()>::value is false.
+//   IsCallableObject<void(*)()>::value is false.
 //
 //   struct Foo {};
-//   IsConvertibleToRunType<void(Foo::*)()>::value is false.
-//
-//   auto f = []() {};
-//   IsConvertibleToRunType<decltype(f)>::value is true.
+//   IsCallableObject<void(Foo::*)()>::value is false.
 //
 //   int i = 0;
-//   auto g = [i]() {};
-//   IsConvertibleToRunType<decltype(g)>::value is false.
+//   auto f = [i]() {};
+//   IsCallableObject<decltype(f)>::value is false.
 template <typename Functor, typename SFINAE = void>
-struct IsConvertibleToRunType : std::false_type {};
+struct IsCallableObject : std::false_type {};
 
 template <typename Callable>
-struct IsConvertibleToRunType<Callable, void_t<decltype(&Callable::operator())>>
-    : std::is_convertible<Callable, ExtractCallableRunType<Callable>*> {};
+struct IsCallableObject<Callable, void_t<decltype(&Callable::operator())>>
+    : std::true_type {};
 
 // HasRefCountedTypeAsRawPtr selects true_type when any of the |Args| is a raw
 // pointer to a RefCounted type.
 // Implementation note: This non-specialized case handles zero-arity case only.
 // Non-zero-arity cases should be handled by the specialization below.
 template <typename... Args>
 struct HasRefCountedTypeAsRawPtr : 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,
-                       std::true_type,
-                       HasRefCountedTypeAsRawPtr<Args...>>::type {};
+    : std::conditional_t<NeedsScopedRefptrButGetsRawPtr<T>::value,
+                         std::true_type,
+                         HasRefCountedTypeAsRawPtr<Args...>> {};
 
 // ForceVoidReturn<>
 //
 // Set of templates that support forcing the function return type to void.
 template <typename Sig>
 struct ForceVoidReturn;
 
 template <typename R, typename... Args>
@@ -115,45 +348,60 @@ struct ForceVoidReturn<R(Args...)> {
 };
 
 // FunctorTraits<>
 //
 // See description at top of file.
 template <typename Functor, typename SFINAE>
 struct FunctorTraits;
 
-// For a callable type that is convertible to the corresponding function type.
+// For empty callable types.
 // 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.
+// base::Bind(), based on the fact that captureless lambdas are empty while
+// capturing lambdas are not. This also allows any functors as far as it's an
+// empty class.
+// Example:
+//
+//   // Captureless lambdas are allowed.
+//   []() {return 42;};
+//
+//   // Capturing lambdas are *not* allowed.
+//   int x;
+//   [x]() {return x;};
+//
+//   // Any empty class with operator() is allowed.
+//   struct Foo {
+//     void operator()() const {}
+//     // No non-static member variable and no virtual functions.
+//   };
 template <typename Functor>
-struct FunctorTraits<
-    Functor,
-    typename std::enable_if<IsConvertibleToRunType<Functor>::value>::type> {
+struct FunctorTraits<Functor,
+                     std::enable_if_t<IsCallableObject<Functor>::value &&
+                                      std::is_empty<Functor>::value>> {
   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 RunFunctor, typename... RunArgs>
+  static ExtractReturnType<RunType> Invoke(RunFunctor&& functor,
+                                           RunArgs&&... args) {
+    return std::forward<RunFunctor>(functor)(std::forward<RunArgs>(args)...);
   }
 };
 
 // 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 Function, typename... RunArgs>
+  static R Invoke(Function&& function, RunArgs&&... args) {
+    return std::forward<Function>(function)(std::forward<RunArgs>(args)...);
   }
 };
 
 #if defined(OS_WIN) && !defined(ARCH_CPU_64_BITS)
 
 // For functions.
 template <typename R, typename... Args>
 struct FunctorTraits<R(__stdcall*)(Args...)> {
@@ -177,46 +425,118 @@ struct FunctorTraits<R(__fastcall*)(Args
   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_64_BITS)
 
+#if defined(OS_MACOSX)
+
+// Support for Objective-C blocks. There are two implementation depending
+// on whether Automated Reference Counting (ARC) is enabled. When ARC is
+// enabled, then the block itself can be bound as the compiler will ensure
+// its lifetime will be correctly managed. Otherwise, require the block to
+// be wrapped in a base::mac::ScopedBlock (via base::RetainBlock) that will
+// correctly manage the block lifetime.
+//
+// The two implementation ensure that the One Definition Rule (ODR) is not
+// broken (it is not possible to write a template base::RetainBlock that would
+// work correctly both with ARC enabled and disabled).
+
+#if HAS_FEATURE(objc_arc)
+
+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 BlockType, typename... RunArgs>
+  static R Invoke(BlockType&& block, RunArgs&&... args) {
+    // According to LLVM documentation (ยง 6.3), "local variables of automatic
+    // storage duration do not have precise lifetime." Use objc_precise_lifetime
+    // to ensure that the Objective-C block is not deallocated until it has
+    // finished executing even if the Callback<> is destroyed during the block
+    // execution.
+    // https://clang.llvm.org/docs/AutomaticReferenceCounting.html#precise-lifetime-semantics
+    __attribute__((objc_precise_lifetime)) R (^scoped_block)(Args...) = block;
+    return scoped_block(std::forward<RunArgs>(args)...);
+  }
+};
+
+#else  // HAS_FEATURE(objc_arc)
+
+template <typename R, typename... Args>
+struct FunctorTraits<base::mac::ScopedBlock<R (^)(Args...)>> {
+  using RunType = R(Args...);
+  static constexpr bool is_method = false;
+  static constexpr bool is_nullable = true;
+
+  template <typename BlockType, typename... RunArgs>
+  static R Invoke(BlockType&& block, RunArgs&&... args) {
+    // Copy the block to ensure that the Objective-C block is not deallocated
+    // until it has finished executing even if the Callback<> is destroyed
+    // during the block execution.
+    base::mac::ScopedBlock<R (^)(Args...)> scoped_block(block);
+    return scoped_block.get()(std::forward<RunArgs>(args)...);
+  }
+};
+
+#endif  // HAS_FEATURE(objc_arc)
+#endif  // defined(OS_MACOSX)
+
 // 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...),
+  template <typename Method, typename ReceiverPtr, typename... RunArgs>
+  static R Invoke(Method method,
                   ReceiverPtr&& receiver_ptr,
                   RunArgs&&... args) {
     return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
   }
 };
 
 // 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,
+  template <typename Method, typename ReceiverPtr, typename... RunArgs>
+  static R Invoke(Method method,
                   ReceiverPtr&& receiver_ptr,
                   RunArgs&&... args) {
     return ((*receiver_ptr).*method)(std::forward<RunArgs>(args)...);
   }
 };
 
+#ifdef __cpp_noexcept_function_type
+// noexcept makes a distinct function type in C++17.
+// I.e. `void(*)()` and `void(*)() noexcept` are same in pre-C++17, and
+// different in C++17.
+template <typename R, typename... Args>
+struct FunctorTraits<R (*)(Args...) noexcept> : FunctorTraits<R (*)(Args...)> {
+};
+
+template <typename R, typename Receiver, typename... Args>
+struct FunctorTraits<R (Receiver::*)(Args...) noexcept>
+    : FunctorTraits<R (Receiver::*)(Args...)> {};
+
+template <typename R, typename Receiver, typename... Args>
+struct FunctorTraits<R (Receiver::*)(Args...) const noexcept>
+    : FunctorTraits<R (Receiver::*)(Args...) const> {};
+#endif
+
 // For IgnoreResults.
 template <typename T>
 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,
@@ -253,17 +573,17 @@ struct FunctorTraits<RepeatingCallback<R
   static R Invoke(CallbackType&& callback, RunArgs&&... args) {
     DCHECK(!callback.is_null());
     return std::forward<CallbackType>(callback).Run(
         std::forward<RunArgs>(args)...);
   }
 };
 
 template <typename Functor>
-using MakeFunctorTraits = FunctorTraits<typename std::decay<Functor>::type>;
+using MakeFunctorTraits = FunctorTraits<std::decay_t<Functor>>;
 
 // InvokeHelper<>
 //
 // There are 2 logical InvokeHelper<> specializations: normal, WeakCalls.
 //
 // The normal type just calls the underlying runnable.
 //
 // WeakCalls need special syntax that is applied to the first argument to check
@@ -305,55 +625,54 @@ struct InvokeHelper<true, ReturnType> {
 // Invoker<>
 //
 // See description at the top of the file.
 template <typename StorageType, typename UnboundRunType>
 struct Invoker;
 
 template <typename StorageType, typename R, typename... UnboundArgs>
 struct Invoker<StorageType, R(UnboundArgs...)> {
-  static R RunOnce(BindStateBase* base, UnboundArgs&&... unbound_args) {
+  static R RunOnce(BindStateBase* base,
+                   PassingType<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::make_index_sequence<num_bound_args>(),
                    std::forward<UnboundArgs>(unbound_args)...);
   }
 
-  static R Run(BindStateBase* base, UnboundArgs&&... unbound_args) {
+  static R Run(BindStateBase* base, PassingType<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.
     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::make_index_sequence<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...>,
+                          std::index_sequence<indices...>,
                           UnboundArgs&&... unbound_args) {
     static constexpr bool is_method = MakeFunctorTraits<Functor>::is_method;
 
-    using DecayedArgsTuple = typename std::decay<BoundArgsTuple>::type;
+    using DecayedArgsTuple = std::decay_t<BoundArgsTuple>;
     static constexpr bool is_weak_call =
         IsWeakMethod<is_method,
-                     typename std::tuple_element<
-                         indices,
-                         DecayedArgsTuple>::type...>::value;
+                     std::tuple_element_t<indices, DecayedArgsTuple>...>();
 
     return InvokeHelper<is_weak_call, R>::MakeItSo(
         std::forward<Functor>(functor),
         Unwrap(std::get<indices>(std::forward<BoundArgsTuple>(bound)))...,
         std::forward<UnboundArgs>(unbound_args)...);
   }
 };
 
@@ -382,154 +701,347 @@ struct BindTypeHelper {
   using UnboundParamsList = DropTypeListItem<num_bounds, RunParamsList>;
 
   using BoundArgsList = TypeList<BoundArgs...>;
 
   using UnboundRunType = MakeFunctionType<ReturnType, UnboundParamsList>;
 };
 
 template <typename Functor>
-typename std::enable_if<FunctorTraits<Functor>::is_nullable, bool>::type
-IsNull(const Functor& functor) {
+std::enable_if_t<FunctorTraits<Functor>::is_nullable, bool> IsNull(
+    const Functor& functor) {
   return !functor;
 }
 
 template <typename Functor>
-typename std::enable_if<!FunctorTraits<Functor>::is_nullable, bool>::type
-IsNull(const Functor&) {
+std::enable_if_t<!FunctorTraits<Functor>::is_nullable, bool> IsNull(
+    const Functor&) {
   return false;
 }
 
-// Used by ApplyCancellationTraits below.
+// Used by QueryCancellationTraits below.
 template <typename Functor, typename BoundArgsTuple, size_t... indices>
-bool ApplyCancellationTraitsImpl(const Functor& functor,
+bool QueryCancellationTraitsImpl(BindStateBase::CancellationQueryMode mode,
+                                 const Functor& functor,
                                  const BoundArgsTuple& bound_args,
-                                 IndexSequence<indices...>) {
-  return CallbackCancellationTraits<Functor, BoundArgsTuple>::IsCancelled(
-      functor, std::get<indices>(bound_args)...);
+                                 std::index_sequence<indices...>) {
+  switch (mode) {
+    case BindStateBase::IS_CANCELLED:
+      return CallbackCancellationTraits<Functor, BoundArgsTuple>::IsCancelled(
+          functor, std::get<indices>(bound_args)...);
+    case BindStateBase::MAYBE_VALID:
+      return CallbackCancellationTraits<Functor, BoundArgsTuple>::MaybeValid(
+          functor, std::get<indices>(bound_args)...);
+  }
+  NOTREACHED();
 }
 
 // Relays |base| to corresponding CallbackCancellationTraits<>::Run(). Returns
 // true if the callback |base| represents is canceled.
 template <typename BindStateType>
-bool ApplyCancellationTraits(const BindStateBase* base) {
+bool QueryCancellationTraits(const BindStateBase* base,
+                             BindStateBase::CancellationQueryMode mode) {
   const BindStateType* storage = static_cast<const BindStateType*>(base);
   static constexpr size_t num_bound_args =
       std::tuple_size<decltype(storage->bound_args_)>::value;
-  return ApplyCancellationTraitsImpl(
-      storage->functor_, storage->bound_args_,
-      MakeIndexSequence<num_bound_args>());
-};
+  return QueryCancellationTraitsImpl(
+      mode, storage->functor_, storage->bound_args_,
+      std::make_index_sequence<num_bound_args>());
+}
+
+// The base case of BanUnconstructedRefCountedReceiver that checks nothing.
+template <typename Functor, typename Receiver, typename... Unused>
+std::enable_if_t<
+    !(MakeFunctorTraits<Functor>::is_method &&
+      std::is_pointer<std::decay_t<Receiver>>::value &&
+      IsRefCountedType<std::remove_pointer_t<std::decay_t<Receiver>>>::value)>
+BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {}
+
+template <typename Functor>
+void BanUnconstructedRefCountedReceiver() {}
+
+// Asserts that Callback is not the first owner of a ref-counted receiver.
+template <typename Functor, typename Receiver, typename... Unused>
+std::enable_if_t<
+    MakeFunctorTraits<Functor>::is_method &&
+    std::is_pointer<std::decay_t<Receiver>>::value &&
+    IsRefCountedType<std::remove_pointer_t<std::decay_t<Receiver>>>::value>
+BanUnconstructedRefCountedReceiver(const Receiver& receiver, Unused&&...) {
+  DCHECK(receiver);
+
+  // It's error prone to make the implicit first reference to ref-counted types.
+  // In the example below, base::BindOnce() makes the implicit first reference
+  // to the ref-counted Foo. If PostTask() failed or the posted task ran fast
+  // enough, the newly created instance can be destroyed before |oo| makes
+  // another reference.
+  //   Foo::Foo() {
+  //     base::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, this));
+  //   }
+  //
+  //   scoped_refptr<Foo> oo = new Foo();
+  //
+  // Instead of doing like above, please consider adding a static constructor,
+  // and keep the first reference alive explicitly.
+  //   // static
+  //   scoped_refptr<Foo> Foo::Create() {
+  //     auto foo = base::WrapRefCounted(new Foo());
+  //     base::PostTask(FROM_HERE, base::BindOnce(&Foo::Bar, foo));
+  //     return foo;
+  //   }
+  //
+  //   Foo::Foo() {}
+  //
+  //   scoped_refptr<Foo> oo = Foo::Create();
+  DCHECK(receiver->HasAtLeastOneRef())
+      << "base::Bind() refuses to create the first reference to ref-counted "
+         "objects. That is typically happens around PostTask() in their "
+         "constructor, and such objects can be destroyed before `new` returns "
+         "if the task resolves fast enough.";
+}
 
 // BindState<>
 //
 // This stores all the state passed into Bind().
 template <typename Functor, typename... BoundArgs>
 struct BindState final : BindStateBase {
   using IsCancellable = std::integral_constant<
       bool,
       CallbackCancellationTraits<Functor,
                                  std::tuple<BoundArgs...>>::is_cancellable>;
 
   template <typename ForwardFunctor, typename... ForwardBoundArgs>
-  explicit BindState(BindStateBase::InvokeFuncStorage invoke_func,
-                     ForwardFunctor&& functor,
-                     ForwardBoundArgs&&... bound_args)
-      // IsCancellable is std::false_type if
-      // CallbackCancellationTraits<>::IsCancelled returns always false.
-      // Otherwise, it's std::true_type.
-      : BindState(IsCancellable{},
-                  invoke_func,
-                  std::forward<ForwardFunctor>(functor),
-                  std::forward<ForwardBoundArgs>(bound_args)...) {
+  static BindState* Create(BindStateBase::InvokeFuncStorage invoke_func,
+                           ForwardFunctor&& functor,
+                           ForwardBoundArgs&&... bound_args) {
+    // Ban ref counted receivers that were not yet fully constructed to avoid
+    // a common pattern of racy situation.
+    BanUnconstructedRefCountedReceiver<ForwardFunctor>(bound_args...);
+
+    // IsCancellable is std::false_type if
+    // CallbackCancellationTraits<>::IsCancelled returns always false.
+    // Otherwise, it's std::true_type.
+    return new BindState(IsCancellable{}, invoke_func,
+                         std::forward<ForwardFunctor>(functor),
+                         std::forward<ForwardBoundArgs>(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,
-                      &ApplyCancellationTraits<BindState>),
+                      &QueryCancellationTraits<BindState>),
         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() {}
+  ~BindState() = default;
 
   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<
-                    typename std::decay<BoundArgs>::type...>::value,
+  static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<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...>;
+  using Type = BindState<std::decay_t<Functor>, std::decay_t<BoundArgs>...>;
 };
 
 template <typename Functor>
 struct MakeBindStateTypeImpl<true, Functor> {
-  using Type = BindState<typename std::decay<Functor>::type>;
+  using Type = BindState<std::decay_t<Functor>>;
 };
 
 template <typename Functor, typename Receiver, typename... BoundArgs>
 struct MakeBindStateTypeImpl<true, Functor, Receiver, BoundArgs...> {
+ private:
+  using DecayedReceiver = std::decay_t<Receiver>;
+
+  static_assert(!std::is_array<std::remove_reference_t<Receiver>>::value,
+                "First bound argument to a method cannot be an array.");
   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<
-                    typename std::decay<BoundArgs>::type...>::value,
+      !std::is_pointer<DecayedReceiver>::value ||
+          IsRefCountedType<std::remove_pointer_t<DecayedReceiver>>::value,
+      "Receivers may not be raw pointers. If using a raw pointer here is safe"
+      " and has no lifetime concerns, use base::Unretained() and document why"
+      " it's safe.");
+  static_assert(!HasRefCountedTypeAsRawPtr<std::decay_t<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...>;
+      std::decay_t<Functor>,
+      std::conditional_t<std::is_pointer<DecayedReceiver>::value,
+                         scoped_refptr<std::remove_pointer_t<DecayedReceiver>>,
+                         DecayedReceiver>,
+      std::decay_t<BoundArgs>...>;
 };
 
 template <typename Functor, typename... BoundArgs>
 using MakeBindStateType =
     typename MakeBindStateTypeImpl<MakeFunctorTraits<Functor>::is_method,
                                    Functor,
                                    BoundArgs...>::Type;
 
 }  // namespace internal
 
+// 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<std::reference_wrapper<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<std::reference_wrapper<T>> {
+  static T& Unwrap(std::reference_wrapper<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(); }
+};
+
+#if defined(OS_WIN)
+template <typename T>
+struct BindUnwrapTraits<Microsoft::WRL::ComPtr<T>> {
+  static T* Unwrap(const Microsoft::WRL::ComPtr<T>& ptr) { return ptr.Get(); }
+};
+#endif
+
+// CallbackCancellationTraits allows customization of Callback's cancellation
+// semantics. By default, callbacks are not cancellable. A specialization should
+// set is_cancellable = true and implement an IsCancelled() that returns if the
+// callback should be cancelled.
+template <typename Functor, typename BoundArgsTuple, typename SFINAE>
+struct CallbackCancellationTraits {
+  static constexpr bool is_cancellable = false;
+};
+
+// Specialization for method bound to weak pointer receiver.
+template <typename Functor, typename... BoundArgs>
+struct CallbackCancellationTraits<
+    Functor,
+    std::tuple<BoundArgs...>,
+    std::enable_if_t<
+        internal::IsWeakMethod<internal::FunctorTraits<Functor>::is_method,
+                               BoundArgs...>::value>> {
+  static constexpr bool is_cancellable = true;
+
+  template <typename Receiver, typename... Args>
+  static bool IsCancelled(const Functor&,
+                          const Receiver& receiver,
+                          const Args&...) {
+    return !receiver;
+  }
+
+  template <typename Receiver, typename... Args>
+  static bool MaybeValid(const Functor&,
+                         const Receiver& receiver,
+                         const Args&...) {
+    return receiver.MaybeValid();
+  }
+};
+
+// Specialization for a nested bind.
+template <typename Signature, typename... BoundArgs>
+struct CallbackCancellationTraits<OnceCallback<Signature>,
+                                  std::tuple<BoundArgs...>> {
+  static constexpr bool is_cancellable = true;
+
+  template <typename Functor>
+  static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
+    return functor.IsCancelled();
+  }
+
+  template <typename Functor>
+  static bool MaybeValid(const Functor& functor, const BoundArgs&...) {
+    return functor.MaybeValid();
+  }
+};
+
+template <typename Signature, typename... BoundArgs>
+struct CallbackCancellationTraits<RepeatingCallback<Signature>,
+                                  std::tuple<BoundArgs...>> {
+  static constexpr bool is_cancellable = true;
+
+  template <typename Functor>
+  static bool IsCancelled(const Functor& functor, const BoundArgs&...) {
+    return functor.IsCancelled();
+  }
+
+  template <typename Functor>
+  static bool MaybeValid(const Functor& functor, const BoundArgs&...) {
+    return functor.MaybeValid();
+  }
+};
+
 // 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::BindTypeHelper<Functor, BoundArgs...>::UnboundRunType;
 
 }  // namespace base
 
--- a/security/sandbox/chromium/base/callback.h
+++ b/security/sandbox/chromium/base/callback.h
@@ -1,56 +1,89 @@
 // 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.
+//
+// NOTE: Header files that do not require the full definition of Callback or
+// Closure should #include "base/callback_forward.h" instead of this file.
 
 #ifndef BASE_CALLBACK_H_
 #define BASE_CALLBACK_H_
 
+#include <stddef.h>
+
 #include "base/callback_forward.h"
 #include "base/callback_internal.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.
-
 // -----------------------------------------------------------------------------
 // Usage documentation
 // -----------------------------------------------------------------------------
 //
-// See //docs/callback.md for documentation.
+// Overview:
+// A callback is similar in concept to a function pointer: it wraps a runnable
+// object such as a function, method, lambda, or even another callback, allowing
+// the runnable object to be invoked later via the callback object.
+//
+// Unlike function pointers, callbacks are created with base::BindOnce() or
+// base::BindRepeating() and support partial function application.
+//
+// A base::OnceCallback may be Run() at most once; a base::RepeatingCallback may
+// be Run() any number of times. |is_null()| is guaranteed to return true for a
+// moved-from callback.
+//
+//   // The lambda takes two arguments, but the first argument |x| is bound at
+//   // callback creation.
+//   base::OnceCallback<int(int)> cb = base::BindOnce([] (int x, int y) {
+//     return x + y;
+//   }, 1);
+//   // Run() only needs the remaining unbound argument |y|.
+//   printf("1 + 2 = %d\n", std::move(cb).Run(2));  // Prints 3
+//   printf("cb is null? %s\n",
+//          cb.is_null() ? "true" : "false");  // Prints true
+//   std::move(cb).Run(2);  // Crashes since |cb| has already run.
+//
+// Callbacks also support cancellation. A common use is binding the receiver
+// object as a WeakPtr<T>. If that weak pointer is invalidated, calling Run()
+// will be a no-op. Note that |is_cancelled()| and |is_null()| are distinct:
+// simply cancelling a callback will not also make it null.
+//
+// base::Callback is currently a type alias for base::RepeatingCallback. In the
+// future, we expect to flip this to default to base::OnceCallback.
+//
+// See //docs/callback.md for the full documentation.
 
 namespace base {
 
 template <typename R, typename... Args>
 class OnceCallback<R(Args...)> : public internal::CallbackBase {
  public:
   using RunType = R(Args...);
-  using PolymorphicInvoke = R (*)(internal::BindStateBase*, Args&&...);
+  using PolymorphicInvoke = R (*)(internal::BindStateBase*,
+                                  internal::PassingType<Args>...);
 
-  OnceCallback() : internal::CallbackBase(nullptr) {}
+  constexpr OnceCallback() = default;
+  OnceCallback(std::nullptr_t) = delete;
 
   explicit OnceCallback(internal::BindStateBase* bind_state)
       : internal::CallbackBase(bind_state) {}
 
   OnceCallback(const OnceCallback&) = delete;
   OnceCallback& operator=(const OnceCallback&) = delete;
 
-  OnceCallback(OnceCallback&&) = default;
-  OnceCallback& operator=(OnceCallback&&) = default;
+  OnceCallback(OnceCallback&&) noexcept = default;
+  OnceCallback& operator=(OnceCallback&&) noexcept = default;
 
   OnceCallback(RepeatingCallback<RunType> other)
       : internal::CallbackBase(std::move(other)) {}
 
   OnceCallback& operator=(RepeatingCallback<RunType> other) {
     static_cast<internal::CallbackBase&>(*this) = std::move(other);
     return *this;
   }
 
-  bool Equals(const OnceCallback& other) const { return EqualsInternal(other); }
-
   R Run(Args... args) const & {
     static_assert(!sizeof(*this),
                   "OnceCallback::Run() may only be invoked on a non-const "
                   "rvalue, i.e. std::move(callback).Run().");
     NOTREACHED();
   }
 
   R Run(Args... args) && {
@@ -64,28 +97,30 @@ class OnceCallback<R(Args...)> : public 
     return f(cb.bind_state_.get(), std::forward<Args>(args)...);
   }
 };
 
 template <typename R, typename... Args>
 class RepeatingCallback<R(Args...)> : public internal::CallbackBaseCopyable {
  public:
   using RunType = R(Args...);
-  using PolymorphicInvoke = R (*)(internal::BindStateBase*, Args&&...);
+  using PolymorphicInvoke = R (*)(internal::BindStateBase*,
+                                  internal::PassingType<Args>...);
 
-  RepeatingCallback() : internal::CallbackBaseCopyable(nullptr) {}
+  constexpr RepeatingCallback() = default;
+  RepeatingCallback(std::nullptr_t) = delete;
 
   explicit RepeatingCallback(internal::BindStateBase* bind_state)
       : internal::CallbackBaseCopyable(bind_state) {}
 
-  // Copyable and movabl.
+  // Copyable and movable.
   RepeatingCallback(const RepeatingCallback&) = default;
   RepeatingCallback& operator=(const RepeatingCallback&) = default;
-  RepeatingCallback(RepeatingCallback&&) = default;
-  RepeatingCallback& operator=(RepeatingCallback&&) = default;
+  RepeatingCallback(RepeatingCallback&&) noexcept = default;
+  RepeatingCallback& operator=(RepeatingCallback&&) noexcept = default;
 
   bool Equals(const RepeatingCallback& other) const {
     return EqualsInternal(other);
   }
 
   R Run(Args... args) const & {
     PolymorphicInvoke f =
         reinterpret_cast<PolymorphicInvoke>(this->polymorphic_invoke());
--- a/security/sandbox/chromium/base/callback_internal.cc
+++ b/security/sandbox/chromium/base/callback_internal.cc
@@ -6,88 +6,96 @@
 
 #include "base/logging.h"
 
 namespace base {
 namespace internal {
 
 namespace {
 
-bool ReturnFalse(const BindStateBase*) {
+bool QueryCancellationTraitsForNonCancellables(
+    const BindStateBase*,
+    BindStateBase::CancellationQueryMode mode) {
+  switch (mode) {
+    case BindStateBase::IS_CANCELLED:
+      return false;
+    case BindStateBase::MAYBE_VALID:
+      return true;
+  }
+  NOTREACHED();
   return false;
 }
 
 }  // namespace
 
 void BindStateBaseRefCountTraits::Destruct(const BindStateBase* bind_state) {
   bind_state->destructor_(bind_state);
 }
 
 BindStateBase::BindStateBase(InvokeFuncStorage polymorphic_invoke,
                              void (*destructor)(const BindStateBase*))
-    : BindStateBase(polymorphic_invoke, destructor, &ReturnFalse) {
-}
+    : BindStateBase(polymorphic_invoke,
+                    destructor,
+                    &QueryCancellationTraitsForNonCancellables) {}
 
-BindStateBase::BindStateBase(InvokeFuncStorage polymorphic_invoke,
-                             void (*destructor)(const BindStateBase*),
-                             bool (*is_cancelled)(const BindStateBase*))
+BindStateBase::BindStateBase(
+    InvokeFuncStorage polymorphic_invoke,
+    void (*destructor)(const BindStateBase*),
+    bool (*query_cancellation_traits)(const BindStateBase*,
+                                      CancellationQueryMode))
     : polymorphic_invoke_(polymorphic_invoke),
       destructor_(destructor),
-      is_cancelled_(is_cancelled) {}
+      query_cancellation_traits_(query_cancellation_traits) {}
 
-CallbackBase::CallbackBase(CallbackBase&& c) = default;
-CallbackBase& CallbackBase::operator=(CallbackBase&& c) = default;
+CallbackBase& CallbackBase::operator=(CallbackBase&& c) noexcept = default;
 CallbackBase::CallbackBase(const CallbackBaseCopyable& c)
     : bind_state_(c.bind_state_) {}
 
 CallbackBase& CallbackBase::operator=(const CallbackBaseCopyable& c) {
   bind_state_ = c.bind_state_;
   return *this;
 }
 
-CallbackBase::CallbackBase(CallbackBaseCopyable&& c)
+CallbackBase::CallbackBase(CallbackBaseCopyable&& c) noexcept
     : bind_state_(std::move(c.bind_state_)) {}
 
-CallbackBase& CallbackBase::operator=(CallbackBaseCopyable&& c) {
+CallbackBase& CallbackBase::operator=(CallbackBaseCopyable&& c) noexcept {
   bind_state_ = std::move(c.bind_state_);
   return *this;
 }
 
 void CallbackBase::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_ = nullptr;
 }
 
 bool CallbackBase::IsCancelled() const {
   DCHECK(bind_state_);
   return bind_state_->IsCancelled();
 }
 
+bool CallbackBase::MaybeValid() const {
+  DCHECK(bind_state_);
+  return bind_state_->MaybeValid();
+}
+
 bool CallbackBase::EqualsInternal(const CallbackBase& other) const {
   return bind_state_ == other.bind_state_;
 }
 
-CallbackBase::CallbackBase(BindStateBase* bind_state)
-    : bind_state_(bind_state ? AdoptRef(bind_state) : nullptr) {
-  DCHECK(!bind_state_.get() || bind_state_->HasOneRef());
-}
+CallbackBase::~CallbackBase() = default;
 
-CallbackBase::~CallbackBase() {}
-
-CallbackBaseCopyable::CallbackBaseCopyable(const CallbackBaseCopyable& c)
-    : CallbackBase(nullptr) {
+CallbackBaseCopyable::CallbackBaseCopyable(const CallbackBaseCopyable& c) {
   bind_state_ = c.bind_state_;
 }
 
-CallbackBaseCopyable::CallbackBaseCopyable(CallbackBaseCopyable&& c) = default;
-
 CallbackBaseCopyable& CallbackBaseCopyable::operator=(
     const CallbackBaseCopyable& c) {
   bind_state_ = c.bind_state_;
   return *this;
 }
 
 CallbackBaseCopyable& CallbackBaseCopyable::operator=(
-    CallbackBaseCopyable&& c) = default;
+    CallbackBaseCopyable&& c) noexcept = default;
 
 }  // namespace internal
 }  // namespace base
--- a/security/sandbox/chromium/base/callback_internal.h
+++ b/security/sandbox/chromium/base/callback_internal.h
@@ -26,129 +26,159 @@ class BindStateBase;
 
 template <typename Functor, typename... BoundArgs>
 struct BindState;
 
 struct BindStateBaseRefCountTraits {
   static void Destruct(const BindStateBase*);
 };
 
+template <typename T>
+using PassingType = std::conditional_t<std::is_scalar<T>::value, T, T&&>;
+
 // 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 BASE_EXPORT BindStateBase
     : public RefCountedThreadSafe<BindStateBase, BindStateBaseRefCountTraits> {
  public:
   REQUIRE_ADOPTION_FOR_REFCOUNTED_TYPE();
 
+  enum CancellationQueryMode {
+    IS_CANCELLED,
+    MAYBE_VALID,
+  };
+
   using InvokeFuncStorage = void(*)();
 
  private:
   BindStateBase(InvokeFuncStorage polymorphic_invoke,
                 void (*destructor)(const BindStateBase*));
   BindStateBase(InvokeFuncStorage polymorphic_invoke,
                 void (*destructor)(const BindStateBase*),
-                bool (*is_cancelled)(const BindStateBase*));
+                bool (*query_cancellation_traits)(const BindStateBase*,
+                                                  CancellationQueryMode mode));
 
   ~BindStateBase() = default;
 
   friend struct BindStateBaseRefCountTraits;
   friend class RefCountedThreadSafe<BindStateBase, BindStateBaseRefCountTraits>;
 
   friend class CallbackBase;
   friend class CallbackBaseCopyable;
 
   // Whitelist subclasses that access the destructor of BindStateBase.
   template <typename Functor, typename... BoundArgs>
   friend struct BindState;
   friend struct ::base::FakeBindState;
 
   bool IsCancelled() const {
-    return is_cancelled_(this);
+    return query_cancellation_traits_(this, IS_CANCELLED);
+  }
+
+  bool MaybeValid() const {
+    return query_cancellation_traits_(this, MAYBE_VALID);
   }
 
   // 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_;
 
   // Pointer to a function that will properly destroy |this|.
   void (*destructor_)(const BindStateBase*);
-  bool (*is_cancelled_)(const BindStateBase*);
+  bool (*query_cancellation_traits_)(const BindStateBase*,
+                                     CancellationQueryMode mode);
 
   DISALLOW_COPY_AND_ASSIGN(BindStateBase);
 };
 
 // Holds the Callback methods that don't require specialization to reduce
 // template bloat.
 // CallbackBase<MoveOnly> is a direct base class of MoveOnly callbacks, and
 // CallbackBase<Copyable> uses CallbackBase<MoveOnly> for its implementation.
 class BASE_EXPORT CallbackBase {
  public:
-  CallbackBase(CallbackBase&& c);
-  CallbackBase& operator=(CallbackBase&& c);
+  inline CallbackBase(CallbackBase&& c) noexcept;
+  CallbackBase& operator=(CallbackBase&& c) noexcept;
 
   explicit CallbackBase(const CallbackBaseCopyable& c);
   CallbackBase& operator=(const CallbackBaseCopyable& c);
 
-  explicit CallbackBase(CallbackBaseCopyable&& c);
-  CallbackBase& operator=(CallbackBaseCopyable&& c);
+  explicit CallbackBase(CallbackBaseCopyable&& c) noexcept;
+  CallbackBase& operator=(CallbackBaseCopyable&& c) noexcept;
 
   // Returns true if Callback is null (doesn't refer to anything).
   bool is_null() const { return !bind_state_; }
   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.
+  //
+  // Must be called on the Callback's destination sequence.
   bool IsCancelled() const;
 
+  // If this returns false, the callback invocation will be a nop due to a
+  // cancellation. This may(!) still return true, even on a cancelled callback.
+  //
+  // This function is thread-safe.
+  bool MaybeValid() const;
+
   // Returns the Callback into an uninitialized state.
   void Reset();
 
  protected:
   using InvokeFuncStorage = BindStateBase::InvokeFuncStorage;
 
   // Returns true if this callback equals |other|. |other| may be null.
   bool EqualsInternal(const CallbackBase& other) const;
 
+  constexpr inline CallbackBase();
+
   // Allow initializing of |bind_state_| via the constructor to avoid default
   // initialization of the scoped_refptr.
-  explicit CallbackBase(BindStateBase* bind_state);
+  explicit inline 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_;
 };
 
+constexpr CallbackBase::CallbackBase() = default;
+CallbackBase::CallbackBase(CallbackBase&&) noexcept = default;
+CallbackBase::CallbackBase(BindStateBase* bind_state)
+    : bind_state_(AdoptRef(bind_state)) {}
+
 // CallbackBase<Copyable> is a direct base class of Copyable Callbacks.
 class BASE_EXPORT CallbackBaseCopyable : public CallbackBase {
  public:
   CallbackBaseCopyable(const CallbackBaseCopyable& c);
-  CallbackBaseCopyable(CallbackBaseCopyable&& c);
+  CallbackBaseCopyable(CallbackBaseCopyable&& c) noexcept = default;
   CallbackBaseCopyable& operator=(const CallbackBaseCopyable& c);
-  CallbackBaseCopyable& operator=(CallbackBaseCopyable&& c);
+  CallbackBaseCopyable& operator=(CallbackBaseCopyable&& c) noexcept;
 
  protected:
+  constexpr CallbackBaseCopyable() = default;
   explicit CallbackBaseCopyable(BindStateBase* bind_state)
       : CallbackBase(bind_state) {}
-  ~CallbackBaseCopyable() {}
+  ~CallbackBaseCopyable() = default;
 };
 
 }  // 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
@@ -4,62 +4,62 @@
 
 #ifndef BASE_COMPILER_SPECIFIC_H_
 #define BASE_COMPILER_SPECIFIC_H_
 
 #include "build/build_config.h"
 
 #if defined(COMPILER_MSVC)
 
-// For _Printf_format_string_.
-#include <sal.h>
-
 // Macros for suppressing and disabling warnings on MSVC.
 //
 // Warning numbers are enumerated at:
 // http://msdn.microsoft.com/en-us/library/8x5x43k7(VS.80).aspx
 //
 // The warning pragma:
 // http://msdn.microsoft.com/en-us/library/2c8f766e(VS.80).aspx
 //
 // Using __pragma instead of #pragma inside macros:
 // http://msdn.microsoft.com/en-us/library/d9x1s805.aspx
 
-// MSVC_SUPPRESS_WARNING disables warning |n| for the remainder of the line and
-// for the next line of the source file.
-#define MSVC_SUPPRESS_WARNING(n) __pragma(warning(suppress:n))
-
 // MSVC_PUSH_DISABLE_WARNING pushes |n| onto a stack of warnings to be disabled.
 // The warning remains disabled until popped by MSVC_POP_WARNING.
 #define MSVC_PUSH_DISABLE_WARNING(n) __pragma(warning(push)) \
                                      __pragma(warning(disable:n))
 
-// MSVC_PUSH_WARNING_LEVEL pushes |n| as the global warning level.  The level
-// remains in effect until popped by MSVC_POP_WARNING().  Use 0 to disable all
-// warnings.
-#define MSVC_PUSH_WARNING_LEVEL(n) __pragma(warning(push, n))
-
 // Pop effects of innermost MSVC_PUSH_* macro.
 #define MSVC_POP_WARNING() __pragma(warning(pop))
 
-#define MSVC_DISABLE_OPTIMIZE() __pragma(optimize("", off))
-#define MSVC_ENABLE_OPTIMIZE() __pragma(optimize("", on))
-
 #else  // Not MSVC
 
-#define _Printf_format_string_
-#define MSVC_SUPPRESS_WARNING(n)
 #define MSVC_PUSH_DISABLE_WARNING(n)
-#define MSVC_PUSH_WARNING_LEVEL(n)
 #define MSVC_POP_WARNING()
 #define MSVC_DISABLE_OPTIMIZE()
 #define MSVC_ENABLE_OPTIMIZE()
 
 #endif  // COMPILER_MSVC
 
+// These macros can be helpful when investigating compiler bugs or when
+// investigating issues in local optimized builds, by temporarily disabling
+// optimizations for a single function or file. These macros should never be
+// used to permanently work around compiler bugs or other mysteries, and should
+// not be used in landed changes.
+#if !defined(OFFICIAL_BUILD)
+#if defined(__clang__)
+#define DISABLE_OPTIMIZE() __pragma(clang optimize off)
+#define ENABLE_OPTIMIZE() __pragma(clang optimize on)
+#elif defined(COMPILER_MSVC)
+#define DISABLE_OPTIMIZE() __pragma(optimize("", off))
+#define ENABLE_OPTIMIZE() __pragma(optimize("", on))
+#else
+// These macros are not currently available for other compiler options.
+#endif
+// These macros are not available in official builds.
+#endif  // !defined(OFFICIAL_BUILD)
+
 // Annotate a variable indicating it's ok if the variable is not used.
 // (Typically used to silence a compiler warning when the assignment
 // is important for some other reason.)
 // Use like:
 //   int x = ...;
 //   ALLOW_UNUSED_LOCAL(x);
 #define ALLOW_UNUSED_LOCAL(x) (void)x
 
@@ -78,19 +78,19 @@
 #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)
+#if defined(COMPILER_GCC) && defined(NDEBUG)
 #define ALWAYS_INLINE inline __attribute__((__always_inline__))
-#elif COMPILER_MSVC && defined(NDEBUG)
+#elif defined(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 { ... }
@@ -129,16 +129,17 @@
 #define WARN_UNUSED_RESULT
 #endif
 
 // Tell the compiler a function is using a printf-style format string.
 // |format_param| is the one-based index of the format string parameter;
 // |dots_param| is the one-based index of the "..." parameter.
 // For v*printf functions (which take a va_list), pass 0 for dots_param.
 // (This is undocumented but matches what the system C headers do.)
+// For member functions, the implicit this parameter counts as index 1.
 #if defined(COMPILER_GCC) || defined(__clang__)
 #define PRINTF_FORMAT(format_param, dots_param) \
     __attribute__((format(printf, format_param, dots_param)))
 #else
 #define PRINTF_FORMAT(format_param, dots_param)
 #endif
 
 // WPRINTF_FORMAT is the same, but for wide format strings.
@@ -193,32 +194,48 @@
 #define CDECL __cdecl
 #else  // defined(OS_WIN)
 #define CDECL
 #endif  // defined(OS_WIN)
 #endif  // !defined(CDECL)
 
 // Macro for hinting that an expression is likely to be false.
 #if !defined(UNLIKELY)
-#if defined(COMPILER_GCC)
+#if defined(COMPILER_GCC) || defined(__clang__)
 #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)
+#if defined(COMPILER_GCC) || defined(__clang__)
 #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
 
+// Macro for telling -Wimplicit-fallthrough that a fallthrough is intentional.
+#if defined(__clang__)
+#define FALLTHROUGH [[clang::fallthrough]]
+#else
+#define FALLTHROUGH
+#endif
+
+#if defined(COMPILER_GCC)
+#define PRETTY_FUNCTION __PRETTY_FUNCTION__
+#elif defined(COMPILER_MSVC)
+#define PRETTY_FUNCTION __FUNCSIG__
+#else
+// See https://en.cppreference.com/w/c/language/function_definition#func
+#define PRETTY_FUNCTION __func__
+#endif
+
 #endif  // BASE_COMPILER_SPECIFIC_H_
--- a/security/sandbox/chromium/base/containers/adapters.h
+++ b/security/sandbox/chromium/base/containers/adapters.h
@@ -3,60 +3,42 @@
 // found in the LICENSE file.
 
 #ifndef BASE_CONTAINERS_ADAPTERS_H_
 #define BASE_CONTAINERS_ADAPTERS_H_
 
 #include <stddef.h>
 
 #include <iterator>
+#include <utility>
 
 #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());
+  using Iterator = decltype(std::rbegin(std::declval<T&>()));
 
   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(); }
+  Iterator begin() const { return std::rbegin(t_); }
+  Iterator end() const { return std::rend(t_); }
 
  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 = ...;
new file mode 100644
--- /dev/null
+++ b/security/sandbox/chromium/base/containers/circular_deque.h
@@ -0,0 +1,1111 @@
+// Copyright 2017 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_CIRCULAR_DEQUE_H_
+#define BASE_CONTAINERS_CIRCULAR_DEQUE_H_
+
+#include <algorithm>
+#include <cstddef>
+#include <iterator>
+#include <type_traits>
+#include <utility>
+
+#include "base/containers/vector_buffer.h"
+#include "base/logging.h"
+#include "base/macros.h"
+#include "base/template_util.h"
+
+// base::circular_deque is similar to std::deque. Unlike std::deque, the
+// storage is provided in a flat circular buffer conceptually similar to a
+// vector. The beginning and end will wrap around as necessary so that
+// pushes and pops will be constant time as long as a capacity expansion is
+// not required.
+//
+// The API should be identical to std::deque with the following differences:
+//
+//  - ITERATORS ARE NOT STABLE. Mutating the container will invalidate all
+//    iterators.
+//
+//  - Insertions may resize the vector and so are not constant time (std::deque
+//    guarantees constant time for insertions at the ends).
+//
+//  - Container-wide comparisons are not implemented. If you want to compare
+//    two containers, use an algorithm so the expensive iteration is explicit.
+//
+// If you want a similar container with only a queue API, use base::queue in
+// base/containers/queue.h.
+//
+// Constructors:
+//   circular_deque();
+//   circular_deque(size_t count);
+//   circular_deque(size_t count, const T& value);
+//   circular_deque(InputIterator first, InputIterator last);
+//   circular_deque(const circular_deque&);
+//   circular_deque(circular_deque&&);
+//   circular_deque(std::initializer_list<value_type>);
+//
+// Assignment functions:
+//   circular_deque& operator=(const circular_deque&);
+//   circular_deque& operator=(circular_deque&&);
+//   circular_deque& operator=(std::initializer_list<T>);
+//   void assign(size_t count, const T& value);
+//   void assign(InputIterator first, InputIterator last);
+//   void assign(std::initializer_list<T> value);
+//
+// Random accessors:
+//   T& at(size_t);
+//   const T& at(size_t) const;
+//   T& operator[](size_t);
+//   const T& operator[](size_t) const;
+//
+// End accessors:
+//   T& front();
+//   const T& front() const;
+//   T& back();
+//   const T& back() const;
+//
+// Iterator functions:
+//   iterator               begin();
+//   const_iterator         begin() const;
+//   const_iterator         cbegin() const;
+//   iterator               end();
+//   const_iterator         end() const;
+//   const_iterator         cend() const;
+//   reverse_iterator       rbegin();
+//   const_reverse_iterator rbegin() const;
+//   const_reverse_iterator crbegin() const;
+//   reverse_iterator       rend();
+//   const_reverse_iterator rend() const;
+//   const_reverse_iterator crend() const;
+//
+// Memory management:
+//   void reserve(size_t);  // SEE IMPLEMENTATION FOR SOME GOTCHAS.
+//   size_t capacity() const;
+//   void shrink_to_fit();
+//
+// Size management:
+//   void clear();
+//   bool empty() const;
+//   size_t size() const;
+//   void resize(size_t);
+//   void resize(size_t count, const T& value);
+//
+// Positional insert and erase:
+//   void insert(const_iterator pos, size_type count, const T& value);
+//   void insert(const_iterator pos,
+//               InputIterator first, InputIterator last);
+//   iterator insert(const_iterator pos, const T& value);
+//   iterator insert(const_iterator pos, T&& value);
+//   iterator emplace(const_iterator pos, Args&&... args);
+//   iterator erase(const_iterator pos);
+//   iterator erase(const_iterator first, const_iterator last);
+//
+// End insert and erase:
+//   void push_front(const T&);
+//   void push_front(T&&);
+//   void push_back(const T&);
+//   void push_back(T&&);
+//   T& emplace_front(Args&&...);
+//   T& emplace_back(Args&&...);
+//   void pop_front();
+//   void pop_back();
+//
+// General:
+//   void swap(circular_deque&);
+
+namespace base {
+
+template <class T>
+class circular_deque;
+
+namespace internal {
+
+// Start allocating nonempty buffers with this many entries. This is the
+// external capacity so the internal buffer will be one larger (= 4) which is
+// more even for the allocator. See the descriptions of internal vs. external
+// capacity on the comment above the buffer_ variable below.
+constexpr size_t kCircularBufferInitialCapacity = 3;
+
+template <typename T>
+class circular_deque_const_iterator {
+ public:
+  using difference_type = std::ptrdiff_t;
+  using value_type = T;
+  using pointer = const T*;
+  using reference = const T&;
+  using iterator_category = std::random_access_iterator_tag;
+
+  circular_deque_const_iterator() : parent_deque_(nullptr), index_(0) {
+#if DCHECK_IS_ON()
+    created_generation_ = 0;
+#endif  // DCHECK_IS_ON()
+  }
+
+  // Dereferencing.
+  const T& operator*() const {
+    CheckUnstableUsage();
+    parent_deque_->CheckValidIndex(index_);
+    return parent_deque_->buffer_[index_];
+  }
+  const T* operator->() const {
+    CheckUnstableUsage();
+    parent_deque_->CheckValidIndex(index_);
+    return &parent_deque_->buffer_[index_];
+  }
+  const value_type& operator[](difference_type i) const { return *(*this + i); }
+
+  // Increment and decrement.
+  circular_deque_const_iterator& operator++() {
+    Increment();
+    return *this;
+  }
+  circular_deque_const_iterator operator++(int) {
+    circular_deque_const_iterator ret = *this;
+    Increment();
+    return ret;
+  }
+  circular_deque_const_iterator& operator--() {
+    Decrement();
+    return *this;
+  }
+  circular_deque_const_iterator operator--(int) {
+    circular_deque_const_iterator ret = *this;
+    Decrement();
+    return ret;
+  }
+
+  // Random access mutation.
+  friend circular_deque_const_iterator operator+(
+      const circular_deque_const_iterator& iter,
+      difference_type offset) {
+    circular_deque_const_iterator ret = iter;
+    ret.Add(offset);
+    return ret;
+  }
+  circular_deque_const_iterator& operator+=(difference_type offset) {
+    Add(offset);
+    return *this;
+  }
+  friend circular_deque_const_iterator operator-(
+      const circular_deque_const_iterator& iter,
+      difference_type offset) {
+    circular_deque_const_iterator ret = iter;
+    ret.Add(-offset);
+    return ret;
+  }
+  circular_deque_const_iterator& operator-=(difference_type offset) {
+    Add(-offset);
+    return *this;
+  }
+
+  friend std::ptrdiff_t operator-(const circular_deque_const_iterator& lhs,
+                                  const circular_deque_const_iterator& rhs) {
+    lhs.CheckComparable(rhs);
+    return lhs.OffsetFromBegin() - rhs.OffsetFromBegin();
+  }
+
+  // Comparisons.
+  friend bool operator==(const circular_deque_const_iterator& lhs,
+                         const circular_deque_const_iterator& rhs) {
+    lhs.CheckComparable(rhs);
+    return lhs.index_ == rhs.index_;
+  }
+  friend bool operator!=(const circular_deque_const_iterator& lhs,
+                         const circular_deque_const_iterator& rhs) {
+    return !(lhs == rhs);
+  }
+  friend bool operator<(const circular_deque_const_iterator& lhs,
+                        const circular_deque_const_iterator& rhs) {
+    lhs.CheckComparable(rhs);
+    return lhs.OffsetFromBegin() < rhs.OffsetFromBegin();
+  }
+  friend bool operator<=(const circular_deque_const_iterator& lhs,
+                         const circular_deque_const_iterator& rhs) {
+    return !(lhs > rhs);
+  }
+  friend bool operator>(const circular_deque_const_iterator& lhs,
+                        const circular_deque_const_iterator& rhs) {
+    lhs.CheckComparable(rhs);
+    return lhs.OffsetFromBegin() > rhs.OffsetFromBegin();
+  }
+  friend bool operator>=(const circular_deque_const_iterator& lhs,
+                         const circular_deque_const_iterator& rhs) {
+    return !(lhs < rhs);
+  }
+
+ protected:
+  friend class circular_deque<T>;
+
+  circular_deque_const_iterator(const circular_deque<T>* parent, size_t index)
+      : parent_deque_(parent), index_(index) {
+#if DCHECK_IS_ON()
+    created_generation_ = parent->generation_;
+#endif  // DCHECK_IS_ON()
+  }
+
+  // Returns the offset from the beginning index of the buffer to the current
+  // item.
+  size_t OffsetFromBegin() const {
+    if (index_ >= parent_deque_->begin_)
+      return index_ - parent_deque_->begin_;  // On the same side as begin.
+    return parent_deque_->buffer_.capacity() - parent_deque_->begin_ + index_;
+  }
+
+  // Most uses will be ++ and -- so use a simplified implementation.
+  void Increment() {
+    CheckUnstableUsage();
+    parent_deque_->CheckValidIndex(index_);
+    index_++;
+    if (index_ == parent_deque_->buffer_.capacity())
+      index_ = 0;
+  }
+  void Decrement() {
+    CheckUnstableUsage();
+    parent_deque_->CheckValidIndexOrEnd(index_);
+    if (index_ == 0)
+      index_ = parent_deque_->buffer_.capacity() - 1;
+    else
+      index_--;
+  }
+  void Add(difference_type delta) {
+    CheckUnstableUsage();
+#if DCHECK_IS_ON()
+    if (delta <= 0)
+      parent_deque_->CheckValidIndexOrEnd(index_);
+    else
+      parent_deque_->CheckValidIndex(index_);
+#endif
+    // It should be valid to add 0 to any iterator, even if the container is
+    // empty and the iterator points to end(). The modulo below will divide
+    // by 0 if the buffer capacity is empty, so it's important to check for
+    // this case explicitly.
+    if (delta == 0)
+      return;
+
+    difference_type new_offset = OffsetFromBegin() + delta;
+    DCHECK(new_offset >= 0 &&
+           new_offset <= static_cast<difference_type>(parent_deque_->size()));
+    index_ = (new_offset + parent_deque_->begin_) %
+             parent_deque_->buffer_.capacity();
+  }
+
+#if DCHECK_IS_ON()
+  void CheckUnstableUsage() const {
+    DCHECK(parent_deque_);
+    // Since circular_deque doesn't guarantee stability, any attempt to
+    // dereference this iterator after a mutation (i.e. the generation doesn't
+    // match the original) in the container is illegal.
+    DCHECK_EQ(created_generation_, parent_deque_->generation_)
+        << "circular_deque iterator dereferenced after mutation.";
+  }
+  void CheckComparable(const circular_deque_const_iterator& other) const {
+    DCHECK_EQ(parent_deque_, other.parent_deque_);
+    // Since circular_deque doesn't guarantee stability, two iterators that
+    // are compared must have been generated without mutating the container.
+    // If this fires, the container was mutated between generating the two
+    // iterators being compared.
+    DCHECK_EQ(created_generation_, other.created_generation_);
+  }
+#else
+  inline void CheckUnstableUsage() const {}
+  inline void CheckComparable(const circular_deque_const_iterator&) const {}
+#endif  // DCHECK_IS_ON()
+
+  const circular_deque<T>* parent_deque_;
+  size_t index_;
+
+#if DCHECK_IS_ON()
+  // The generation of the parent deque when this iterator was created. The
+  // container will update the generation for every modification so we can
+  // test if the container was modified by comparing them.
+  uint64_t created_generation_;
+#endif  // DCHECK_IS_ON()
+};
+
+template <typename T>
+class circular_deque_iterator : public circular_deque_const_iterator<T> {
+  using base = circular_deque_const_iterator<T>;
+
+ public:
+  friend class circular_deque<T>;
+
+  using difference_type = std::ptrdiff_t;
+  using value_type = T;
+  using pointer = T*;
+  using reference = T&;
+  using iterator_category = std::random_access_iterator_tag;
+
+  // Expose the base class' constructor.
+  circular_deque_iterator() : circular_deque_const_iterator<T>() {}
+
+  // Dereferencing.
+  T& operator*() const { return const_cast<T&>(base::operator*()); }
+  T* operator->() const { return const_cast<T*>(base::operator->()); }
+  T& operator[](difference_type i) {
+    return const_cast<T&>(base::operator[](i));
+  }
+
+  // Random access mutation.
+  friend circular_deque_iterator operator+(const circular_deque_iterator& iter,
+                                           difference_type offset) {
+    circular_deque_iterator ret = iter;
+    ret.Add(offset);
+    return ret;
+  }
+  circular_deque_iterator& operator+=(difference_type offset) {
+    base::Add(offset);
+    return *this;
+  }
+  friend circular_deque_iterator operator-(const circular_deque_iterator& iter,
+                                           difference_type offset) {
+    circular_deque_iterator ret = iter;
+    ret.Add(-offset);
+    return ret;
+  }